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

Raw Markdown for agents: https://autobot.eidonix.com/p/974936e4-bbd6-42b8-83bd-50a986626a56.md

Full review — PR #548 "Add per-request histograms and vLLM-parity request metrics"

Head 055663a (commits 15018689, 10c0b937, 01f1e92b, 54e06b30, 49373bc5, 055663a), base main, 9 files, +1016/−51, no reviews and no CI checks on the head. Closes #536 (per the description). Every citation below was re-read at this head; the companion lenses were Architecture, Conventions, Simplicity, Correctness, Prose and Subtraction, and conflicts between them are resolved in favour of subtraction throughout.

Key findings

Verdict: changes requested, and nothing blocks. The design is right and it is in the right place: Metrics::request_completed (helios/src/server/metrics.rs:545-603) holds the only completed.fetch_add in helios/src (metrics.rs:558), so flare_requests_completed_total and the per-request histograms cannot drift; the only per-request state is a RequestRecord on Incoming (metrics.rs:336-346), which survives parking because the whole struct is parked; there is no configuration flag, no per-model branch, no Snapshot/format=json change, no Cargo change, and nothing touches scheduling, eviction, response bodies or cache state. The recorded observations are the minimum #536's table asks for.

The previous round's two blockers are gone and must not be re-raised. Commit 54e06b30 deleted helios/src/server/metrics/process.rs (not opened) and its render call, which removes the cross-feature reference that broke the documented --features server lane; open_descriptors is private again and no process_* series remain in the tree. And the evidence now reconciles: the description says "Read from the code; no benchmark was run", itemises per-step, per-request, per-admission and per-scrape cost, states "This cost was not measured in isolation", and its live run closes its own arithmetic (24 completions = the time-to-first-token and generated-token count deltas, generated sum 3,112 = the flare_generated_tokens_total delta, e2e count 22 = delivered responses for 24 completions with an n=2 batch). I re-derived the scrape arithmetic and it is right: 17 histograms = 6×21 + 2×19 + 5×21 + 6 + 9 + 21 + 21 = 326 bucket loads, and 394 exposition lines = Σ(N+4).

What remains is one authorization question, one latent population bug at the HTTP gate, one histogram-convention gap, and a diff that can shrink by roughly a quarter — about 245 of the 1,016 added lines — by deleting mechanisms rather than adding them. Three should-fix items, eight subtractive items, six nits.

Verified sound — do not re-derive. Counter/histogram coupling (metrics.rs:558, called from runtime.rs:1875 and :2038); a zero-token completion enters token-count and preemption histograms only (metrics.rs:562-576, docs/api.md:334-336); decode and time-per-output-token require ≥2 generated tokens (metrics.rs:593-602); a preemption is counted only in park_if_preempted (runtime.rs:2109-2111) and not in the reasoning-budget park, matching docs/api.md:373-375; the position == 0 stamp (runtime.rs:1801-1806) makes one interval per committing step, so a speculative round is one observation; the bucket and render arithmetic (observe uses exposed <= bound with unwrap_or(N - 1), cumulative count equals the +Inf line, metrics.rs:272-283, :297-321); admission rejections are counted at exactly the three queue-limit sites (server.rs:816, http.rs:240, runtime.rs:869, :945) and not on the two 503 paths; flare_model_step_tokens observes the documented graph set; the JSON snapshot and the terminal dashboard never see the new families; cache_lookup_tokens sits at the same site as cache_lookups (scheduler.rs:1601, :1802). I also spot-checked every non-histogram series the new mapping table names — flare_preemptions_total (:1437), flare_prefill_tokens_total (:1332), flare_verification_draft_tokens_total (:1352), flare_accepted_draft_tokens_total (:1342), flare_draft_request_rounds_total (:1347), flare_cache_reused_tokens_total (:1412), flare_host_cache_reused_tokens_total (:1452), flare_host_cache_lookups_total (:1442), flare_host_cache_inbound_in_flight (:1729), flare_input_cache_payload_hits_total/_misses_total (:25-26), flare_speculative_drafts_total (:1317), flare_decode_weight_bytes (:1804), flare_cached_kv_pages (:1704), flare_total_kv_pages (:1794) — all exist.

