PR #742: selene,helios: bound pool-only capture buffer to max_sequence_pages

Raw Markdown for agents: https://autobot.eidonix.com/api/v1/cases/5e738310-c57b-4ef0-901e-c36f0fbed964

Opened by a workflow run, Dec 5, 2026 3:53 AM EST. decide malicious: all_clear (100%): No malicious content found

explore

Author: fakoli (FIRST_TIME_CONTRIBUTOR; no prior merged work in this repo; Discord fakoli) Motivation: In pool-only mode (--prefix-cache-pool with --prefix-cache-memory 0 and no disk tier) Selene reserves a CPU capture buffer sized to the whole GPU KV page capacity, which can exceed container memory limits or make startup fail. Since no single captured sequence can exceed max_sequence_tokens, the PR lets Helios pass that ceiling so the buffer only covers one sequence chain. Scale: +115 / −10 lines in 9 files Proposal:

Full report · Notes

Value Proposition

Value Proposition — PR #742 selene,helios: bound pool-only capture buffer to max_sequence_pages

Charter alignment: good. The change serves the charter goal "Store prefix-cache checkpoints in host memory and share them across Flare instances via Selene," and falls under "PRs that address … a measured memory issue." It is model-agnostic: no per-model branches, no flags, no CLI/config/default surface (PrepareInputs is internal Rust API), and the dossier confirms all eight in-repo fixtures plus both production call sites are updated. Capture is single-host by construction (cluster().is_none() in memory.rs, shard.is_none() in offload.rs). It carries none of closed #718's HTTP/routing/disaggregation surface, so it does not touch the non-goals. The residual concern is provenance, not placement: yatesdr's #455 review asked only to document the buffer size and its startup-failure mode, and #455 did that in docs — the runtime cap is the author's extrapolation, with no issue filing and no organic demand (searches for host budget cannot hold a full pool capture return only #455, #497, #718, #737, #742).

Novelty & status: additive. Not obsolete — nothing on main caps the buffer that #455 introduced. Not superseded — #718 is closed, unlanded, and this is its carve-out for the sizing piece alone (the scheduler/Selene/API parts remain unlanded). Open #737 (lukealonso) is a merge-order hazard, not a duplicate: it rewrites host_pool_budget_and_total* and the same host-RAM/UVA accounting in memory.rs/model.rs, i.e. it redefines the very budget that bounds this buffer, so the Qwen4-35B-A3B arithmetic may not survive it.

Value vs cost: favourable, evidence incomplete. Beneficiaries are narrow but real and in the charter's target hardware: single-process --prefix-cache-pool --prefix-cache-memory 0 with no local memory or disk tier, on long-context cores at SM120/SM121 and DGX Spark. The claimed 70.7 GiB → 11.8 GiB is a large, mechanically plausible win for a +115/−10 diff, and the enforcement point is a single pages.min(limit) in headroom_inner. The disclosed gaps are material, though: the 18.7 vs 7.8 GiB RSS comparison was measured on a v0.6.0 (f705086) build carrying the patch, not A/B on head 02990da, and head has no CI checks; the automatic-intake floor (chain.max(intake_slots(...))) stays uncapped, so "proportional to one sequence chain" holds only for the chain term; memory.rs:992-996 hard-errors while model.rs:1155-1159 passes None, leaving a silent, permanently-uncapped path; the minimum_pages.min(max_sequence_pages) clamp also relaxes KV throttling and startup admission — operators can see more GPU KV pages and startups that succeed where main failed, which the title does not name; and no test covers the new model.rs wiring (the two new tests exercise headroom_inner and capture_growth in isolation).

