PR #549 — Report KV pages held by active requests
Reviewed at head 9cca87ac ("Keep page gauges out of the copy-out retry key"), draft, 8 files, +246/−16 (docs/api.md, helios/src/cache.rs, helios/src/cache/lifecycle_tests.rs (not opened), helios/src/cache/tests.rs, helios/src/scheduler.rs, helios/src/scheduler/tests.rs, helios/src/server/metrics.rs, helios/src/server/runtime.rs). Closes #537. Sibling metrics PRs are #548 ("Add request latency histograms and process metrics") and #553; neither changes code this PR touches.
Verdict: Changes Requested — small. The previous rounds' blocker is fixed at this head (the two gauges are zeroed when the copy-out retry key is built), as are the retire pin-ordering defect and the misleading cache.rs doc comment. What remains is one API paragraph that contradicts itself, four mechanical accuracy defects in the PR description, and about 75 of the 246 added lines that can simply be deleted. Nothing below asks for new code, a new flag, a new test, or new documentation.
Key findings
- Scope and approach are right. Confined to shared runtime layers — KV cache accounting (
helios/src/cache.rs), scheduler statistics (helios/src/scheduler.rs), the Prometheus renderer (helios/src/server/metrics.rs),docs/api.md. No per-model branch, no boolean policy flag, no environment switch, no allocation/eviction/preemption/readmission change. Matches the charter ("keep the runtime small and model-agnostic"; "look for the smallest footprint in shared code") andAGENTS.md:165-200(not opened). - The stated constraint holds.
Cache::statsstill does not scannodes; the count is maintained on the pin paths (helios/src/cache.rs:551-580) and the scheduler adds per-slot counts (helios/src/scheduler.rs:1216-1228). Work is bounded per pin operation; no steady-state cost class changes. - The previously reported blocker is fixed — do not re-raise it.
helios/src/server/runtime.rs:2441-2456builds theCopyoutResourceskey withSchedulerStats { request_pages: 0, reserved_pages: 0, ..self.scheduler.stats() }(2446-2449), compared at2455, so page movement between reserved and private pages no longer re-offers deferred host copy-outs. Residual coupling only — Nit 3. - Also fixed at this head:
retirereleases the request pin before emptying the slot (helios/src/scheduler.rs:3149-3157);pin_request's doc comment states the cache's half and points at the scheduler (helios/src/cache.rs:548-550); the three mirroredif inbound.is_none()pin branches became one dispatcher (helios/src/scheduler.rs:2025-2040). - Verified correct — do not re-flag: pin/release symmetry on every path (admission
helios/src/scheduler.rs:1645/1656/1678; ticket waiters1889; boundary publication2977/2979/2997/2998; retirement3155), ticket-parent pins keeping the plain API (1871,1907), copy-out viapin_checkpoint(2044/2048);request_pinned_pagesmoving only at the 0↔1 transition ofrequest_pins(helios/src/cache.rs:551-580); compaction carrying request pins into the heir (helios/src/cache.rs:613-631, assert at627); eviction gated onpins == 0(helios/src/cache.rs:658-663); gauges inside the existing gauge array (helios/src/server/metrics.rs:1309-1318), stored in the bulk table (metrics.rs:517-518), absent from the JSONSnapshot; reserved pages genuinely "neither free, cached, nor written" (popped fromfree_pagesathelios/src/scheduler.rs:1721-1724, consumed intoprivate_pagesatscheduler.rs:2439-2444); retirement drain and in-flight restore tickets outside both gauges (helios/src/scheduler.rs:1887-1899,3177-3191). - Explicitly not pressed: a
docs/runtime-core-design.md(not opened) entry (more prose, not less); an extra test forpublish_boundary'sExistingbranch (cheapest coverage is the S-1 fixture merge, Nit 5); deletingCheckpoint::direct_request_pins; deletingflare_reserved_kv_pageswhile the docs namerequest + reserved; removing the runtime zeroing block — see "Answered, not cut" under Subtract.
Blockers
None. Correctness is clean at this head, architecture reports no blocking issue, prose has no blocking defect, and the gauges' semantics are exercised by two tests plus the test-only drift assertion.
Should Fix (2)
SF1. docs/api.md:298-312 — two incompatible ratios, misattributed exclusions, a test hook, wrong cadence
Current docs/api.md:307-312:
"Reserved pages are outside the request gauge, so
flare_request_kv_pages + flare_reserved_kv_pagesis the figure comparable to another runtime's used KV cache. Dividing either gauge byflare_total_kv_pagesexcludes idle cached prefixes and snapshot backing pages, and the test-only assertion inCache::statscompares the maintained request-pinned count with a full scan of every checkpoint on each read."
Four defects:
- Two incompatible ratios in adjacent sentences (
docs/api.md:308vs309). Line 308 says the sum is the comparable figure; line 309 says either gauge divided by total gives the share. By the author's own scrapereservedis 2–3 pages of 21504, soreserved/totalcarries no information; an operator cannot tell whether to plotrequest/totalor(request+reserved)/total— the number #537 exists to make computable. - Exclusion misattributed. The division is not the cause; what is left out is a property of the numerator. "idle cached prefixes" also reads as excluding
cachedwholesale, which contradictsdocs/api.md:303-306(pinned checkpoint tail pages appear in both gauges). - A
#[cfg(test)]assertion in the operator-facing API page (helios/src/cache.rs:818-837) — validation evidence, which belongs in the PR body (docs/design-review.md(not opened) principle 16;.agents/skills/repo-prose/SKILL.md:26-29(not opened)). - Cadence overstated at
docs/api.md:302-303("on every scheduler pass"): the worker stores only when a pass reports progress (helios/src/server/runtime.rs:1148-1153), plus startup (runtime.rs:722) and the post-shutdown drain (runtime.rs:745).
Requested replacement for docs/api.md:298-312 (net −2 lines, no new claims added):
`flare_request_kv_pages` counts the distinct KV pages that requests owning a
model slot reference: their private pages plus the tail pages of the prefix
checkpoints they pin, each page counted once even when several requests
reference it. It is not disjoint from `flare_cached_kv_pages`: a pinned
checkpoint stays published, so its tail pages count in both gauges. Neither
gauge counts pages draining after a request retires, or an admission ticket's
in-flight restore. `flare_reserved_kv_pages` counts pages reserved for those
requests' growth that are neither free, cached, nor written yet. The worker
publishes both when a scheduler pass makes progress, and a scrape reads the last
published values. `(flare_request_kv_pages + flare_reserved_kv_pages)` over
`flare_total_kv_pages` is the share comparable to vLLM's `kv_cache_usage_perc`;
idle cached prefixes and snapshot backing pages are outside it.
Why "requests owning a model slot" and not "active requests": SchedulerStats::request_pages sums private_pages only over slots whose request is Some (helios/src/scheduler.rs:1216-1222), while inbound_waiting counts an Inbound restore-ticket request as active (scheduler.rs:1229-1232) even though its pages are in neither gauge. Stating the narrower set keeps the prose true. Rules: AGENTS.md:165-166 (not opened) requires contributions to address inaccurate documentation; principle 16 requires prose a reviewer can reconstruct the argument from without the diff.
SF2. PR description — four mechanical accuracy defects, one editing pass
- "What changed" never names
helios/src/server/runtime.rs. The head commit makes the deferred copy-out retry key depend on a zeroedSchedulerStats(helios/src/server/runtime.rs:2441-2456;CopyoutResourcesembeds the whole struct atruntime.rs:1053-1059). That is the behavioural change which makes "No allocation, eviction, or scheduling decision changes" true. Add a bullet saying so and why (decode moves page counts without moving cache resources), and a matching clause under Evidence if the blocked-host-cache tests exercise the re-offer path, otherwise say that path was not separately measured (AGENTS.md:103-112(not opened)). - "A page shared through a pinned ancestor therefore counts once for every request that references it" is wrong and contradicts the PR's own test.
helios/src/cache.rs:551-563adds tail pages only on the 0→1 transitionif node.request_pins == 1, so a shared page counts once in total;helios/src/cache/tests.rs:320-342assertsrequest_pinned_pages == 3, not 4. As written it makes the reported 399/402 of 21504 look implausible. Say: counted once in the total, however many requests pin checkpoints below it; per-request totals add each request's private pages. - "a checkpoint leaves
nodesonly at zero pins" is false for compaction.compact_ancestorremoves the node athelios/src/cache.rs:614with its pins held, moving them into the heir (cache.rs:615-616, pages moved at629-631;debug_assert_eq!(node.request_pins, child.request_pins)at627). Say: a leaf leavesnodesonly at zero pins; a compacted ancestor's request pins and pages move into its heir. - The live consistency check does not attest the gauge, and the quoted ratio is not the documented one.
request + reserved < total − free − cachedholds trivially because the right side is dominated by snapshot-backing pages (helios/src/server/metrics.rs:1294-1298). Cite the drift assertion (helios/src/cache.rs:818-837) instead, optionally plusrequest_pinned_pages <= cached_pages. And "ratio measured 0.0186 and 0.0187" isrequest/totalwhile the docs namerequest + reserved— label which one was measured.
Rules: AGENTS.md:88-102 (not opened) (name the affected components, make before/after explicit, state the effect precisely) and AGENTS.md:135-137 (not opened) (do not publish a description whose exact change must be guessed).
Subtract / Simplify (3 items, ~75 of +246 lines ≈ 30%; up to ~100 if flare_reserved_kv_pages also goes)
Nothing here adds a parallel mechanism: the gauges reuse the existing gauge array, the bulk update table and the expected-exposition rows; no second representation of the count exists. The deletions below remove duplicated fixtures and a duplicated chain walk — no requested behaviour is lost.
S-1 (~45 lines) — the new scheduler test re-runs the test directly below it
request_kv_pages_count_shared_prefix_pages_once (helios/src/scheduler/tests.rs:970-1034, 65 lines) repeats branching_requests_own_distinct_tail_pages_and_terminal_snapshots (helios/src/scheduler/tests.rs:1036-1081) step for step: same scheduler(2, 8, 5), same seed admit / init / plan / commit Fence(2) / complete / freeze(3) / finish, same two admit(spec(65, 4)), same Fence(5) completion, retain_prompt(6), prefill-lane assertion, Fence(7) completion. Lines 972-1009 are identical to 1038-1075; the existing test already asserts the shared page counts are equal (1078) and the private page counts differ (1079). Only 1010-1033 is new evidence.
Delete the test; append this to the existing one (keeping the handles rather than shadowing them at 1076-1077):
let (shared, private, reserved) = (
first.shared_pages.len(),
first.private_pages.len() + second.private_pages.len(),
first.reserved_pages.len() + second.reserved_pages.len(),
);
assert!(!first.shared_pages.is_empty());
let stats = scheduler.stats();
assert_eq!(stats.request_pages, shared + private);
assert_eq!(stats.reserved_pages, reserved);
scheduler.cancel(first.handle).unwrap();
scheduler.cancel(second.handle).unwrap();
let stats = scheduler.stats();
assert_eq!((stats.request_pages, stats.reserved_pages), (0, 0));
assert!(stats.cached_pages > 0);
Take the lengths into locals before the cancels (the borrow comes back for cancel); LiveRequest::handle is public (helios/src/scheduler.rs:226). Every proven behaviour survives — shared page counted once, per-request private pages, retire/cancel to zero — on a fixture the suite already pays for (AGENTS.md:194-199 (not opened)).
S-2 (~10 lines) — the new cache test repeats the fixture below it
helios/src/cache/tests.rs:322-328 is character-identical to 346-352 inside branching_pins_ancestors_and_prevents_direct_ancestor_unpin. Because pin_request calls pin first (helios/src/cache.rs:552), the existing test can take its pins through pin_request/unpin_request and gain the request_pinned_pages assertions without losing its pin_count() checks. Also drop helios/src/cache/tests.rs:335 (cache.unpin_request(parent).is_err()): it re-tests the "no direct pin" guard already covered at tests.rs:358, and parent holds no direct request pin, so it is not evidence for the test's named claim (shared page counted once). Caveat: request pins inserted at tests.rs:356 change the counts asserted at 357-386; fold after :372 or adjust the two pin_count() expectations.
S-3 (~20 lines) — pin_request/unpin_request duplicate pin/unpin's guards and walk the chain twice
pin (helios/src/cache.rs:519-534) and unpin (helios/src/cache.rs:536-546) each compute self.chain(id)? once and own their whole invariant inside that walk, including the refcount-exhaustion guard (cache.rs:524-528). pin_request calls self.pin(id)? and then chains again (cache.rs:552-554); unpin_request does the same (cache.rs:569-571). Result: two walks and two Vec<CheckpointId> allocations per request pin and per release, on admission (helios/src/scheduler.rs:1645), ticket waiters (1889), both boundary publications (2977, 2997), retirement (3155), and both rollback arms (1656, 1678); the request_pins ⊆ pins invariant now lives in two function pairs whose only detector is the test-only drift assert (helios/src/cache.rs:818-837). Fold into one private worker:
fn pin_with(&mut self, id: CheckpointId, request: bool) -> Result<()> {
if !self.checkpoint(id)?.ready { return Err("cannot pin a checkpoint before GPU readiness".into()); }
let chain = self.chain(id)?;
if self.nodes[&id].direct_pins == u64::MAX
|| chain.iter().any(|id| self.nodes[id].pins == u64::MAX) {
return Err("checkpoint reference count exhausted".into());
}
self.nodes.get_mut(&id).unwrap().direct_pins += 1;
if request { self.nodes.get_mut(&id).unwrap().direct_request_pins += 1; }
for ancestor in chain {
let node = self.nodes.get_mut(&ancestor).unwrap();
node.pins += 1;
if request {
node.request_pins += 1;
if node.request_pins == 1 { self.request_pinned_pages += node.tail_pages.len(); }
}
}
Ok(())
}
pub fn pin(&mut self, id: CheckpointId) -> Result<()> { self.pin_with(id, false) }
pub fn pin_request(&mut self, id: CheckpointId) -> Result<()> { self.pin_with(id, true) }
Mirror unpin_with(id, request), keeping the direct_request_pins == 0 check when request == true and adding debug_assert!(node.request_pins > 0) at the 1→0 transition (the usize subtraction at cache.rs:576 is otherwise guarded only by an invariant). This gives the 0↔1 transition — the only place request_pinned_pages moves — a single site, and the existing tests at helios/src/cache/tests.rs:320-342 keep passing unchanged.
Answered, not cut
flare_reserved_kv_pages(~22-25 lines) stays while the docs namerequest + reservedfor vLLMkv_cache_usage_percparity, which SF1 states. If SF1 is instead answered by reducing the paragraph torequest/total(what #537 literally asks and what the description actually measured), it becomes cleanly deletable:helios/src/scheduler.rs:132-133,1223-1228;helios/src/server/metrics.rs:266,518,1314-1318,1791,1836; thedocs/api.mdreserved clause — andhelios/src/server/runtime.rs:2448shrinks to one zeroing line.Checkpoint::direct_request_pinsstays (helios/src/cache.rs:82-83,461,553,566-568,570): a checkpoint can be pinned by a request and for host copy-out (pin_checkpoint,helios/src/scheduler.rs:2044), so a duplicated release would silently driverequest_pinsbelow truth instead of erroring; the guard atcache.rs:566-568is the only release-build detector.- The runtime zeroing block stays (
helios/src/server/runtime.rs:2443-2450) — it is what makes the head truthful; its permanent replacement is Nit 3. pin_prefix/unpin_prefix(helios/src/scheduler.rs:2025-2040) stay: net +4 lines over the three inlineif inbound.is_none()branches they replaced, and they encode the admission pin kind once; routing the four directcache.pin_requestcalls through them would be line-neutral.- Keep — best value per line in the change:
PrefixCheckpointCache::request_pinned_pagesand its 0↔1 brackets (helios/src/cache.rs:551-580); the compaction agreement assert (cache.rs:623-627); the drift assertion (cache.rs:818-837, compares the maintained count with a full scan ofnodeson every stats read in test builds); therequest_pages/reserved_pagessums; the atomic/store/render triple; the first three lines of thedocs/api.mddefinition.
Nits (5)
helios/src/scheduler.rs:1203-1228—stats()walksself.slotsthree times (1203-1207,1216-1222,1223-1228) on every progressing pass (helios/src/server/runtime.rs:1148-1149); onefoldseeded overslot.requestyields both new values and reads as the documented pair.helios/src/scheduler.rs:3151-3152—retirere-readsself.request(handle)?forprefix(already bound atscheduler.rs:3120) anderror_code(read at3116-3119, with no writer in between); bind both once. No behaviour change.helios/src/server/runtime.rs:2441-2456—CopyoutResourcesstill embeds all ofSchedulerStats(runtime.rs:1053-1059), so every future gauge joins the copy-out retry key by default and needs a second edit here; the smaller long-term shape is a key holding only the cache fields copy-out depends on (free_pages,free_snapshots,cached_pages, snapshot backing, retiring slots). That changes which page movements re-offer deferred copy-outs, so it needs its own justification — a note, not a request.helios/src/cache.rs:626— "Both nodes are counted or neither is, and the pages move into the counted heir": "counted" does two jobs. Say "The ancestor's request pins equal its heir's, and its pages move into that heir."- Coverage, free and optional — nothing exercises
publish_boundary'sExisting { ready: true }re-pin (helios/src/scheduler.rs:2994-3006), the one place a second request pins a checkpoint another request already pinned. Cheapest reach is the S-1 merged fixture; do not add a test.
Open questions, process notes, and what could not be verified
- No CI run on the head commit in this environment, so the 508-test figure in the description is taken on trust (the named tests were read and match their claims). Windows build and the full helios suite are CI's job.
- The live scrape numbers (399/402 request pages, 2–3 reserved, 2037/2043 cached of 21504, ratios 0.0186/0.0187) come from a validation tree on fork commit
5ffe4d54(upstream PR #482 plus #536/#548) and are not reproducible from this branch. The description discloses the instance, the two-GPU configuration, the agent session's own traffic contaminating the gauges, and claims no comparison — honest; do not press. - No table rows for the two gauges in
docs/api.md:332-355is correct and not a finding: that table maps JSONSnapshotfields and these gauges are deliberately text-only (consistent with the "beyond the JSON fields below" sentence atdocs/api.md:292-296). - The description's cross-reference "#536" for the sibling metrics PR that adds the other region of
helios/src/server/metrics.rsis probably meant to be #548 (same author, also metrics). Both touch disjoint regions (cached_pagesvs. the completion counter), so merge order is not a risk; the author should confirm the number. - Authorization —
AGENTS.md:165-169(not opened) admits contributions that address "a demonstrated defect … or inaccurate documentation", which #537 does; whether a user-filed issue is sufficient authorization (AGENTS.md:201-205(not opened)) is for the owners to confirm, not this review. - An Inbound restore-ticket request contributes nothing to
request_pages(itsprefixisNoneuntilfinish_inbound) and nothing toreserved_pages, while its ticket's pages are held out offree_pages, yetSchedulerStats::inbound_waiting(helios/src/scheduler.rs:1229-1232) counts it as active. The SF1 replacement wording ("requests owning a model slot") states the exclusion rather than changing the count; counting ticket pages would be new behaviour and is not requested. - Whether the duplicate chain walk is measurable is unresolved (needs a micro-benchmark); S-3 stands on structure alone, and the PR claims no performance change either way.
- Sibling-PR merge order (#548/#553) was not verified against their diffs; the affected regions of
helios/src/server/metrics.rsdo not overlap this PR's lines.