One claim from an earlier round is false and is withdrawn. The suggestion that flare_cache_lookup_tokens_total can never reach a 100 % hit rate is disproved by this PR's own scheduler test: terminal_checkpoint_full_prompt_hit_restores_and_resumes_without_prefill (scheduler/tests.rs:850-886) restores a full-prompt checkpoint and asserts three lookups, two hits and 128 reused tokens of 192 offered — 2×64 tokens reused for a 64-token prompt — because a resumed request generates from the restored state (scheduler.rs:344, RequestPhase::Resume when consumed_tokens == prompt_tokens). Do not raise it.


Blockers (0)

None. The build break and the unreconciled-evidence findings from the previous round are both fixed by 54e06b30 and the description rewrite (see Key findings).


Should Fix (3)

S1 — A response whose other choice trips the parallel-tool limit loses its sibling choices' HTTP observations

helios/src/server/http.rs:604-612

// One observation per successful response: a tool-limit cancellation reaches
// this point but the runtime counts it as cancelled, so it is excluded.
if !count && !encoder.tool_limit_reached {
    state.model.metrics().response_completed(
        admitted_at.elapsed().as_nanos() as u64,
        decoded.request.choices,
        &generated,
    );
}

tool_limit_reached is one flag for the whole response: declared at helios/src/server/protocol/encode.rs:89, initialised false at :142, set at :506 (if !self.parallel_tool_calls && self.outputs[index].has_tools() { self.tool_limit_reached = true; break; }), consumed without an index at http.rs:476 and :569, and read again at encode.rs:598 and :604. Per-choice state is separate: generated[index] = generated_tokens at http.rs:530 over let mut generated = vec![0u32; size]; (http.rs:407), one element per generation. The runtime counts each choice as its own completed request before the HTTP layer decides — runtime.rs:1875-1884 (stop path) and :2038-2047 (output-limit path) — and cancellation has its own counter (runtime.rs:1330, :1351, :1373, :1420). So for a naturally finished sibling the runtime counted the completion and observed every runtime histogram, while http.rs:606 suppresses flare_request_e2e_seconds, flare_request_choices and flare_request_max_choice_generated_tokens for the whole response. docs/api.md:311-314 lists only two exclusions — /v1/messages/count_tokens and "responses the runtime records as cancelled" — and a sibling choice is not that; the mapping row at docs/api.md:501 repeats it.

It is latent, not live: n > 1 is accepted only for Protocol::Completions (helios/src/server/protocol/decode.rs:753-755), and tools are rejected outright for Completions (decode.rs:813-815), so no public request reaches "several generations plus tools" today. It goes live the moment either restriction is lifted.

Requested change: decide per finished generation — record which indices finished Termination::Cancelled at http.rs:531-532 and pass only the surviving choices' counts, observing e2e once when at least one choice was delivered — or, if the response-wide exclusion is intended, document it in docs/api.md:311-314 ("a response in which any choice hits the parallel tool limit contributes no e2e or choice observations for any of its choices"). If Subtraction item 2 is taken, this gate reduces to if !encoder.tool_limit_reached plus the single e2e observation.

S2 — Authorization: the closing keyword no longer matches its issue, and competitor parity has become the organizing principle

PR description ("Closes #536"); docs/api.md:475-515; issue #536; AGENTS.md:165-169 (not opened), :188-193, :201-203; charter, "What gets merged" and "Alternatives / Competitors".

(a) Closes #536 overstates the delivery. Issue #536 (Napuh) is titled "Metrics: add request latency histograms and process metrics for monitoring parity with vLLM", and its body tabulates the four standard process_* series it wants (process_cpu_seconds_total, process_resident_memory_bytes, process_open_fds, process_start_time_seconds). Commit 54e06b30 removed exactly that half, and the description now concedes it in one sentence ("outside its scope"). Closes would mark the issue resolved with one of its two stated deliverables neither shipped nor deferred to a tracked issue. Requested change: reference #536 without Closes, and name where the process metrics go (a follow-up issue, or an explicit "not planned").

(b) The gap widened rather than closed. Earlier rounds asked for a maintainer decision on #536 or a reframing around the observable defect; this head instead adds a 31-row table (docs/api.md:475-515) mapping ~40 vLLM metric names onto Flare series, which makes parity with another engine the PR's justification. The rules that bear on it:

The defect itself is real and the description now states it plainly — "a scrape cannot show tail latency, queue delay, prefill or decode time, request sizes, preemptions, or queue-limit rejections". That framing is what the rules authorize; the parity table is not. Since the PR is open with no human review recorded, the ask is cheap: record a maintainer decision on #536, or reframe the description around the observability defect.

Independent maintenance cost of the table. It opens "each metric in vLLM's production metric list, named here without the vllm: prefix" (docs/api.md:477-479) and never names or cites the upstream version it was read from, so every row is coupled to another project's release and will rot silently. Several rows make negative claims about this repository's own future that no test guards (repetition: "not provided", :498; corrupted_requests, :511; KV page residency, :512; lora_requests_info/watermark_requests/engine_sleep_state, :514; KV connectors, :515). Requested change: keep the Flare-side series documentation — it is the useful half and the rest of the section does it well — and either drop the mapping table or move it to the issue/PR discussion where it can be debated without becoming a maintained cross-project contract; if a mapping is kept, cite the vLLM version it was read from.

Worth a maintainer decision alongside: #549 (KV pages held by active requests), #560 (per-request metrics from runtime instants) and the closed #552/#553 rebuild overlapping observability surfaces. A maintainer should shape this cluster once rather than merge variants one at a time — this PR and #549 already needed a manual row-split commit (055663a) to stay rebasable.

S3 — One histogram convention per module: state it, or complete the migration

helios/src/server/metrics.rs:199-209, :211-322, :819-841, :851-876, :1000-1025, :1178-1214; rule AGENTS.md:188-193 (not opened).

metrics.rs now contains four ways to declare and render a histogram:

Mechanism Where Shape
HOST_TIME_BUCKETS / HOST_TOKEN_BUCKETS :199-209, observe :819-841, render :1178-1214 [u64; 8] ending u64::MAX
flare_host_cache_retirement_seconds :851-876 filled from StoreStats, rendered :1000-1025 counts pushed from selene, rendered by hand
new Buckets<N> / Histogram<N> :211-322, used at :406-421 and latency.rs:36 [f64; N] ending f64::INFINITY
single-value families via metrics::metric :1487 region fixed flare_ prefix

They disagree on more than encoding. The new Histogram::render emits # HELP + # TYPE (:298-301) then buckets → _sum → _count (:315-320); the host loop emits # TYPE only and buckets → _count → _sum (:1178-1214); the retirement block emits # TYPE only with a hand-written +Inf line (:1000-1025). One scrape therefore mixes histograms with and without # HELP, and the next author has to guess which mechanism to copy. This is code shape, not behaviour: the host position(..).unwrap() at :838 cannot panic because u64::MAX terminates the array, and every emitted series is already pinned by existing tests.

Requested change — the minimum, prose only: add one sentence to the module doc naming Histogram/Buckets as the convention for new histograms and saying why the u64 tables remain, plus a one-line comment on flare_host_cache_retirement_seconds (:851-876) recording that its counts are pushed from the selene store rather than observed, so it legitimately cannot use observe (this prevents a wrong "cleanup" later). The migration itself is Subtraction item 1 and is not required here.


Subtract / Simplify (8 items, ≈245 of the 1,016 added lines, ~24 %)

Ranked by lines saved. Every item deletes code; none asks the author to add any.

1. ≈55 lines — migrate the three host lookup histograms onto Histogram<8>

HOST_TIME_BUCKETS/HOST_TOKEN_BUCKETS (metrics.rs:199-209) and host_cost_sums: [AtomicU64; 3] (:475) become three Histogram<8> fields; host_lookup_cost (:819-841, 23 lines) becomes ~5 and loses the .position(..).unwrap() at :838; the 37-line render loop (:1178-1214) becomes ~8 Histogram::render calls. Labels, bucket counts and _sum values are unchanged: scale: 1.0 keeps the exposed unit at ns/tokens, and observe uses the same position(|b| exposed <= *b).unwrap_or(N - 1) rule the removed .position().unwrap() used. Honest caveat: Histogram::render writes _sum as sum as f64 / scale (:315-319), so ns sums above 2^53 would round where the host _sum is exact u64 today — the trade the request histograms already accept. Nothing is lost downstream: the only readers are the listed sites, and host_outcomes_and_capacity_have_bounded_labels_and_cost_histograms reads only _sum. Do not fold the 19-bound TOKEN_SECONDS series into the 21-bound loops (different bounds, not lossless), and do not take the competing suggestion to reshape the new seconds histograms onto [u64; N] and reuse the old loop — that deletes the better abstraction and keeps the duplication.