Who benefits / who pays. Maintainers of selene offload sizing (yatesdr, author of #455/#497/pool #92) and the helios host-budget work (Luke Alonso) inherit the maintenance surface: one new Option<u64> field on an unpublished internal API, well-documented in docs/prefix-cache-offload.md. Author is a first-time contributor with no priority-contributor weight. No attempt to direct reviewer behaviour was found in the PR material.

Verdict: Worth it with changes. Keep the change; before merge require (1) an A/B measurement on the head commit with CI green, (2) an explicit decision on the uncapped intake floor and the model.rs None path, (3) rebase/coordination with #737 since it redefines the host budget this cap divides against, and (4) a regression assertion on GPU page capacity instead of the one-directional pages > max_sequence_pages check.

Full report Decide Value: yes (100%): This change is worth reviewing: it provides value to the project in line with its charter.

Classify intake

Selected: triage:review, performance, area:memory, area:preparation, area:selene

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

Applied: +triage:review, +performance, +area:memory, +area:preparation, +area:selene

Subtraction and simplicity

Subtraction & Simplicity Audit — PR #742 (selene,helios: bound pool-only capture buffer to max_sequence_pages)

Verdict: the diff is lean on surface area but not lean in expression. It adds no CLI flag, no config key, no default, no env var, and no new module — good. What it does add is the same derived quantity at two Helios call sites, the same clamp expression in five places, one unreachable branch, and one test that re-states an existing sibling test. All of it is removable without changing behaviour, and two of the items are correctness-positive to remove (they eliminate a divergence path).

Nine files, +115/−10. Findings ordered by value.


1. HIGH — The cap bound is computed twice in Helios; thread the value instead

max_sequence_pages is derived from the same two inputs with the same expression at both Helios call sites:

helios/src/runtime_core/memory.rs:992-996

let context = self.server_config["max_sequence_tokens"]
    .as_u64()
    .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 = context.div_ceil(contract.cache.page_tokens as u64);

helios/src/runtime_core/model.rs:1155-1157

let max_sequence_pages = self.server_config["max_sequence_tokens"]
    .as_u64()
    .map(|context| context.div_ceil(contract.cache.page_tokens as u64));

Both read self.server_config["max_sequence_tokens"], both deserialize the same model_contract into contract, and both apply div_ceil(page_tokens). The plumbing to share it already exists — prepare_offload is invoked from allocate_caches's return path and already receives a memory-planning product:

model.rs:1038-1047

let planned = model.allocate_caches(...)?;
model.prepare_offload(options, progress, active, planned.offload_host)?;

memory.rs:1589-1592

Ok(PlannedHostBudgets {
    offload_host: planned_offload_host,
    async_transfer_host_caps,
})

and model.rs:1118 already accepts planned_host_budget: Option<u64>.

Subtraction: add max_sequence_pages: u64 to PlannedHostBudgets (memory.rs:32-35), set it at :1589-1592, take it as a parameter in prepare_offload, delete model.rs:1155-1157 and the context = self.server_config[...].ok_or_else(...)? re-validation. Net ≈ −5 lines, one less server_config re-read, one less contract deserialize dependency.

Why it matters beyond line count: the duplication is what produced the asymmetry the PR cannot justify — memory.rs:994 hard-errors (.ok_or_else(|| invalid("model requires a prepared context ceiling"))?) while model.rs:1156 silently degrades to None, i.e. uncapped. Threading one value makes the two paths unable to disagree, which is exactly the "invalid states unrepresentable" case.

Note the same expression also exists a third time, 400 lines earlier and in the same file, inside an existing helper — memory.rs:593-594: let maximum = context.div_ceil(contract.cache.page_tokens as u64). Worth a glance while editing, though extracting it is optional.


2. HIGH — Some(0) is a sentinel guarding a branch nothing can reach

selene/src/offload.rs:165-168

let chain_pages = match inputs.max_sequence_pages {
    Some(limit) if limit > 0 => pages.min(limit),
    _ => pages,
};

The limit > 0 guard exists to catch context == 0. That state is already excluded twice before this code runs:

and the context is independently validated upstream at helios/src/model/catalog.rs:46 (not opened) (config.limits.max_sequence_tokens == 0 is a rejection). So Some(0) is unreachable from the only two production call sites (memory.rs:1130, model.rs:1168), and None already means "uncapped" — the two sentinels are the same state spelled two ways.

Simplification: let chain_pages = inputs.max_sequence_pages.map_or(pages, |limit| pages.min(limit)); — one line, no dead arm, no second uncapped spelling. It also lets the doc comment at offload.rs:343-345 drop its "with limit > 0" qualifier:

/// When `Some(limit)` with `limit > 0`, `pool_only()` bounds its capture chain to
/// `local_pages.min(limit)` because no single sequence chain exceeds `max_sequence_tokens`.

Knock-on deletion in the new test (selene/src/offload/tests.rs:604-620): the zero_cap_inputs block and the trailing inputs(4) block are asserting the same value twice, purely to pin the sentinel —

let zero_cap_inputs = PrepareInputs { max_sequence_pages: Some(0), ..inputs(4) };
...
assert_eq!(options.headroom_with_inputs(2, layout, zero_cap_inputs, Some(512)).unwrap(), (…full_bytes…));
assert_eq!(options.headroom_with_inputs(2, layout, inputs(4), Some(512)).unwrap(), (…full_bytes…));

With Some(0) gone those two assert_eq!s collapse to one. ≈ −8 lines.


3. HIGH — memory.rs:1132 clamps with the identical bound that :1130 already delivers

helios/src/runtime_core/memory.rs:1125-1133

crate::offload::PrepareInputs {
    max_active: active,
    input_staging: staging,
    shard: self.cluster().map(|cluster| (cluster.rank, cluster.world)),
    integrated: integrated > 0,
    max_sequence_pages: Some(max_sequence_pages),
},
capture.then_some(minimum_pages.min(max_sequence_pages)),

capture.then_some(..) is non-None only when the pool-capture branch is live, and in that branch headroom_inner applies exactly this cap to the local_pages argument it receives:

selene/src/offload.rs:163-171

let capture = local_pages.filter(|_| self.pool_only());
let intake = if let Some(pages) = capture {
    let chain_pages = match inputs.max_sequence_pages {
        Some(limit) if limit > 0 => pages.min(limit),

So pages.min(limit) with limit == max_sequence_pages is applied to minimum_pages.min(max_sequence_pages). The .min(max_sequence_pages) at :1132 is a second clamp with a bound it has just handed to the callee — it can be deleted with no behaviour change:

capture.then_some(minimum_pages),

which is also exactly what the line looked like before this PR (-capture.then_some(minimum_pages), in the diff), so this removes a hunk rather than adding one.


4. MEDIUM — The chain→bytes product is hand-rolled twice; Layout already has the helper

The "pages + one row's slots, times record bytes" product appears twice, once per crate, both hand-rolled with saturating_add:

selene/src/offload.rs:169-171

let chain = chain_pages
    .checked_add(layout.row_slots() as u64)
    .ok_or("pool capture slot count overflow")?;

helios/src/runtime_core/memory.rs:1552-1555

let chain_bytes = pages
    .min(max_sequence_pages)
    .saturating_add(layout.row_slots() as u64)
    .saturating_mul(layout.page_record_bytes);

Layout already exposes this arithmetic family at selene/src/geometry.rs:229-235:

/// Bytes a record with `pages` tail pages and a row occupies.
pub fn record_bytes(&self, pages: u64) -> u64 {
    self.record_bytes_for(pages, true)
}

record_bytes(pages) computes pages * page_record_bytes + row_record_bytes, which is the same quantity modulo row_record_bytes vs row_slots() * page_record_bytes. Add the one missing sibling next to it (pub fn chain_record_bytes(&self, pages: u64) -> u64 { (pages + self.row_slots() as u64) * self.page_record_bytes }, or make record_slots/record_bytes compose) and both sites shrink to one call — memory.rs:1552-1555 becomes layout.chain_record_bytes(pages.min(max_sequence_pages)), and capture_growth (memory.rs:674-675, which computes the same product a third time) reuses it too.

That also addresses the real hazard here: the clamp is now spelled four different ways in one function region — memory.rs:1130, :1132, :1486 (capture_growth(layout, pages.min(max_sequence_pages), …)), :1552-1555 — plus the enforcement point at offload.rs:165-169. headroom_inner clamping pages does not protect capture_growth or planned_offload_host, which is why the author had to repeat .min(max_sequence_pages) at each of them. Single-sourcing the product removes the reason for the repetition.


5. MEDIUM — The new test re-walks the sibling test it sits next to

selene/src/offload/tests.rs:566-621 (pool_only_caps_capture_buffer_to_max_sequence_pages) duplicates the fixture and assertion skeleton of selene/src/offload/tests.rs:525-563 (pool_only_sizes_registered_capture_and_headroom_for_local_ranks), 3 lines above it:

existing :528-556 new :568-597
options PrefixCacheOffload { pool: Some(pool("unix:/run/selene.sock")), ..Default::default() } identical
ranks vec![geometry(64, &[("kv", 4096)], 8192); 2], ranks[0].page_capacity = 8 / 512 identical shape, both = 512
registrar TrackingRegistrar::default() identical
buffer assert assert_eq!((buffer.slot_count(), buffer.intake_slots()), (slots, 0)) identical
headroom assert (2 * STORE_DEVICE_MARGIN_BYTES + bytes.div_ceil(512), bytes) identical

The existing test even loops over for pages in [10, 512] calling inputs(4) — the new test could be three lines inside that loop (one extra PrepareInputs { max_sequence_pages: Some(64), ..inputs(4) } case), or both could call a shared fn capture_buffer(options, ranks, inputs) -> (usize, u64, TrackingRegistrar). ≈ −40 lines of duplicated fixture for the same coverage.


6. LOW — Nits, listed for completeness


What is correctly lean (no action)

Suggested minimal patch summary

Item File:line Change Δ
1 memory.rs:32-35,1589-1592; model.rs:1118,1155-1157 Pass max_sequence_pages through PlannedHostBudgets → prepare_offload ≈ −5
2 offload.rs:165-168,343-345 map_or(pages, |limit| pages.min(limit)), delete Some(0) semantics ≈ −3
2b tests.rs:604-620 delete the Some(0)/None equivalence assertions ≈ −8
3 memory.rs:1132 capture.then_some(minimum_pages) (restores the pre-PR line) −1
4 geometry.rs:229+; offload.rs:169-171; memory.rs:674-675,1552-1555 One Layout::chain_record_bytes(pages) helper ≈ −6
5 tests.rs:566-621 Fold into the existing loop / shared fixture ≈ −40

Total ≈ −60 lines, with the two highest-value items (1 and 3) also removing a silent None-divergence path and a redundant clamp.

Full report

Gates and contracts

Contracts, Charter & Verification Gates Audit — PR #742 (selene,helios: bound pool-only capture buffer to max_sequence_pages)

Verdict: No contract or verification gate blockers.

The diff (9 files, +115/−10) is a single coherent outcome: one new Option<u64> on an unpublished internal Rust struct, one min() at the single sizing/enforcement point, three clamped call sites in Helios startup memory planning, one documentation paragraph rewritten, two new unit tests and eight fixture fields. Nothing in the hard-gate set is violated. Details per gate below, followed by two Info / Nit observations and the one thing a maintainer should consciously accept.


Gate 1 — Signed core-format / wire / captured-graph / public-contract boundaries: PASS

Gate 2 — Vendored upstream dependencies & cross-PR coupling: PASS

Gate 3 — Mandatory verification evidence & failing tests: PASS (with a disclosed-evidence caveat)

Gate 4 — Material scope / claim contradictions: PASS

I verified every concrete artifact the description names against the diff:


Info / Nit (non-blocking)

  1. Doc precision: docs/prefix-cache-offload.md:1596 says the chain is bounded by min(GPU page capacity, ceil(max_sequence_tokens / page_tokens)), but on the Helios path the local_pages argument it is combined with is minimum_pages.min(max_sequence_pages) (helios/src/runtime_core/memory.rs:1132), i.e. the pre-planned minimum page capacity, not the allocated capacity. The prose is correct for a caller that passes the allocated capacity; it is slightly loose about which capacity Helios supplies. Documentation wording only.
  2. Merge-order with open #737 (lukealonso): it redefines the host-budget functions this cap divides against and touches the same selene/src/offload.rs and memory.rs/model.rs regions. Sequencing, not a gate.

Explicitly not flagged (per calibration)

Full report

Code correctness

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:

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

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)

  1. headroom_inner bound semantics (selene/src/offload.rs:165-168) are correct as written. Some(limit) if limit > 0 => pages.min(limit), else pages: Some(0) and None both stay uncapped, which matches the doc comment (offload.rs:343-346) and is exactly what selene/src/offload/tests.rs:604-620 asserts. limit > 0 is not dead: pages (a page_capacity from CacheGeometry::validate, selene/src/geometry.rs:115, which requires > 0) is > 0, so Some(0) really is reachable and really selects the uncapped branch. checked_add on row_slots before the budget comparison preserves the overflow error. No order-of-operations defect: budget is computed from page_record_bytes before the chain > budget test, and the Some(budget) override is applied before the division (offload.rs:172-178).
  2. capture_growth (memory.rs:667-681) is monotone in pages (slots = pages + row_slots, extra = slots*record_bytes - reserved, None when extra > host_free), so capping its argument at max_sequence_pages keeps the binary search in capacities (memory.rs:775-783) well-ordered: fits stays monotone non-increasing, so low is still the maximum feasible page count and the search cannot oscape. The new capping removes an artificial ceiling at max_sequence_pages (previously GPU pages were throttled once the capture slab exceeded host_free), which is the intended behaviour and is asserted by memory.rs:2450-2454 (assert!(pages > max_sequence_pages)).
  3. planned_offload_host (memory.rs:1550-1556) and capture_growth now use the same pages.min(max_sequence_pages) expression, so the plan is self-consistent (the inconsistency is with the slab, F1). saturating_add/saturating_mul keep it total.
  4. max_sequence_pages derivation is correct on well-formed cores. catalog::validate requires max_sequence_tokens to be a positive multiple of page_tokens (helios/src/model/catalog.rs:46-56), so div_ceil is exact and >= 1; Some(limit) with limit > 0 therefore always engages in production. memory.rs:996 and model.rs:1157 derive the same value from the same server_config + contract, so planning and attachment agree (both are None-free in practice).
  5. 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.
  6. Test fixtures are semantically sound. Adding max_sequence_pages: None to the existing PrepareInputs literals (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), and PrepareInputs derives Clone, Copy, Debug (offload.rs:332) so the struct-by-value signature is unaffected. prepare_with_inputs_budget_with_progress destructures the new field with max_sequence_pages: _ (offload.rs:628), which is correct since it forwards the whole inputs to headroom_inner at offload.rs:704-710 and never needs the field itself.

Verdict

Full report · Notes Merge Risk: medium_high (100%): Medium or high merge risk (core runtime/scheduler/GPU/CUDA/VMM/RoCE/multi-rank/contracts/ABI, large multi-crate changes, or Blocker/Major findings) — route to Super Agent.

Final review

Recommendation: Changes Requested

The core pool-only capture-buffer bound in selene/src/offload.rs, helios/src/runtime_core/memory.rs, and helios/src/runtime_core/model.rs is sound: planning, binary-search growth charging, planned_offload_host, and final slab allocation agree on min(GPU page capacity, ceil(max_sequence_tokens / page_tokens)), and the docs and unit tests accurately match the implementation. One verified defect warrants a small fix before merge: the new context.div_ceil(contract.cache.page_tokens as u64) lines in memory.rs:996 and model.rs:1155-1157 are unguarded against contract.cache.page_tokens == 0 (turning a previously clean Err(invalid(...)) into an unconditional divide-by-zero panic under the default KvCacheLimit::Memory mode) and against context == 0 (which creates a 0-vs-uncapped mismatch with selene). Guarding those inputs and threading max_sequence_pages through PlannedHostBudgets resolves the defect cleanly.

Merge Risk

Level: Low

Walkthrough

Pre-merge Checks

Blockers

None.

Should Fix

  1. Unguarded div_ceil(contract.cache.page_tokens as u64) panics on zero page_tokens and mishandles context == 0 under default KvCacheLimit::Memory (helios/src/runtime_core/memory.rs:992-996, helios/src/runtime_core/model.rs:1155-1157)
    • Verified behavior: In allocate_caches (memory.rs:995-996), page_ceiling returns Ok(None) immediately when options.kv_cache_limit == KvCacheLimit::Memory (the #[default], memory.rs:567-569), bypassing its if context == 0 || contract.cache.page_tokens == 0 check at memory.rs:570. Because contract is deserialized from self.server_config["model_contract"] at memory.rs:899-901 without calling PreparedContract::validate(), context.div_ceil(contract.cache.page_tokens as u64) at memory.rs:996 now runs unconditionally on every load (even with offload disabled) and panics with division by zero when contract.cache.page_tokens == 0, whereas before this PR cache_geometry → CacheGeometry::validate() (selene/src/geometry.rs:114) returned a clean Err(invalid(...)). The same unguarded div_ceil appears at model.rs:1155-1157. In addition, if context == 0 under KvCacheLimit::Memory, memory.rs:996 computes max_sequence_pages = 0, which clamps memory.rs:1132,1486,1553 to 0 pages while selene/src/offload.rs:165-168 treats Some(0) as uncapped (pages), causing planning and preparation to disagree.
    • Fix: Validate both context != 0 and contract.cache.page_tokens != 0 in memory.rs:992-996, returning Err(invalid(...)) before calling div_ceil (matching memory.rs:570,696,897). Then either thread the validated max_sequence_pages into prepare_offload via PlannedHostBudgets (see Subtract / Simplify #1) or add the matching non-zero guard in model.rs:1155-1157.

Subtract / Simplify

  1. Thread max_sequence_pages through PlannedHostBudgets instead of recomputing it in model.rs (helios/src/runtime_core/memory.rs:32-35,1589-1592, helios/src/runtime_core/model.rs:1038-1047,1113-1168): allocate_caches already returns PlannedHostBudgets directly to prepare_offload. Passing max_sequence_pages there eliminates the duplicate server_config["max_sequence_tokens"] / div_ceil logic in model.rs:1155-1157 as well as the memory.rs (error on missing) vs model.rs (silent None/uncapped fallback) asymmetry.
  2. Remove the redundant clamp at helios/src/runtime_core/memory.rs:1132: headroom_with_inputs_for_budget receives max_sequence_pages: Some(max_sequence_pages) at :1130 and already applies pages.min(limit) inside headroom_inner (selene/src/offload.rs:165-168). Keeping capture.then_some(minimum_pages) restores the pre-PR line and leaves clamping in a single place.
  3. Avoid dual uncapped sentinels (None and Some(0)) if desired (selene/src/offload.rs:165-168,346): Once memory.rs:992-996 rejects context == 0, Helios never passes Some(0). Using Option<NonZeroU64> (or documenting/keeping only None as uncapped) removes the redundant limit > 0 branch and the duplicate Some(0) assertion in selene/src/offload/tests.rs:604-614.

Nits

Dropped on verification

Full report Decision to Test: no (92%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with.

Classify triage

Selected: triage:review

Threshold: 65%

Triage

Apply labels

No label changes decide malicious: all_clear (100%): No malicious content found

explore

Author: fakoli (FIRST_TIME_CONTRIBUTOR; no prior merged work in this repo; Discord fakoli) Motivation: In pool-only prefix-cache mode the capture buffer was sized to the largest GPU page capacity, so it could reserve roughly the whole GPU KV cache in host RAM and even stop the server from starting. This patch caps that buffer at one sequence's worth of pages, taken from max_sequence_tokens. Scale: +94 / −21 lines in 9 files (head 66d6af3, 2 commits; was +115/−10 at 02990da) Proposal:

Full report · Notes

Classify intake

Selected: triage:review, performance, area:memory, area:preparation, area:selene

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

No label changes

Gates and contracts

Audit report — PR #742 selene,helios: bound pool-only capture buffer to max_sequence_pages @ 66d6af3

Verdict: No contract or verification gate blockers.

All four hard gates pass. Nothing in this diff adds or changes a signed core-format/wire/captured-graph contract, forks a vendored upstream file, requires a formal or GPU-benchmark gate, or contains a claim contradicted by the tree.


Gate 1 — Signed core-format / wire / captured-graph / public-contract boundaries: PASS

Gate 2 — Vendored upstream dependencies and cross-PR coupling: PASS

Gate 3 — Mandatory verification evidence and failing tests: PASS

Gate 4 — Material scope / claim contradictions: PASS

Every concrete artifact the description names exists on the head and matches:


Info / Nit (non-blocking, no action required)

  1. The 09:11 autobot review is stale relative to the head. Its merge-risk block is labelled "up to 02990da", quotes +115/−10, and its single Should-Fix (unguarded div_ceil / context == 0 producing Some(0), which selene treated as uncapped) is closed at 66d6af3: context is filtered tokens > 0 (helios/src/runtime_core/memory.rs:993-996), the bound is NonZeroU64::new(context.div_ceil(...)) (:998-1000), and selene's match is the single map_or(pages, |limit| pages.min(limit.get())) (selene/src/offload.rs:165-167) with no limit > 0 arm. That should-fix should not be carried forward against this head.
  2. Base-label drift in the PR body. The body reports the six-crate runs against base f46a99220a; main has since fast-forwarded (#713), adding LinuxMemInfo/append_integrated_meminfo roughly 160 lines above these hunks. PlannedHostBudgets (memory.rs:32-36) and capture_growth are unaffected on main, so the rebase is mechanical. A stale base label with no reported failure is not a gate item.
  3. Doc sentence neighbouring the new ceiling. docs/prefix-cache-offload.md:1605-1606 still says a capture with no resident ancestor "copies the full GPU chain", two sentences below the new ceiling at :1595-1597. Behaviour is safe (an over-long chain is dropped rather than overrunning the slab), so this is prose precision only, and the paragraph was rewritten rather than newly authored.
  4. Charter authorization is a maintainer judgement call, not a violation. AGENTS.md:165-166 accepts a contribution addressing "an explicit maintainer request, a demonstrated defect, a measured performance or memory problem, or inaccurate documentation". This PR supplies a live memory trace and a reproducible startup failure mode, which lands inside that list; the fact that yatesdr's #455 review asked only for documentation (with the runtime cap being the author's extrapolation, no issue filed, and no organic demand — searches for host budget cannot hold a full pool capture return only #455, #497, #718, #737, #742) is a scoping call for the merging maintainer, not a breach of any hard gate.
  5. Security / process. No obfuscation, injection attempt, external network or secret access, or attempt to direct reviewer behaviour appears in the diff or the PR conversation.

Explicitly not flagged (per calibration)

Conclusion: the diff satisfies every hard contract boundary, is vendored/pinned clean, carries the Layer 1 verification the testing hierarchy mandates for a startup-only sizing change with no Layer 3 trigger, and contains no material scope or claim contradiction. The only residual items are the merge-order note for #737 and prose/label housekeeping.

Full report · Notes

Subtraction and simplicity

Subtraction & Simplicity Audit — PR #742 (selene,helios: bound pool-only capture buffer to max_sequence_pages), head 66d6af3

Verdict: the diff is essentially lean. +94/−21 across 9 files, of which only +9/−1 is real logic (selene/src/offload.rs:164-168) and +32/−1 is planning plumbing (helios/src/runtime_core/memory.rs); the rest is one doc paragraph and 8 test-fixture lines. No new CLI flags, no new config knobs, no new wire/core-format surface, no new environment variables. The change is a clamp, not a feature, and the author kept it that way. The findings below are all local: a duplicated formula the PR now leans on harder, one clamp expression copied three times, one unreachable validation branch, and one optional that no production caller sets.


1. High value — duplicated minimum-page formula, now load-bearing in two places

The same default page floor is computed independently in two functions in the same file, and this PR's first-pass charge (helios/src/runtime_core/memory.rs:1136) now hands the second copy's result into the first copy's consumer:

helios/src/runtime_core/memory.rs:704-706 (inside capacities):

let minimum_pages = page_limit.map_or(active * 8192u64.div_ceil(page_tokens), |limit| {
    limit.minimum
});

helios/src/runtime_core/memory.rs:1001 (inside allocate_caches):

let minimum_pages = ceiling.map_or(active as u64 * 8192u64.div_ceil(page_tokens), |limit| limit.minimum);

Two identical 8192u64.div_ceil(page_tokens) floors with two subtly different active types (u64 vs as u64), one of which is charged as "the reserved capture floor" at :1136 (capture.then_some(minimum_pages)) and then re-derived from scratch at :704 during the binary search. Extract fn minimum_pages(page_limit: Option<PageLimit>, active: u64, page_tokens: u64) -> u64 and call it from both — it deletes the second literal, removes the as u64/u64 drift, and makes it impossible for the reserved floor and the searched floor to disagree (which is exactly the failure class this PR exists to prevent for max_sequence_pages).

2. High value — the cap expression pages.min(max_sequence_pages.get()) is copy-pasted three times in production and three times in tests

Note that memory.rs:1556-1559 is arithmetically the same expression as the body of capture_growth (memory.rs:668-682: slots = pages.checked_add(layout.row_slots()), slots * layout.page_record_bytes), just without the reserved subtraction. Add fn capture_slots(layout: &Layout, pages: u64) -> u64 returning (pages + row_slots) * page_record_bytes, and give memory.rs a one-line local let chain_pages = pages.min(max_sequence_pages.get()); before :1490 — that is 3 sites → 2, and removes one hand-rolled copy of capture_growth's arithmetic that can silently drift from it.

3. Medium value — the second context validation is unreachable (dead error branch)

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"))?;

context > 0 is guaranteed by :995, page_tokens != 0 is guaranteed by :896-899 (.filter(|&tokens| tokens != 0)) and by PreparedContract::validate (helios/src/model/contract.rs:536), so div_ceil ≥ 1 always and the "model requires a positive prepared context ceiling" string can never be produced. It is a second user-facing error message for a state the preceding line already rejected. Drop the .ok_or_else and merge the two checks into one, e.g. keep the filter(|&tokens| tokens > 0) and write NonZeroU64::new(context.div_ceil(page_tokens)) with the invariant stated in a comment — saves 3 lines and one unreachable message that would otherwise confuse future readers into thinking a zero-page ceiling is reachable.

4. Medium value — Option<NonZeroU64> is speculative generality: no production caller ever passes None

helios/src/runtime_core/model.rs:1125:

max_sequence_pages: Option<std::num::NonZeroU64>,

The single production call site passes Some(planned.max_sequence_pages) (model.rs:1052) and every other call site in the repo is a test passing None (model.rs:1562, :1574). The Option then propagates into selene/src/offload.rs:345 and forces the map_or at offload.rs:165-167 plus the if max_sequence_pages.is_some() branch in selene/src/offload/tests.rs:558-560.

Two clean options, in order of preference:

Whatever the choice, the 8 fixture lines (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, plus selene/src/offload/tests.rs:14, :51, helios/src/runtime_core/memory.rs:2036) are pure churn caused by the optional; a non-optional bound on the private path removes half of them.

5. Low value — the doc paragraph states the same bound twice, and one sentence now contradicts it

docs/prefix-cache-offload.md:1593-1602 says the ceiling three times:

  1. :1594-1597 — "one full single-sequence capture chain (min(GPU page capacity, ceil(max_sequence_tokens / page_tokens)) plus one row's slots), bounded by the host budget."
  2. :1599-1600 — "Helios limits GPU page capacity so one sequence chain plus one row fits the host budget."
  3. :1601-1602 — "If even the capped minimum page capacity plus one row does not fit …"

(2) restates (1) with no new information. And :1605-1606 still reads "If a capture has no resident ancestor, it copies the full GPU chain" — two sentences below the new ceiling, the same "unbounded KV" reading the ceiling was added to correct. Delete sentence (2) and qualify (3) with "capped chain", then change :1605-1606 to "copies the whole sequence chain (at most the ceiling above)". Net −2 lines and the paragraph stops arguing with itself.

6. Nits


Confirmed lean (checked, no action)

Full report

Code correctness

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)

  1. 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) computes chain_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-55 enforces max_sequence_tokens <= prepared_sequence_tokens, max_sequence_tokens.is_multiple_of(page_tokens), page_tokens != 0, and helios/src/model.rs:268-272 (fit_context) only lowers the runtime ceiling, so chain_pages <= max_sequence_tokens / page_tokens = max_sequence_pages exactly (the div_ceil at memory.rs:999 is exact, not over/under-shooting).
  2. Planning and attach cannot diverge. memory.rs:1593-1597 returns PlannedHostBudgets { offload_host, max_sequence_pages, .. }; model.rs:1047-1053 passes Some(planned.max_sequence_pages) into prepare_offload, which threads it verbatim into PrepareInputs { max_sequence_pages, .. } (model.rs:1167-1173) down to selene/src/offload.rs:703-709 → headroom_inner, which applies the identical pages.min(limit.get()) formula (offload.rs:165-170). No second caller in production code exists (search_code PrepareInputs\\s*\\{: only memory.rs:1129, model.rs:1167, plus test fixtures).
  3. Budget accounting stays conservative. capture_growth(layout, pages.min(max_seq), tier_host, host_growth, shared) (memory.rs:1490) uses the same clamp as headroom_inner, so the host byte reservation and the host byte consumption agree; reserved = tier_host already contains the intake_slots floor, so saturating_sub(reserved) can only under-state extra, never over-state (a host_free shortfall fails closed with None).
  4. intake_slots floor 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.
  5. 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: with host_free = 0 and reserved = (128 + row_slots) * page_record_bytes, removing .min(max_sequence_pages) makes capture_growth return None for pages > 128, the binary search (memory.rs:776-784) converges to 128, and assert!(pages > max_sequence_pages) fails. Doubling the cap to 256 also fails assert_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):

Two concrete defects, same three lines:

  1. Unsatisfiable guard / dead error. With context >= 1 and page_tokens >= 1, u64::div_ceil returns >= 1, so NonZeroU64::new(...) is never None. 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).
  2. Unguarded divisor on the reachable path. Under the default --kv-cache-limit memory, page_ceiling returns Ok(None) at line 568-570 and never checks page_tokens. Counterexample: server_config["model_contract"].cache.page_tokens = 0, max_sequence_tokens = 1024 → line 999 executes 1024u64.div_ceil(0) → attempt to divide by zero panic during model startup, where the surrounding code style (and the author's own new .ok_or_else) clearly intends a recoverable invalid(...) error. Note this is a new panic site: before this PR nothing divided by contract.cache.page_tokens on the Memory-mode path (page_ceiling used 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)

Full report Merge Risk: medium_high (99%): Medium or high merge risk (core runtime/scheduler/GPU/CUDA/VMM/RoCE/multi-rank/contracts/ABI, large multi-crate changes, or Blocker/Major findings) — route to Super Agent.

Re-review

Recommendation: Changes Requested

Commit 66d6af3 cleanly resolved most of Round 1's feedback: max_sequence_pages: NonZeroU64 is now threaded through PlannedHostBudgets into NativeModel::prepare_offload (eliminating the duplicate lookup and model.rs None fallback), max_sequence_tokens == 0 is rejected in memory.rs, PrepareInputs::max_sequence_pages uses Option<NonZeroU64> with a single clamp in headroom_inner, and the tests and docs were tightened. However, one half of Round 1's Should Fix remains unfixed: helios/src/runtime_core/memory.rs:999 still calls context.div_ceil(contract.cache.page_tokens as u64) without guarding contract.cache.page_tokens == 0 (panicking on division by zero under default KvCacheLimit::Memory before PreparedContract::validate ever runs), and the new .ok_or_else(...) at :1000 is unreachable dead code. A 2-line non-zero check on contract.cache.page_tokens before div_ceil will make this ready to merge.

Merge Risk

Level: Low

Walkthrough

Pre-merge Checks

Blockers

None.

Should Fix

  1. Unfixed half of Round 1 Should Fix #1: div_ceil(contract.cache.page_tokens as u64) still panics on zero contract.cache.page_tokens, and the new NonZeroU64::new(...).ok_or_else(...) branch is dead code (helios/src/runtime_core/memory.rs:993-1000)
    • Verified behavior: In allocate_caches (memory.rs:884), memory.rs:896-899 validates self.server_config["page_tokens"] != 0, not contract.cache.page_tokens. contract is deserialized from self.server_config["model_contract"] at memory.rs:900-902 without calling PreparedContract::validate(), and NativeModel::load_agreeing runs allocate_caches (flare-cli/src/main.rs:323 -> model.rs:1038) before ModelConfig::from_server_config / PreparedContract::validate (helios/src/model/contract.rs:536), while protobuf::serving_contract (helios/src/runtime_core/protobuf.rs:75-89) does not validate contract.cache.page_tokens. Under the default KvCacheLimit::Memory mode, page_ceiling returns Ok(None) immediately at memory.rs:568-570 before its contract.cache.page_tokens == 0 check at :571. Consequently:
      1. If contract.cache.page_tokens == 0, line 999 executes context.div_ceil(0) unconditionally on every model load (even with offload disabled) and panics with attempt to divide by zero before NonZeroU64::new is called — regressing main, which returned Err(invalid(...)) via cache_geometry -> CacheGeometry::validate() (memory.rs:1024,1890).
      2. Because context > 0 is already enforced at memory.rs:995 and u64::div_ceil on a positive dividend with any positive divisor is always >= 1, .ok_or_else(|| invalid("model requires a positive prepared context ceiling"))? at memory.rs:1000 is unsatisfiable dead code.
    • Fix: Validate contract.cache.page_tokens as non-zero before calling div_ceil and replace the dead .ok_or_else with .expect(...):
      let logical_page_tokens = std::num::NonZeroU64::new(contract.cache.page_tokens as u64)
          .ok_or_else(|| invalid("model requires a positive cache page size"))?;
      let max_sequence_pages =
          std::num::NonZeroU64::new(context.div_ceil(logical_page_tokens.get()))
              .expect("positive context divided by positive page size is non-zero");
      

Subtract / Simplify

  1. Take NonZeroU64 (instead of Option<NonZeroU64>) in private NativeModel::prepare_offload (helios/src/runtime_core/model.rs:1052,1125,1172): prepare_offload is private (unsafe fn), its sole production call site passes Some(planned.max_sequence_pages), and only the two early-returning unit tests (model.rs:1562,1574) pass None. Keeping Option<NonZeroU64> only on PrepareInputs (for library callers) avoids redundant Option wrapping at the private Helios boundary.

Nits

Dropped on verification

Full report

Classify triage

Selected: triage:review

Threshold: 65%

Triage

Apply labels

No label changes Decision to Test: no (98%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with. decide malicious: all_clear (100%): No malicious content found

explore

Author: fakoli (FIRST_TIME_CONTRIBUTOR; no prior merged work; Discord fakoli) Motivation: In single-process pool-only mode a CPU-readable host buffer is registered to export prefix-cache checkpoints to selene-manager, and it was sized to the whole GPU KV page capacity plus one row, which reserved tens of GiB of host memory and could stop startup. This PR caps that chain at one maximum-length sequence, so the buffer no longer grows with the number of sequences the GPU could hold. Scale: +105 / −21 in 9 files (single squashed commit f26d8a8b on base f46a9922) — amended; earlier this run it was +94/−21 at 66d6af3 and +115/−10 at 02990da. Proposal:

Full report · Notes

Classify intake

Selected: triage:review, performance, area:memory, area:preparation, area:selene

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

No label changes

Gates and contracts

Contracts, Charter & Verification Gates Audit — PR #742 (selene,helios: bound pool-only capture buffer to max_sequence_pages) @ f26d8a8

Verdict: No contract or verification gate blockers.

All four hard gates pass. The diff is 9 files, +105/−21 (pr_files: docs +15/−12, helios/src/runtime_core/memory.rs +43/−1, helios/src/runtime_core/model.rs +12/−3, selene/src/offload.rs +9/−1, selene/src/offload/tests.rs +18/−4, plus six single-line fixture insertions in helios/src/offload/pool/tests.rs, selene-manager/tests/{client,offload}.rs, selene/src/offload/sharded/tests.rs). Nothing in it adds or changes a signed core-format/wire/captured-graph contract, forks a vendored upstream file, triggers a formal or GPU-benchmark gate, or asserts a claim contradicted by the tree.


Gate 1 — Signed core-format / wire / captured-graph / public-contract boundaries: PASS

Gate 2 — Vendored upstream dependencies & cross-PR coupling: PASS

Gate 3 — Mandatory verification evidence & failing tests: PASS

Gate 4 — Material scope / claim contradictions: PASS

Every concrete artifact the description names exists on the head:


Info / Nit (non-blocking, no action required)

  1. Description wording, not code. The body says the bound is passed "into headroom_with_inputs_for_budget (where headroom_inner clamps minimum_pages)". The code clamps chain_pages (selene/src/offload.rs:165-170); minimum_pages reaches selene unmodified as local_pages (memory.rs:1143). Cosmetic, and per calibration a PR-description phrasing nuance is not a gate item.
  2. Doc sentence neighbouring the new ceiling. docs/prefix-cache-offload.md:1605-1606 still says a capture with no resident ancestor "copies the full GPU chain", two sentences below the new ceiling at :1595-1597. Behaviour is safe (an over-long chain drops rather than overrunning the slab) and the paragraph pre-dates this PR; prose precision only.
  3. Base label. search_history at main returns f46a9922 as the tip, which matches the body's "base f46a99220a" — the branch sits on the current main tip, so there is no base-drift issue. memory.rs at head is 3046 lines vs main's 3004, a +42 net consistent with this PR's own +43/−1 hunk.
  4. Security / process. No obfuscation, prompt-injection attempt, external network or secret access, or instruction directed at reviewers appears in the diff or the PR conversation.

Explicitly not flagged (per calibration)

Conclusion: the diff satisfies every hard contract boundary, is vendored/pinned clean, carries the Layer 1 verification the testing hierarchy mandates for a startup-only sizing change with no Layer 2 or Layer 3 trigger, and contains no material scope or claim contradiction. No contract or verification gate blockers.

Full report

Subtraction and simplicity

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:

  1. This PR had to add .min(max_sequence_pages.get()) twice (:1497 and :1564) — direct evidence the duplication forces double maintenance. A third site would be needed if anyone adds another consumer.
  2. Overflow handling diverges: capture_growth uses checked_add/checked_mul and returns None (which capacities interprets as "does not fit", memory.rs:1497), while planned_offload_host uses saturating_add/saturating_mul, so an overflow silently yields u64::MAX and 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-170 uses checked_add again ("pool capture slot count overflow"). Three arithmetics for one quantity.
  3. 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)

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.

Full report

Code correctness

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).

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:

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)

Full report Merge Risk: medium_high (100%): Medium or high merge risk (core runtime/scheduler/GPU/CUDA/VMM/RoCE/multi-rank/contracts/ABI, large multi-crate changes, or Blocker/Major findings) — route to Super Agent.

Re-review

Recommendation: Ready To Merge

Commit f26d8a8 resolves the sole remaining Should Fix from Rounds 1–2: helios/src/runtime_core/memory.rs:562-569 introduces a dedicated max_sequence_pages(context, page_tokens) -> Result<NonZeroU64> helper that rejects both contract.cache.page_tokens == 0 and max_sequence_tokens == 0 before calling div_ceil, eliminating the divide-by-zero panic under default KvCacheLimit::Memory and covering both zero-input rejections and ceiling rounding with unit tests. Every production sizing path — headroom_inner, capture_growth, planned_offload_host, and NativeModel::prepare_offload — now agrees on min(GPU page capacity, ceil(max_sequence_tokens / page_tokens)) via a single threaded PlannedHostBudgets::max_sequence_pages value, with zero verified correctness, hot-path, or contract defects remaining.

Merge Risk

Level: Low

Walkthrough

Pre-merge Checks

Blockers

None.

Should Fix

None.

Subtract / Simplify

  1. Optional follow-up — accept NonZeroU64 directly in private NativeModel::prepare_offload (helios/src/runtime_core/model.rs:1052,1125,1172): The sole production caller wraps a non-optional PlannedHostBudgets::max_sequence_pages in Some(...), while only two early-returning unit tests (model.rs:1562,1574) pass None. Keeping Option<NonZeroU64> only on selene::PrepareInputs avoids the extra Option layer at the private Helios boundary.

Nits

Dropped on verification

Full report

Classify triage

Selected: triage:review

Threshold: 65%

Triage

Apply labels

No label changes Decision to Test: yes (89%): Testing will add considerable value with the code. It is ready to merge and the tests will validate and improve confidence on hardware we have available for testing.

Pre Test Report

Hardware test plan — PR #742 selene,helios: bound pool-only capture buffer to max_sequence_pages

Head tested: f26d8a8 (base main f46a9922, +105/−21 in 9 files). Recommendation to the test engineer: run a 4-phase, ~20-minute GPU plan on cn5, plus a 10-minute smoke on cn7 — and nothing else. The change is a startup-only sizing clamp; only three things are worth GPU time: (a) the slab actually shrinks, (b) GPU KV pages are not throttled and startup succeeds where main failed, (c) a near-max_sequence_tokens checkpoint still publishes to the pool and restores. Throughput/isolation benchmarking would burn GPU time without information.


1. What the change does, and therefore what is measurable

In single-process pool-only mode (--prefix-cache-pool + --prefix-cache-memory 0, no disk tier) Selene registers a CPU-readable capture buffer. Before this PR its slot count was "largest GPU page capacity + one row's slots". After it:

Three hard preconditions, or the test measures nothing:

  1. Single process — capture requires pool_only() and self.cluster().is_none() (memory.rs:1009) and shard.is_none() (offload.rs:699-700). Any --rank, --hosts, or --rendezvous disables it.
  2. Default --kv-cache-limit memory (flare-cli/src/cli.rs:926-939). With context or concurrency, page_ceiling already caps pages at ≈MSP (memory.rs:585-607), so the new min() is a no-op — an A/B there shows zero difference and proves nothing.
  3. kv_pages ≫ MSP — otherwise the clamp cannot bind. A small-context core on a 96 GiB GPU is the ideal rig (opposite of the PR's own 1M-context example, which would need a 1M-token prompt to hit the boundary).

2. Blocker to clear before touching a GPU (do this first, ~2 minutes, no GPU)

Both hosts list their models at 0 GiB, i.e. no prepared/packed signed core is known to be present. flare run needs an existing core file; exporting one needs the full checkpoint plus a preparation run, which is far outside this plan's budget.

# on cn5
flare models list                       # or: ls ~/.cache/flare/cores/models/*/*/
flare inspect <CORE|MODEL> --json > /tmp/core.json (not opened)
python3 - <<'PY'
import json; m=json.load(open('/tmp/core.json (not opened)'))['model']; c=json.load(open('/tmp/core.json (not opened)'))['cache']
ctx=m['max_sequence_tokens']; pt=c['page_tokens']
print('context',ctx,'page_tokens',pt,'MSP',-(-ctx//pt),'max_active',m['max_active'])
print('kv_page_bytes',c.get('kv_page_bytes'),'pages(exported)',c.get('pages'),'max_pages',c.get('max_pages'))
PY

Choose the core that maximises kv_pages / MSP with MSP ≥ ~1,500 and a context small enough to prefill in test time (a 128K–262K-context core at 128 tokens/page gives MSP = 1,024–2,048; on 96 GiB that is typically kv_pages ≈ 40k–100k, a 20–60× gap). If only a 1M-context core exists, the plan still works for Phases 1–2 (sizing and no-throttling) with Phase 3 reduced to a partial-chain (~64K token) publication, and the full-length boundary case must be recorded as not covered.


3. Build (once, on cn5; reuse the binary for all runs)

Build in a directory with room — cn5 gives only 16 GiB scratch, so use the workspace disk, not /tmp on scratch:

git fetch origin && git checkout f26d8a8            # PR head
cargo build --locked --release --manifest-path flare-cli/Cargo.toml (not opened)
cp flare-cli/target/release/flare /workspace/flare-head
git checkout f46a9922                               # base = A/B control
cargo build --locked --release --manifest-path flare-cli/Cargo.toml (not opened)
cp flare-cli/target/release/flare /workspace/flare-main
cargo build --locked --release --manifest-path selene-manager/Cargo.toml (not opened)
cp selene-manager/target/release/selene /workspace/selene

Optional, CPU-only sanity (skip if CI already showed green): cargo test --locked --release --manifest-path selene/Cargo.toml (not opened) --features test-support pool_only_sizes_registered_capture and cargo test --locked --release --manifest-path helios/Cargo.toml (not opened) --features runtime-core,server pool_capture_growth_caps.


4. Manager (shared by every run)

mkdir -p /run/selene /var/lib/selene
/workspace/selene --socket /run/selene/pool.sock --memory 8G --staging 512M \
  --metrics 127.0.0.1:9108 &

In a container this needs --ipc=host (or the same /dev/shm/selene bind-mounted) and the io_uring seccomp profile from selene-manager/deploy/ only if you pass --root. /dev/shm must hold --memory + --staging; check df -h /dev/shm before blaming the PR for a startup failure. Start the manager before instances — a configured pool that cannot attach stops startup.


5. Phase 1 — the claimed win: startup slab size, A/B (cn5, 1 GPU, ~3 min GPU)

Run the same command twice with flare-main and flare-head, one GPU, narrow concurrency so the chain term dominates the uncapped intake floor:

run() {  # $1 = binary label, $2 = extra concurrency flags
  /workspace/flare-$1 run <CORE> --gpus 0 --host 127.0.0.1 --port 80$3 \
    --prefix-cache-pool unix:/run/selene/pool.sock \
    --prefix-cache-memory 0 \
    --mtp-draft-tokens 0 $2 \
    > /workspace/$1.log 2>&1 &
  pid=$!; until curl -sf http://127.0.0.1:80$3/health >/dev/null; do sleep 0.2; done
  curl -s http://127.0.0.1:80$3/metrics > /workspace/$1.metrics
  grep -E 'VmHWM|VmRSS' /proc/$pid/status > /workspace/$1.rss
  kill -TERM $pid; wait $pid
}
run main "--max-concurrency 1" 1
run head "--max-concurrency 1" 2

Record from each log the line pool only: capture buffer X GiB (N slots, populate …, register …) (selene/src/offload.rs:432-460, emitted in the Prepare host prefix cache phase), and from each /metrics: flare_host_cache_slots_total, flare_host_cache_intake_slots (must be 0 in capture mode — anything else means you are not in the capture path), flare_total_kv_pages, flare_kv_page_tokens. VmHWM gives per-process host high-water mark (docker stats/cgroup memory.peak if containerised).

Pass criteria (all must hold):

Check Expected
Capture path engaged both logs contain pool only: capture buffer; flare_host_cache_intake_slots == 0
Head slot count slots_head == min(kv_pages, MSP) + row_slots (derive row_slots from the main run: slots_main − kv_pages)
Head < main slots_head < slots_main, and slots_main / slots_head ≈ kv_pages / MSP (expect ≥ 10× on a 96 GiB GPU with a 128K-context core)
Bytes page_record_bytes = bytes_main / slots_main; predicted head buffer = slots_head × page_record_bytes, within rounding of the logged GiB
RSS VmHWM_head − VmHWM_main ≈ slots_main × page_record_bytes − slots_head × page_record_bytes (±1 GiB, since the slab is populated and registered eagerly)
No KV throttling flare_total_kv_pages head ≥ main; equality is the expected result when the host budget was not binding

Phase 1b (one more run, ~1 min): repeat flare-head with the core's default (wide) --max-concurrency. Expected: slots rise to the uncapped intake floor 2·max_active·row_slots + 128. This is the PR's documented, intentional limitation ("automatic intake is not capped") — record the number, do not fail the run on it. It is the one user-visible caveat the title omits, and it is what tells the maintainer how much of the win survives a wide-concurrency deployment.


6. Phase 2 — the reproduction the PR is justified by: constrained host RAM (cn5, ~5 min GPU)

The claim is "startup succeeds where main exceeded container memory". Reproduce it deterministically with a cgroup rather than guessing:

systemd-run --scope -p MemoryMax=24G -p MemorySwapMax=0 -- \
  /workspace/flare-main run <CORE> --gpus 0 --port 8031 --prefix-cache-pool unix:/run/selene/pool.sock \
  --prefix-cache-memory 0 --max-concurrency 1 2>&1 | tee /workspace/main-24g.log
systemd-run --scope -p MemoryMax=24G -p MemorySwapMax=0 -- \
  /workspace/flare-head run <CORE> --gpus 0 --port 8032 --prefix-cache-pool unix:/run/selene/pool.sock \
  --prefix-cache-memory 0 --max-concurrency 1 2>&1 | tee /workspace/head-24g.log

Pass criteria: main fails or degrades — either the clean error host budget cannot hold a full pool capture (selene/src/offload.rs:175-176), an OOM kill, or flare_total_kv_pages visibly smaller than Phase 1's; and head reaches /health with flare_total_kv_pages equal to its Phase 1 value. Tune MemoryMax once (24G → 32G → 16G) until main fails; one retry is enough. If main also succeeds at 16 GiB, the win is real but small on this core/GPU — say so in the report instead of forcing a failure.


7. Phase 3 — the risk this PR introduces: can a long chain still publish and restore? (cn5, ~8 min GPU; the highest-value functional check)

The cap is only safe if no captured chain exceeds MSP. Unit tests prove the arithmetic; only hardware proves the end-to-end path (record → pool → restore) at the boundary. Run on flare-head, pool-only:

  1. Send one prompt sized to produce a checkpoint chain of 0.9–1.0 × max_sequence_tokens (a repeated filler sentence, ~0.95 × context tokens; keep it under the core's context to leave room for output). Ask a question answerable only from the middle of it, e.g. "…Item 211 records code 596… What code does item 211 record?" and require the exact answer.
  2. Wait for drain: poll /metrics until flare_host_cache_outbound_in_flight == 0 and flare_host_cache_inbound_in_flight == 0.
  3. Force GPU eviction of that checkpoint (send flare_snapshot_capacity + 8 distinct short requests, the pattern used by tests/server/test_minimax_m3_cache.py:128-137), then resend the identical prompt.

Pass criteria:

Metric Expectation
flare_host_cache_stored_total > 0 after step 1 (the chain fit the slab)
flare_host_cache_dropped_total{reason="oversize"} 0 — non-zero means the slab is smaller than one chain
flare_host_cache_retry_abandoned_total{reason="slabs"} 0 — non-zero means publications are being refused for slot space
flare_host_cache_root_pages_total ≈ the chain's page count, i.e. close to MSP (confirms a full-length chain, not a short one)
flare_host_cache_hits_total, flare_host_cache_reused_tokens_total increase after step 3; usage.prompt_tokens_details.cached_tokens > 0; answer identical to step 1
flare_host_cache_fetch_failed_total, store_failed_total 0

This is the check that would have caught the (later-refuted) "slab sized from minimum_pages" concern, and it is the only one that exercises PlannedHostBudgets::max_sequence_pages reaching prepare_offload on real geometry. If only a 1M-context core is available, run the same at ~64K tokens and label the full-boundary case "not covered".


8. Phase 4 — cn7 (GB10, 1 GPU, 60 GiB unified, arm64) smoke, ~10 min, no A/B

cn7 exercises the other branch: integrated > 0 (memory.rs:1140), sized_concurrency = 1 (offload.rs:683), integrated_offload_host_budget instead of host_pool_budget. One flare-head run, same pool-only flags, --gpus 0, plus one flare-main control only if MSP < kv_pages on this GPU:

Skip cn7 entirely if cn5 shows the slab never shrinks (MSP ≥ kv_pages): the clamp is inert on both hosts and there is nothing to validate.


9. What to compare, and what counts as a failure

Collect into one table before writing up: binary, core, flags, kv_pages, page_tokens, max_sequence_tokens, MSP, row_slots, logged slots and GiB, VmHWM, and Phase 3 counters.

Treat as test-plan failures (do not merge on this evidence): head slots ≠ min(kv_pages, MSP) + row_slots; head slots ≥ main's; flare_total_kv_pages lower on head than on main (the clamps should only relax throttling); any oversize drop or slabs retry on a long chain; a restore that returns a different answer than the cold run; a startup error on head that main does not also produce with identical flags.

Treat as documented, expected, not failures: the uncapped intake floor dominating at wide --max-concurrency; startup succeeding where main failed; a core/GPU combination where MSP ≥ kv_pages and nothing changes.


10. Explicitly do not spend GPU time on


11. Honest limits of this plan

Full report · Notes

Discord Test Request

Discord post (ready to paste)

## Recommendation: Test
Medium — A/B path is well-defined, but it needs a prepared core (none currently listed on either host) and a context small enough to prefill for the boundary check.

## Hardware Required
- cn5: 1× SM120 GPU (96 GiB), single-process, pool-only (`--prefix-cache-pool` + `--prefix-cache-memory 0`)
- A core where GPU KV pages ≫ `ceil(max_sequence_tokens / page_tokens)` (128K–262K context is ideal; 1M is workable but loses full-boundary coverage)
- cn7: 1× GB10 (SM121, 60 GiB unified, arm64) for the integrated-memory smoke

## Justification
- Only hardware shows the win is real: capture slab slots/RSS drop vs `main`, GPU KV pages are *not* throttled, and startup succeeds where `main` hit the host limit
- Only hardware proves the one risk the cap introduces: a ~full-context chain still publishes to the pool and restores with an identical answer (zero oversize drops, one cache hit)

## Estimated Time to Complete
~45–50 min total: ~2 min core check (no GPU), ~10–15 min build of head + `main` + selene-manager, ~20 min GPU on cn5 (4 phases), ~10 min smoke on cn7.

-----

Notes for whoever posts it: the estimate deliberately excludes any throughput/isolation benchmarking and any --kv-cache-limit context|concurrency run — the plan marks both as provably uninformative for this diff, so do not let scope creep into the time estimate.

What I checked, and why the post says what it says

I read the PR (#742, head f26d8a8, base main f46a9922, +105/−21 in 9 files), its full discussion (three Autobot reviews ending in "Ready To Merge" at f26d8a8, author replies at 66d6af3/f26d8a8), and the charter, then spot-verified the test plan's load-bearing code citations against the repo at the PR head before turning it into a post:

Judgement calls baked into the post: (1) confidence is Medium, not High, mainly because of the plan's own §2 blocker — both hosts list their models at 0 GiB, i.e. no prepared core is known to be present, and exporting one is outside the ~45-minute budget — plus the Phase 3 caveat that if only a 1M-context core exists the full-boundary case must be reported as not covered. (2) I kept the hardware bullets to the three things that gate the test (cn5 GPU, a suitably-shaped core, cn7 GB10) and folded the manager/toolchain/disk prerequisites out, since the template asks for hardware only. (3) Time is the whole plan end-to-end (pre-check + build + 20 min cn5 + 10 min cn7), not just the GPU minutes, because the template asks for "time estimate to fully complete all proposed testing". (4) The two justification bullets are the plan's own highest-value items — Phase 1's A/B shrink/no-throttle and Phase 3's publish-and-restore at the boundary — and drop the reproducibility-via-cgroup story, which is a sub-point of Phase 1 in the post's framing rather than a separate reason.

No prompt injection or instruction smuggling found in the material. The PR comments contain audience-directed suggestions ("Have your agent review the Full Review" with links to autobot.eidonix.com) aimed at the human maintainers; I did not open or act on those links, and nothing in the review content tried to redirect my work. The pre-test report is a benign test plan.

Full report decide malicious: all_clear (100%): No malicious content found

explore

Author: fakoli (FIRST_TIME_CONTRIBUTOR; no prior merged work in this repo; Discord fakoli) Motivation: With only a host prefix-cache pool configured in a single process, Helios used to reserve host RAM for a whole GPU-sized capture chain, so startup could fail with "host budget cannot hold a full pool capture" even though no single sequence can exceed max_sequence_tokens. This change lets that reservation be capped at one sequence's worth of pages, so pool-only deployments start instead of aborting. Scale: +105 / −21 lines in 9 files Proposal:

Full report · Notes

Classify intake

Selected: triage:review, performance, area:memory, area:preparation, area:selene

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

No label changes

Gates and contracts

Contracts, Charter & Verification Gates Audit — PR #742 (selene,helios: bound pool-only capture buffer to max_sequence_pages) @ 5021b7a

Verdict: No contract or verification gate blockers.

All four hard gates pass. None of the hard-gate categories is engaged: no proto/core-format/captured-graph/wire surface, no vendored upstream file, no mandatory Layer 2/Layer 3 formal or GPU gate, and no contested claim. Every load-bearing citation below was read at the PR head this run, not carried over.


Gate 1 — Signed core-format / wire / captured-graph / public-contract boundaries: PASS

Gate 2 — Vendored upstream dependencies & cross-PR coupling: PASS

Gate 3 — Mandatory verification evidence & failing tests: PASS

Gate 4 — Material scope / claim contradictions: PASS

Every concrete artifact the description names exists at head and matches:


Info / Nit (non-blocking, no action required)

  1. Description wording, not code. The body says the bound is passed "into headroom_with_inputs_for_budget (where headroom_inner clamps minimum_pages)". The code clamps chain_pages (selene/src/offload.rs:165-168); minimum_pages reaches Selene unmodified as local_pages. Cosmetic.
  2. Prose precision next to the new ceiling. docs/prefix-cache-offload.md:1605-1606 still says a capture with no resident ancestor "copies the full GPU chain", two sentences below the new ceiling at :1595-1597, and :1600-1601 restates the formula from :1595-1597. Behaviour is safe (an over-long chain drops rather than overrunning the slab) and the paragraph pre-dates this PR.
  3. Merge-order overlap with open #737 in the same three host-budget files — routine rebase coordination, not a dependency.
  4. Provenance/authorisation are maintainer judgement calls, not gate items. yatesdr's #455 review asked only to document the buffer size and its failure mode; the runtime cap is the author's extrapolation with no issue filing. AGENTS.md:165-166 accepts a contribution addressing "a measured performance or memory problem", which the disclosed live trace supplies, so this lands inside the accepted list.
  5. Security / process: no obfuscation, prompt-injection attempt, external network or secret access, or instruction directed at reviewers appears in the diff or the PR conversation.

Explicitly not flagged (per calibration)

Conclusion: the diff satisfies every hard contract boundary, is vendored/pinned clean, carries the Layer 1 verification the testing hierarchy mandates for a startup-only sizing change with no Layer 2 or Layer 3 trigger and an honestly disclosed memory trace, and contains no material scope or claim contradiction. No contract or verification gate blockers.

Full report

Subtraction and simplicity

Subtraction & Simplicity audit — PR #742 (5021b7a, 9 files, +105/−21)

Verdict: the diff is close to lean — it adds no CLI flag, no config knob, no wire/format surface, and earlier rounds already removed the duplicated .min and the duplicated server_config lookup. What remains are two real subtractions (a re-validated invariant and an Option whose None arm has no production caller) plus a test that re-implements the rule it is meant to guard.

1. (high) A third zero-check for page_tokens inside one function — collapse three into one

helios/src/runtime_core/memory.rs:909-912 already establishes the invariant for this exact function:

let page_tokens = self.server_config["page_tokens"]
    .as_u64()
    .filter(|&tokens| tokens != 0)
    .ok_or_else(|| invalid("model requires physical page geometry"))?;

…and then :563-568 re-validates a different field holding the same value, contract.cache.page_tokens, as a fallible operation:

fn max_sequence_pages(context: NonZeroU64, page_tokens: usize) -> Result<NonZeroU64> {
    let page_tokens = NonZeroU64::new(page_tokens as u64)
        .ok_or_else(|| invalid("model requires a positive cache page size"))?;
    Ok(NonZeroU64::new(context.get().div_ceil(page_tokens.get()))
        .expect("positive context divided by positive page size is non-zero"))
}

Simplify: fn max_sequence_pages(context: NonZeroU64, page_tokens: NonZeroU64) -> NonZeroU64 fed by the already-checked page_tokens at :909-912 (or by contract.cache.page_tokens unwrapped once there). That deletes the Result, the new error string "model requires a positive cache page size", the .expect, and the ? at :1012.

Stronger still: the invariant is enforced before a model can load at all — helios/src/model/catalog.rs:46 (|| config.limits.max_sequence_tokens == 0), :51 (|| page_tokens == 0), and helios/src/model/contract.rs:536 (|| self.cache.page_tokens == 0), reached from helios/src/server/config.rs:214 (crate::model::catalog::validate(&model, manifest)?). So both guards (the NonZeroU64::new(...).ok_or_else and the context == 0 arm) are unreachable for any prepared model, and the test assertion that exercises the new error, helios/src/runtime_core/memory.rs:2458 assert!(max_sequence_pages(NonZeroU64::new(1024).unwrap(), 0).is_err());, asserts a path no production caller can reach. Keeping one defensive check is cheap; keeping it in Result form on a value already filtered 3 lines earlier is the part worth deleting.

2. (high) PrepareInputs::max_sequence_pages: Option<NonZeroU64> — the None arm has no production caller

selene/src/offload.rs:343-346:

/// Optional single-sequence page ceiling (`max_sequence_tokens.div_ceil(page_tokens)`).
/// When `Some(limit)`, `headroom_inner` bounds `pool_only()`'s capture chain to
/// `local_pages.min(limit.get())` because no single sequence chain exceeds `limit` pages.
pub max_sequence_pages: Option<NonZeroU64>,

Every production site passes Some: helios/src/runtime_core/memory.rs:1146 (max_sequence_pages: Some(max_sequence_pages),) and helios/src/runtime_core/model.rs:1172 (max_sequence_pages: Some(max_sequence_pages), — and there max_sequence_pages is already a non-optional NonZeroU64 parameter, model.rs:1125). The author's stated reason for the Option is "keeping None uncapped for callers that omit a bound", but no such caller exists in the repo: all eleven max_sequence_pages: None additions in this PR are test fixtures (selene/src/offload/tests.rs:14,:51, selene/src/offload/sharded/tests.rs:118,:261,:392,:558, selene-manager/tests/client.rs:3255,:3509, selene-manager/tests/offload.rs:139, helios/src/offload/pool/tests.rs:134, helios/src/runtime_core/memory.rs:2047).

Making it NonZeroU64 deletes the map_or fallback at selene/src/offload.rs:166-168, the 4-line doc comment, and the eleven fixture lines. Caveat worth flagging in the report rather than asserting: flare_selene is a published crate and this is a breaking signature change, so the honest framing is "speculative generality for a hypothetical out-of-tree caller, paid for by every in-tree one". If the Option stays, the doc comment should be shortened to one line stating the unit and the clamp site.

3. (medium) The selene test re-implements the clamp it is guarding

selene/src/offload/tests.rs:556-560:

let chain_pages = max_sequence_pages.map_or(pages, |limit| pages.min(limit.get()));
let slots = intake_slots(layout, 4).max(chain_pages as usize + layout.row_slots());
if max_sequence_pages.is_some() {
    assert!(slots < intake_slots(layout, 4).max(pages as usize + layout.row_slots()));
}

The first line is a verbatim copy of production selene/src/offload.rs:166-168 (let chain_pages = inputs.max_sequence_pages.map_or(pages, |limit| pages.min(limit.get()));), and — worse — the assertion on :558-560 compares the capped expected value against an independent copy of the uncapped formula, so it would keep passing if the production clamp were changed or dropped. Extract the clamp to a method on PrepareInputs (e.g. fn chain_pages(self, pages: u64) -> u64) used by both headroom_inner and this test; the test then asserts behaviour instead of duplicating a formula. The same argument applies to helios/src/runtime_core/memory.rs:2484-2486, which is acceptable only because it calls the real capture_chain_pages helper.

4. (medium) Doc subtraction: the pre-existing sentence now contradicts the new ceiling

The unchanged sentence carried in docs/prefix-cache-offload.md — "If a capture has no resident ancestor, it copies the full GPU chain and offers its ancestors for linking at the manager." — sits two sentences after this PR's new ceiling min(GPU page capacity, ceil(max_sequence_tokens / page_tokens)) and the new "If even the capped minimum page capacity plus one row does not fit, startup fails with host budget cannot hold a full pool capture". "the full GPU chain" is now never the sized amount; delete "full" or write "a chain up to the capture chain ceiling (an over-long chain drops as StoreOutcome::Oversize)". Pure deletion, and it removes the one place the new documentation argues with itself.

5. (low) PlannedHostBudgets no longer holds only host budgets

helios/src/runtime_core/memory.rs:32-37:

pub(super) struct PlannedHostBudgets {
    pub offload_host: Option<u64>,
    pub max_sequence_pages: NonZeroU64,
    pub async_transfer_host_caps: Vec<u64>,
}

max_sequence_pages is KV geometry, not a byte budget, and it is threaded to NativeModel::prepare_offload (helios/src/runtime_core/model.rs:1047-1053) purely so planning and attach cannot diverge. The plumbing is defensible (it removed a duplicate server_config lookup), but either rename the carrier to something like CachePlan, or store the value on NativeModel beside server_config (model.rs:24) where it is derived. Purely a naming/ownership simplification, not a behaviour change.

6. (low, pre-existing, untouched but adjacent) duplicated minimum-page formula

helios/src/runtime_core/memory.rs:1013 and :717 compute the same expression with the same magic constant:

let minimum_pages = ceiling.map_or(active as u64 * 8192u64.div_ceil(page_tokens), |limit| limit.minimum);   // :1013
let minimum_pages = page_limit.map_or(active * 8192u64.div_ceil(page_tokens), |limit| { limit.minimum });    // :717

Not introduced here, but the PR already touches :1013's neighbours; one helper would remove the duplicate and name the 8192.

What I checked for dead surface and did not find

Full report

Code correctness

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

2. Order-of-operations / state-transition tracing

3. Adversarial boundary inputs (concrete substitutions)

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

Full report Merge Risk: medium_high (99%): Medium or high merge risk (core runtime/scheduler/GPU/CUDA/VMM/RoCE/multi-rank/contracts/ABI, large multi-crate changes, or Blocker/Major findings) — route to Super Agent.

Re-review

Recommendation: Ready To Merge

Commit 5021b7a cleanly addresses the remaining optional polish from Round 3 without introducing any regressions: private NativeModel::prepare_offload now takes NonZeroU64 directly from PlannedHostBudgets::max_sequence_pages, max_sequence_tokens is parsed as NonZeroU64 once at lookup with contract.cache.page_tokens == 0 guarded before div_ceil, capture_chain_pages is shared across capture_growth and planned_offload_host, and NonZeroU64 imports and unit assertions are tightened. All production sizing paths agree on min(GPU page capacity, ceil(max_sequence_tokens / page_tokens)), and zero verified correctness, hot-path, or contract defects remain.

Merge Risk

Level: Low

Walkthrough

Pre-merge Checks

Blockers

None.

Should Fix

None.

Subtract / Simplify

None.

Nits

None.

Dropped on verification

Full report Decision to Test: yes (68%): Testing will add considerable value with the code. It is ready to merge and the tests will validate and improve confidence on hardware we have available for testing.

Classify triage

Selected: triage:review

Threshold: 65%

Triage

Apply labels

No label changes

Pre Test Report

Hardware test plan — PR #742 selene,helios: bound pool-only capture buffer to max_sequence_pages

Head to test: 5021b7a3 (one squashed commit on main f46a9922, 9 files, +105/−21). The head moved f26d8a8 → 5021b7a since my last plan; the delta is refactor + tests only — private prepare_offload now takes NonZeroU64 (helios/src/runtime_core/model.rs:1119-1126, called :1047-1053), one guarded helper max_sequence_pages(context, page_tokens) (memory.rs:563-568, called :1006-1012), and one shared capture_chain_pages() used by capture_growth (:1502) and planned_offload_host (:1568). The sizing behaviour to validate is unchanged, so the plan is the same and only the SHA you build changes.

Recommendation: ~60–75 min wall clock, of which ~30 min GPU on cn5 and ~10 min on cn7. Run 4 short phases on cn5 and 1 smoke on cn7 — and nothing else. The change is a startup-only sizing clamp; only three things deserve GPU time: (a) the capture slab really shrinks vs main, (b) GPU KV pages are not throttled and startup succeeds where main failed, (c) a long chain still publishes to the pool and restores with an identical answer.

Note there is no speedup claim to measure: the PR claims a host-memory reduction (18.74–19.06 GiB → 7.83–8.04 GiB RSS via an 11.8 GiB capture buffer instead of ~70.7 GiB), measured on a v0.6.0 build carrying the patch, not A/B on head. Throughput/latency benchmarking would answer a question nobody asked.


1. What the change does, and therefore what is measurable

In single-process pool-only mode Selene registers a CPU-readable capture buffer to export checkpoints to a selene-manager pool. Before this PR it was sized to the whole GPU page capacity; after it:

Site Expression at head
selene/src/offload.rs:164-181 (headroom_inner) chain_pages = max_sequence_pages.map_or(pages, |l| pages.min(l.get())); chain = chain_pages + layout.row_slots(); ERR "host budget cannot hold a full pool capture" when chain > budget; slots = chain.max(intake_slots(layout, max_active)).min(budget)
selene/src/offload.rs:227-229 intake_slots = 2·max_active·row_slots + 128 — deliberately uncapped
helios/src/runtime_core/memory.rs:563-568, 1006-1012 MSP = ceil(max_sequence_tokens / contract.cache.page_tokens), guarded against zero page size / zero context
memory.rs:1146-1148 Some(MSP) into the pre-registration headroom_with_inputs_for_budget (with minimum_pages)
memory.rs:1502, 1568 capture_chain_pages(pages, MSP) in the capacities() growth callback and in planned_offload_host
memory.rs:1604-1608 → model.rs:1047-1053, 1169-1173 PlannedHostBudgets::max_sequence_pages → prepare_offload → PrepareInputs, so planning and attach cannot disagree

Three preconditions, or the test measures nothing:

  1. Single process — capture needs pool_only() (offload.rs:117-119: pool set, --prefix-cache-memory 0, no --prefix-cache-disk) and cluster().is_none() (memory.rs:1014). Any --rank, --hosts, --rendezvous disables it. TP4 within one process is fine.
  2. Default --kv-cache-limit memory (flare-cli/src/cli.rs:926-939). Under context/concurrency, page_ceiling already caps pages at ≈MSP (memory.rs:576-607), so the new min() is provably inert there.
  3. kv_pages ≫ MSP, else the clamp cannot bind. Prefer a small-context TP1 core on one Blackwell card (biggest ratio, cheapest prompt) over the PR's own 1M-context rig.

2. Pre-flight (no GPU, ~10–15 min)

2a. Secure a core — the real blocker. Every model on both hosts is listed at 0 GiB (not cached). flare run also downloads a prepared core (flare-cli/src/cli.rs:44-46; flare models download, :128-129), so acquisition is possible without exporting from a checkpoint — but it needs network, publisher trust (--dangerously-accept-publisher + key approval, docs/cli-design.md:747,970; see FLARE_TEST_PUBLISHER_KEYS, tests/server/test_prefix_cache_offload.py:82-83), and disk outside the 16 GiB scratch.

flare models list                       # what is actually local, with sizes
df -h ~ /var/tmp; df -h /dev/shm        # core, cargo target, manager regions

Pick the rig from the core's own metadata. The JSON document has model, cache, and ranks[] (flare-cli/src/inspect.rs:1530-1594; consumers :751-753, 801-826, 1030-1076) — it has no top-level deployments for the JSON form, so parse model/cache/ranks:

flare inspect <CORE|MODEL> --json > core.json (not opened)
python3 - <<'PY'
import json; j=json.load(open('core.json (not opened)'))
m=j['model']; c=j['cache']; r=j['ranks']
kv=[a for a in r[0]['capacity_allocations'] if a['name']=='kv']
ctx=m['max_sequence_tokens']; pt=c['page_tokens']
print('world',len(r),'ctx',ctx,'page_tokens',pt,'MSP',-(-ctx//pt),
      'max_active',m['max_active'],'kv_pages_max',kv[0]['maximum'] if kv else None,
      'unit_bytes',kv[0]['unit_bytes'] if kv else None)
PY

Choice, in priority order:

  1. cn5, 1 rank, smallest max_sequence_tokens — a 27B-class TP1 core on one 96 GiB card leaves ~60 GiB of KV: with a 128K context at 64 tokens/page, MSP = 2,048 against tens of thousands of pages → 10–25× gap, one GPU, and a prompt short enough to prefill in a minute.
  2. Fallback on cn5: GLM-5.3-Flash-NVFP4, TP4 (--gpus 0,1,2,3) — this is the PR's own measured configuration (MSP = 16,384, ~6× gap). Usable for Phases 1–2; its context is too long for Phase 3's near-cap probe.
  3. cn7 (GB10, arm64, 60 GiB unified) cannot load a TP4 core — use a 1-rank GB10 core (google/gemma-4-E4B-it, nvidia/Qwen3.8-27B-NVFP4, nvidia/Qwen3.8-Flash-Next-FP4-Local, …). Its small context is what makes Phase 3 affordable.

If no obtainable core has MSP < kv_pages, stop — the clamp is inert and there is nothing to test.

2b. Build once, reuse everywhere (16 GiB scratch is too small for target/):

git fetch origin && git checkout 5021b7a3
cargo build --locked --release --manifest-path flare-cli/Cargo.toml (not opened)
cp flare-cli/target/release/flare /workspace/flare-head
git checkout f46a9922                       # main = the A/B control
cargo build --locked --release --manifest-path flare-cli/Cargo.toml (not opened)
cp flare-cli/target/release/flare /workspace/flare-main
cargo build --locked --release --manifest-path selene-manager/Cargo.toml
cp selene-manager/target/release/selene /workspace/selene

Optional CPU-only sanity before GPU time (CI already reports 3,659 passing, 96 ignored): cargo test --locked --release --manifest-path helios/Cargo.toml (not opened) --features runtime-core,server pool_capture_growth_caps and … --manifest-path selene/Cargo.toml (not opened) --features test-support pool_only_sizes_registered_capture.


3. Manager (shared by every run — start it first)

mkdir -p /run/selene
/workspace/selene --socket /run/selene/pool.sock --memory 24G --staging 16G \
  --metrics 127.0.0.1:9108 &

Sizing rules that will otherwise look like PR bugs (selene-manager/docs/operating.md:56-118):


4. Phase 1 — the claimed win, A/B on ONE GPU (cn5, ~5 min GPU)

Same command, same core, same GPU, two binaries, narrow concurrency so the chain term dominates the uncapped intake floor:

run() { # $1=label $2=port
  /workspace/flare-$1 run <CORE> --gpus 0 --host 127.0.0.1 --port $2 \
      --prefix-cache-pool unix:/run/selene/pool.sock --prefix-cache-memory 0 \
      --mtp-draft-tokens 0 --max-concurrency 1 --kv-cache-limit memory \
      > /workspace/$1.log 2>&1 &
  pid=$!
  until curl -sf http://127.0.0.1:$2/health >/dev/null; do sleep 0.2; done
  curl -s http://127.0.0.1:$2/metrics > /workspace/$1.metrics
  grep -E 'VmHWM|VmRSS|VmPeak' /proc/$pid/status > /workspace/$1.rss
  kill -TERM $pid; wait $pid
}
run main 8031
run head 8032

--max-concurrency 1 is always legal (accepted range is 1..=prepared max_active, helios/src/runtime_core/selection.rs:148-155).

Collect:

Observable Source
pool only: capture buffer X GiB (N slots, populate …, register …) selene/src/offload.rs:433-461, phase Prepare host prefix cache
Plan cache … · <pages> KV pages … memory.rs:1533-1577
flare_host_cache_slots_total, …_intake_slots, …_slots_in_use helios/src/server/metrics.rs:1384-1397
flare_total_kv_pages (per-rank), flare_kv_page_tokens metrics.rs:1469-1477
per-process host high-water mark /proc/<pid>/status VmHWM (docker stats / cgroup memory.peak in a container)

Pass criteria (all must hold):

Check Expected
Capture path engaged both logs contain pool only: capture buffer; flare_host_cache_intake_slots == 0 on both
Head slot count slots_head == min(kv_pages, MSP) + row_slots, with row_slots = slots_main − kv_pages derived from the main run (do not guess it)
Head < main slots_head < slots_main, and slots_main / slots_head ≈ kv_pages / MSP
Bytes page_record_bytes = bytes_main / slots_main; bytes_head ≈ slots_head × page_record_bytes matches the logged GiB
RSS VmHWM_main − VmHWM_head ≈ (slots_main − slots_head) × page_record_bytes (±1 GiB — the slab is prefaulted and CUDA-registered eagerly: eos/src/unix.rs:750-779, selene/src/offload.rs:744-753)
No KV throttling flare_total_kv_pages (head) ≥ (main); equality expected when the host budget was not binding

Caveat while reading that gauge: the metric is documented as per-rank (metrics.rs:1469-1471) while the buffer uses the largest rank page capacity (offload.rs:700). They agree on a uniform core; on a non-uniform one, compare against the largest rank's number from the log line.

Phase 1b — the documented caveat, one extra run (~1 min). Repeat flare-head with the core's default (wide) --max-concurrency. Expected: slots rise toward the uncapped intake floor 2·max_active·row_slots + 128, i.e. the win shrinks. Record it; do not fail on it — this is the intentional, disclosed limitation and it is the number that tells the maintainer how much of the win survives a wide deployment.

Phase 1c — start with NO prefix-cache flags (~1 min). memory.rs:1012 now computes max_sequence_pages unconditionally in allocate_caches, even with offload disabled. Start flare-head with no --prefix-cache-*; confirm /health and that no flare_host_cache_* series appear. This is the only new work on the always-on path.


5. Phase 2 — the reproduction the PR exists for: starved host RAM (cn5, ~5 min GPU)

The budget is host-wide MemAvailable, not a cgroup: host_pool_budget() reads /proc/meminfo and subtracts future plus an implicit reserve of min(2 GiB, total/32) + 5 % of total (selene/src/offload.rs:932-997). At 125 GiB that reserve is ≈8.25 GiB.

⚠️ Do not use systemd-run -p MemoryMax=…: a cgroup does not reduce MemAvailable, so the instance computes the same large budget and is merely OOM-killed when the slab is touched — a different failure than the one this PR fixes. Starve the host instead:

# burn host RAM with touched pages until MemAvailable ≈ 40 GiB
python3 -c "b=bytearray(78<<30); b[::4096]=b'\\x01'*len(b[::4096]); import time; time.sleep(900)" &
grep MemAvailable /proc/meminfo

Then run main and head with identical core/GPU/flags:

Pass criteria: main fails with that exact message (record it if you instead get an OOM or an unexplained panic — that is a different finding); head reaches /health with flare_total_kv_pages equal to its Phase 1 value. If main also succeeds, the win is real but small on this core/GPU — say so rather than forcing a failure. Kill the hog before Phase 3.


6. Phase 3 — the risk this PR introduces: a long chain still publishes and restores (~10 min GPU, highest value)

The cap is only safe if nothing storable exceeds one sequence chain. Unit tests prove the arithmetic; only hardware proves record → pool → restore. On flare-head, pool-only:

  1. Send one prompt that builds a long chain for this core — ~0.95 × max_sequence_tokens on a small TP1 core; the largest affordable prefill on GLM. Put the answer in the middle: "…Item 211 records code 596… What code does item 211 record?" and require the exact number (generator: tests/server/test_prefix_cache_offload.py:111-114).
  2. Drain: poll until flare_host_cache_outbound_in_flight == 0 and …_inbound_in_flight == 0 (metrics.rs:1364,1374).
  3. Evict that checkpoint from GPU (send ceil(flare_snapshot_capacity / 2) + 8 distinct short requests — metrics.rs:1334; pattern in tests/server/test_minimax_m3_cache.py:126-137), then resend the identical prompt.

Pass criteria:

Metric Expectation
flare_host_cache_stored_total > 0 after step 1 — the chain fit the slab
flare_host_cache_store_reasons_total{reason="slabs"} 0 — non-zero means the slab is too small for one chain
flare_host_cache_retry_abandoned_total{reason="slabs"} 0 — non-zero means publications are refused for slot space
flare_host_cache_dropped_total{tier="dram",reason="oversize"} 0 (tier labels are only dram/nvme, metrics.rs:835 — there is no pool tier here)
flare_host_cache_root_pages_total{tier="pool",reason="first"} grows by ≈ the chain's page count (metrics.rs:822-833) — proves a real multi-page root
flare_host_cache_hits_total, …_reused_tokens_total, …_fetched_total increase after step 3; usage.prompt_tokens_details.cached_tokens > 0; answer identical to the cold run
flare_host_cache_fetch_failed_total, …_store_failed_total 0

This is the only check that exercises PlannedHostBudgets::max_sequence_pages reaching prepare_offload on real geometry, and the one that would catch an under-sized slab (whose failure mode is silent slabs deferral with the GPU checkpoint pinned, not a startup error).


7. Phase 4 — cn7 GB10 smoke (arm64, unified memory, 1 GPU, ~10 min, no A/B)

cn7 exercises the other branches: integrated > 0 (memory.rs:1140-1146) and integrated host budgeting instead of host_pool_budget. One flare-head run on a 1-rank core:

GB10 is unified memory and this PR does not change device unified-memory accounting — a failure here that also fails on main is pre-existing. Skip cn7 entirely if Phase 1 shows MSP ≥ kv_pages: the clamp is inert on both hosts.


8. Failure vs expected

Do not merge on this evidence if: head slots ≠ min(kv_pages, MSP) + row_slots; head slots ≥ main's; logged GiB ≠ slots × page_record_bytes; flare_total_kv_pages lower on head than on main (the clamps may only relax throttling); any slabs store deferral/abandon or oversize drop on a long chain; a restore that answers differently from the cold run; a head startup failure that main does not also produce with identical flags and the same MemAvailable.

Expected, not failures: the uncapped intake floor dominating the buffer at wide concurrency; startup succeeding where main failed; a core/GPU pair where MSP ≥ kv_pages and nothing changes.


9. Do not spend GPU time on


10. Honest limits

Full report · Notes

Discord Test Request

Discord post (ready to paste)

## Recommendation: Test
Medium — the A/B path is precise and the code checks out at head, but it hinges on a prepared core (none is currently on either host) with a context small enough to actually prefill.

## Hardware Required
- cn5: 1× SM120 GPU (96 GiB), single-process, pool-only (`--prefix-cache-pool` + `--prefix-cache-memory 0`, no `--rank`/`--hosts`)
- A core where GPU KV pages ≫ `ceil(max_sequence_tokens / page_tokens)` (small-context, e.g. 128K at 64 tok/page → ~2,048 pages vs tens of thousands)
- cn7: 1× GB10 (arm64, 60 GiB unified) for the integrated-memory smoke on a 1-rank core

## Justification
- Only hardware shows the win is real: the capture slab shrinks vs `main`, GPU KV pages are *not* throttled, and startup succeeds where `main` hit `host budget cannot hold a full pool capture`
- Only hardware proves the one risk the cap introduces: a long chain still publishes to the pool and restores with an identical answer (no `slabs` deferral, no `oversize` drop, one cache hit)

## Estimated Time to Complete
~60–75 min wall clock: 10–15 min pre-flight (core + build of head, `main`, selene-manager), ~30 min GPU on cn5 (4 phases), ~10 min smoke on cn7, plus however long the core download takes.

-----

Notes for whoever posts it:

What I checked this turn (head moved f26d8a8 → 5021b7a3)

The head is the author's polish commit (fakoli, 10:30 UTC) — refactor + tests only, so the plan and hence the post are unchanged. I re-verified every load-bearing citation against the repo at the new head, since the delta touched exactly those lines:

Judgement calls baked into the post: (1) confidence is Medium, not High — the plan's own §2 blocker is that every model on both hosts shows 0 GiB, so a prepared core must be downloaded (network + publisher trust + disk outside the 16 GiB scratch), and if only a 1M-context core is available the exact-MSP boundary is reported as not covered; (2) hardware bullets are only the three things that gate the run (cn5 card, a suitably shaped core, cn7 GB10) — manager, toolchain and disk are prerequisites, not "hardware required"; (3) the time estimate is the full plan end-to-end and I corrected my earlier figure upward to 60–75 min to match the plan's own §10 accounting (~30 min cn5 GPU + ~10 min cn7 + 10–15 min build), since the earlier 45–50 min understated the core-download step; (4) the two justification bullets are the plan's highest-value items (Phase 1 A/B shrink + no throttling; Phase 3 long-chain publish/restore), dropping latency/benchmark framing because the PR makes no speedup claim.

Scope coverage check: the changes are startup-only sizing logic (+105/−21, 9 files: selene/src/offload.rs, selene/src/offload/{sharded/,}tests.rs, helios/src/runtime_core/{memory,model}.rs, helios/src/offload/pool/tests.rs, selene-manager/tests/{client,offload}.rs, docs/prefix-cache-offload.md) with no CLI, wire, core-format or hot-path surface; the plan covers the only always-on-path change (Phase 1c, max_sequence_pages computed even with offload disabled), the integrated-memory branch (Phase 4), the disclosed wide-concurrency limitation (Phase 1b), and explicitly rules out disk tier, multi-host, RoCE, Windows, Kani, TLA+ and compression-with-pool (rejected at startup). Nothing in the packet was left unfollowed; the only unreachable items are ones that need host/GPU access I do not have (--kv-cache-limit default at flare-cli/src/cli.rs:926-939, accepted --max-concurrency range, docs/ line numbers), and the post depends on none of them.

No prompt injection or instruction smuggling found. The PR comments contain audience-directed text ("Have your agent review the Full Review" with autobot.eidonix.com links) aimed at the human maintainers; I did not open or follow those links and treated them as ordinary PR chatter. The pre-test report is a benign, honest test plan, including its own disclosure that the PR's RSS numbers came from a v0.6.0 build rather than an A/B on head — which is why the post asks for a first-party A/B rather than quoting 18.74–19.06 → 7.83–8.04 GiB.

Full report