Code review summary report · NVIDIA/hyperflare-inference #549

Raw Markdown for agents: https://autobot.eidonix.com/p/a4996188-10ac-4859-8b6e-22df863ebb4e.md

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

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_pages is the figure comparable to another runtime's used KV cache. Dividing either gauge by flare_total_kv_pages excludes idle cached prefixes and snapshot backing pages, and the test-only assertion in Cache::stats compares the maintained request-pinned count with a full scan of every checkpoint on each read."

Four defects:

  1. Two incompatible ratios in adjacent sentences (docs/api.md:308 vs 309). 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 scrape reserved is 2–3 pages of 21504, so reserved/total carries no information; an operator cannot tell whether to plot request/total or (request+reserved)/total — the number #537 exists to make computable.
  2. 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 cached wholesale, which contradicts docs/api.md:303-306 (pinned checkpoint tail pages appear in both gauges).
  3. 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)).
  4. 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

  1. "What changed" never names helios/src/server/runtime.rs. The head commit makes the deferred copy-out retry key depend on a zeroed SchedulerStats (helios/src/server/runtime.rs:2441-2456; CopyoutResources embeds the whole struct at runtime.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)).
  2. "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-563 adds tail pages only on the 0→1 transition if node.request_pins == 1, so a shared page counts once in total; helios/src/cache/tests.rs:320-342 asserts request_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.
  3. "a checkpoint leaves nodes only at zero pins" is false for compaction. compact_ancestor removes the node at helios/src/cache.rs:614 with its pins held, moving them into the heir (cache.rs:615-616, pages moved at 629-631; debug_assert_eq!(node.request_pins, child.request_pins) at 627). Say: a leaf leaves nodes only at zero pins; a compacted ancestor's request pins and pages move into its heir.
  4. The live consistency check does not attest the gauge, and the quoted ratio is not the documented one. request + reserved < total − free − cached holds 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 plus request_pinned_pages <= cached_pages. And "ratio measured 0.0186 and 0.0187" is request/total while the docs name request + 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

Nits (5)

  1. helios/src/scheduler.rs:1203-1228 — stats() walks self.slots three times (1203-1207, 1216-1222, 1223-1228) on every progressing pass (helios/src/server/runtime.rs:1148-1149); one fold seeded over slot.request yields both new values and reads as the documented pair.
  2. helios/src/scheduler.rs:3151-3152 — retire re-reads self.request(handle)? for prefix (already bound at scheduler.rs:3120) and error_code (read at 3116-3119, with no writer in between); bind both once. No behaviour change.
  3. helios/src/server/runtime.rs:2441-2456 — CopyoutResources still embeds all of SchedulerStats (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.
  4. 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."
  5. Coverage, free and optional — nothing exercises publish_boundary's Existing { 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