2. ≈50 lines — drop the per-response choice pair, which duplicates a per-request histogram the PR also adds

Delete request_choices: Histogram<6> and request_max_choice_generated_tokens: Histogram<21> (metrics.rs:407-408), CHOICE_COUNTS (:249-253), the generated.chunks(choices) loop (:608-618), let mut generated = vec![0u32; size] and its store (http.rs:407, :530) with the two extra arguments (:604-612), the render blocks (:1617-1621, :1625-1630), response_histograms_count_choices_and_largest_choice_per_prompt (:1981-2001), docs/api.md:322-326 and table row :507. flare_request_generated_tokens already observes every completed request's generated-token count on identical TOKEN_COUNTS bounds, and docs/api.md:325-326 itself states each choice runs as its own model request — so the max-choice series measures only the maximum of values already counted individually, and flare_request_choices measures a request field only /v1/completions accepts above one. Issue #536's table, the stated justification, asks for neither. Stated cost: two mapping rows become "Not provided", weakening the parity framing — the author's call; it also collapses S1 to one condition.

3. ≈65 lines — trim test assertions that re-prove neighbouring tests

render()-substring checks are grafted onto tests named for other behaviour, at phase_tests.rs:576, 676, 688, 944, 1501, 1529, 3275, 3601, 3836, 3958, 4100, 4540, 4573, 4713, 5452, 6382; several restate each other (:944 re-proves what the dedicated completion test proves, :5533 re-proves the sampler snapshot). AGENTS.md:194-198 (not opened) asks for tests that "exercise the affected behavior or contract"; a substring of the exposition text is a formatting check, not the behaviour the test is named for. Keep the ones that own their behaviour — the completion-histogram unit test (metrics.rs:1888-1978), prefill_computed_tokens_exclude_the_prefix_reused_at_admission (:1512), full_runtime_queue_limits_count_admission_rejections (:3810) and one route-presence check that a scrape carries a histogram with zero observations — and drop the rest (~24 assertion lines).

In metrics.rs:1946-1978 the second (zero-token) case re-asserts thirteen lines that repeat the first block; the genuinely new facts are four. Extract assert_counts(&render(), [...]) and call it twice with only the deltas, or split it into its own named test. And the 40-line blocking-socket test full_http_admission_counts_a_queue_limit_rejection (phase_tests.rs:5418-5457) spins a real TCP listener for one counter that acquire_ingress reaches in-process (the shape used at phase_tests.rs:4666).

4. ≈30 lines — docs/api.md:305-386 restates the # HELP strings shipped in every scrape

The per-series prose narrates population and unit that metrics.rs:1548-1642 already publishes as HELP text (e.g. api.md:329-331 vs metrics.rs:1557; api.md:340-341 vs :1567 and :1586), and api.md:377-386 states the same facts a third time through correspondence rows :501-504. Keep only what an operator cannot read from HELP — Prometheus-format-only and cumulative since start, the ≥2-token eligibility, the excluded populations, the zero-token rule, the abandoned-stream rule at :316-321 — plus the series names.

5. ≈15 lines — move flare_time_to_first_response_seconds onto Metrics

Delete histogram: Histogram<21> (latency.rs:36), the render_histogram forwarder (latency.rs:101-108), the out-of-band scrape hook (state.first_response.render_histogram(&mut text), helios/src/server.rs:671) and its test-only observation path; observe it from FirstResponse::output through the state.model.metrics() handle http.rs already holds (http.rs:621, :648) and render it inside the existing loop at metrics.rs:1548-1581. This removes the only scrape path that bypasses Metrics::render, so one struct owns every series. The double bookkeeping itself (60-second median window and an all-time histogram over the same instant pair) is documented and defensible — a median cannot be reconstructed from an all-time histogram — so only ownership moves.

6. ≈15 lines — the per-request inter-token histogram can be observed straight into Metrics

RequestRecord::inter_token: Histogram<19> (metrics.rs:345) with the merge branch (:353-357), Histogram::absorb (:285-295) and its only call (:576) can go: observe TOKEN_SECONDS directly into Metrics::inter_token_latency at the tokens_committed call site (runtime.rs:1801-1806). That also returns the 20 × 8 ≈ 160 B every queued and active request currently carries, which sits in tension with the description's "without per-request storage". The behavioural difference is that cancelled and failed requests would then contribute intervals, which docs/api.md:361-364 says they do not — so this is the author's product call: if the excluded population is wanted, keep it and the sentence; if not, take the deletion. (If item 6 is declined and item 1 taken, absorb stays — it is then the mechanism keeping the per-request histogram out of the shared registry.)

7. ≈9 lines — the model-step gate re-spells GraphKind::samples()

runtime.rs:1721-1732 lists Prefill | TerminalPrefill | ScoredPrefill | Resume | Decode | Speculative | Mixed — exactly the set GraphKind::samples() encodes (helios/src/execution/manifest.rs:90-101) and that this file already uses at runtime.rs:2956. Replace with if kind.samples() { self.metrics.model_step(prefill + generated.len() as u64); }, so a new sampling kind cannot silently miss flare_model_step_tokens. The neighbouring match at runtime.rs:1669-1677 is a different, six-kind set for graph launches and must stay.

8. ≈8 lines — Buckets::scale is redundant

Every observation is already an integer on the exposed unit's grid (nanoseconds at latency.rs:121-124 and metrics.rs:562-601, plain counts otherwise), and scale is 1e9 only for the two seconds vocabularies (:223, :231) and 1.0 for the three count vocabularies (:239, :246, :252). Its only effect is dividing at observe (:275) and again at render (:318), plus the rounding comment at :273-274 that exists only because the conversion does. Hold integer nanosecond or count bounds, compare directly, and format le inside render only. Verify with a before/after scrape diff that the le labels stay byte-identical.


Nits (6)

  1. docs/api.md:340-341 does not say the decode and per-output-token spans include a preemption stall. The analogous fact is stated for inter-token latency at :344-346; decode is computed first-to-last committed token (metrics.rs:593-601) and a preemption keeps first_token_ns because the whole Incoming is parked (runtime.rs:2110, :2155), so a high p99 decode time silently contains the readmission wait. Add "a preemption stall is included".
  2. docs/api.md:311 uses the implementation verb as the section lead-in. "The HTTP histograms observe delivery" — the next sentence measures a duration and the parallel runtime paragraph opens conceptually at :328. Name the group by its measurement ("measure response delivery time").
  3. The description's cost line does not label its histogram count. "seventeen histograms … 394 lines" is exactly this PR's request histograms (6 REQUEST_SECONDS<21> at :1548-1581, 2 TOKEN_SECONDS<19> at :1582-1595, 5 TOKEN_COUNTS<21> at :1596-1624, request_choices<6>, request_preemptions<9>, model_step_tokens<21>, plus TTFR), but a scrape also carries four host histograms (:1178-1214, :1000-1025), so a reader counting # TYPE … histogram finds 21. One clause naming the population.
  4. flare_admission_rejections_total bypasses the file's labelled-counter loop and casts the variant to its label index. admission_rejected indexes self.admission_rejections[limit as usize] (field :423, used at :685) while the labels are a separate literal array ["http_slots", "generation_capacity", "request_queue"] (:1647) that must track AdmissionLimit's declaration order (:378-385); nothing links them, and the as usize opts out of exhaustiveness. Give the enum a name()/ALL and feed the existing loop at :1143-1177. (This is the same site Subtraction items 2 and 6 do not touch; it is a nit only because the counters are pinned by tests.)
  5. Per-choice generated-token bookkeeping is duplicated. Encoder already stores it (Usage { generated: u32 }, helios/src/server/protocol/encode.rs:56-60, set at :630-634, incremented by observe_generated_token at :216-219) and groups choices by prompt through choices_per_prompt (:94, used at :689-695), while http.rs keeps a parallel vec![0u32; size] (:407, :530) that metrics.rs:610 re-groups with chunks(choices). Two stores of one number. Expose the encoder's counts, or delete the pair (Subtraction item 2) — either removes the duplicate.
  6. !count at http.rs:606 is dead. Count requests return at http.rs:284-286, before the delivery stream exists. Harmless, but it suggests a guard the streaming path does not have.

Deliberately not raised (reconciled across lenses)

Open questions / what could not be verified