Skip to content

Add per-request histograms and vLLM-parity request metrics - #548

Open
WynnD wants to merge 13 commits into
NVIDIA:mainfrom
WynnD:metrics/request-latency-histograms
Open

WynnD wants to merge 13 commits into
NVIDIA:mainfrom
WynnD:metrics/request-latency-histograms

Conversation

@WynnD

@WynnD WynnD commented Nov 26, 2026 •

Copy link
Copy Markdown

/metrics reports counters and gauges but no request distributions, so a scrape cannot show tail latency, queue delay, prefill or decode time, request sizes, preemptions, or queue-limit rejections. Dashboards and alerts written for vLLM read exactly these series, and #536 asks for them. The runtime already counts completed requests in one function; recording the histograms there keeps counter and histograms consistent, and the remaining quantities are counted at sites that already update related counters.

What changed

  • Runtime (server/runtime.rs, server/metrics.rs). Each request carries a small record that survives preemption: the instants of its first scheduled model step and its first and last committed token, its output limit, its preemption count, and its inter-token intervals. On successful completion they enter new histograms: queue, prefill, decode, and inference time, time to first token, time per output token, inter-token latency, prompt, computed-prompt, generated, and max tokens, and preemptions. Cancelled and failed requests are not observed.
  • New counters and gauges. flare_requests_output_limited_total (completions that stopped at the token limit), flare_cache_lookup_tokens_total (prompt tokens offered to prefix lookup, so reuse can be expressed as a token hit rate), flare_parked_requests (requests waiting for readmission), flare_admission_rejections_total{reason} (http_slots, generation_capacity, request_queue), and the flare_model_step_tokens histogram (tokens per model step).
  • HTTP (server/http.rs, server/latency.rs). flare_request_e2e_seconds observes each successful response with at least one delivered choice, excluding token counting; flare_request_choices and flare_request_max_choice_generated_tokens record n and the longest choice per prompt, skipping choices cancelled by the parallel-tool-call limit; flare_time_to_first_response_seconds is observed beside the existing first-response sampler.
  • One histogram mechanism (server/metrics.rs). All observed histograms, including the three existing host prefix-store lookup histograms, render through one Histogram/Buckets type. The host histograms keep their names, bounds, and values, and gain # HELP lines and the standard _sum then _count order.
  • docs/api.md defines each series' population and maps each metric in vLLM's production list (checked 2026-11-27) to the Flare series that measures it or marks it as not provided (no vllm: names are exported).

Result

Request latency, size, preemption, and rejection distributions become scrapeable. Responses, scheduling, eviction, and the JSON snapshot are unchanged. Added work: one clock read per scheduled model step (shared by its lanes, taken after input packing succeeds), one store or histogram observation per committing step per request (not per token), about a dozen observations per completed request, one observation per model step that processed tokens, and 17 histograms per text scrape. This cost was not measured in isolation.

Evidence

  • cargo check --features server is clean. cargo test --features runtime-core,server --lib -- server:: scheduler:: cache::: 816 passed; 1 failed, a template test that needs FLARE_TEST_TEMPLATE_DIR and is unrelated. A multi-choice test covers a response whose other choice is cancelled by the parallel-tool-call limit.
  • Live, on one RTX PRO 6000 Blackwell serving the prepared local-inference-lab/Qwen3.8-Flash-Next-FLARE gb202 package with this PR, Report KV pages held by active requests #549, and Emit vLLM-compatible per-request metrics from runtime instants #560 built from upstream main: every new series is exported, and the host prefix-store histograms carry # HELP. Over 24 completed requests of mixed Chat, Completions (including n=2 and two prompts), and Responses traffic, the completed-counter delta was 24, equal to the time-to-first-token and generated-token histogram count deltas. The generated-token histogram sum delta (3,067) equals the flare_generated_tokens_total delta, the end-to-end count delta (22) equals the delivered responses, and output-limited stops were counted.
  • Not run: multi-GPU cores and the Windows build.

This PR and #549 (KV-page gauges) are independent and merge cleanly in either order. The mapping row for kv_cache_usage_perc lists it as not provided as one ratio; #549 supplies that ratio.

Refs #536. This PR covers its request histograms; the process_* series #536 also lists are not included and can follow separately.

Discord: oystersmiles

`/metrics` reports counters, gauges, and the dashboard snapshot, but no
distribution of request latency, so an operator cannot see tail latency, queue
delay, prefill time, decode rate, or prompt size from a scrape, and generic
Prometheus process dashboards have nothing to read. Issue NVIDIA#536 requests
histograms for per-request latency and prompt size together with the standard
process_* metrics. Fixed-bound histograms answer those questions without
per-request storage, and the runtime already counts completions in one place, so
recording the histograms there keeps the counter and the observations together.

The runtime now keeps lifecycle instants on `Incoming` so they survive
preemption: `Worker::reserve_and_pack` stamps the first model step that includes
a request, `Worker::complete` stamps its first and last committed generated
tokens, and `Metrics::request_completed` records queue, prefill, decode, time per
output token, and prompt tokens while incrementing `requests_completed_total`.
Both call sites that incremented the counter directly now call
`request_completed`, so the counter cannot drift from the histograms. Cancelled
and failed requests stay out of the request histograms.

The generation handler records `request_e2e_seconds` when delivery completes a
successful response, except for `/v1/messages/count_tokens`, and the existing
first-response sampler now also observes `time_to_first_response_seconds` when it
offers answer or reasoning text; its median gauge is unchanged. On Linux,
`server/metrics/process.rs` derives `process_cpu_seconds_total`,
`process_resident_memory_bytes`, `process_virtual_memory_bytes`,
`process_start_time_seconds`, `process_open_fds`, and `process_max_fds` from
procfs and `RLIMIT_NOFILE`, omitting only the metrics whose source cannot be
read; other platforms write nothing. Names, types, and endpoints are documented
in `docs/api.md`, and the JSON snapshot is unchanged.

The claimed result is observability only: latency, prompt-size, and process
resource distributions become scrapeable with no change to serving behavior.

Evidence: `cargo test --locked --release --manifest-path helios/Cargo.toml
--target-dir ~/.cache/hyperflare-target --features runtime-core,server --lib --
server::runtime::phase_tests` passed 109 tests, including
`reasoning_budget_cuts_or_plainly_continues_with_exact_history_and_usage` (a
preempted and readmitted request records one queue, prefill, and prompt-token
observation),
`first_response_http_nonstream_records_only_when_completed_body_is_offered`,
`first_response_http_stream_excludes_pretext_failures_and_unpolled_bodies`, and
`metrics_route_serves_prometheus_or_json_without_the_api_key`, whose text scrape
carries the first-response histogram, an empty request histogram, and a resident
memory gauge. `server::metrics::` passed 20 tests, including
`request_histograms_bucket_completed_request_timings`,
`render_reports_process_memory_descriptors_and_start_time`, and
`parse_stat_reads_fields_after_a_parenthesized_command_with_a_paren`. The whole
`server::` filter ran 326 tests with one failure,
`messages_image_hints_end_after_expansion_for_text_and_segmented_templates`,
which requires templates from `tests/frontend/prepare_templates.py` through
`FLARE_TEST_TEMPLATE_DIR`; no templates are installed on this host, so that test
is unrun here. Windows builds and the rest of the helios suite are left to CI.

Signed-off-by: Wynn Drahorad <[email protected]>
Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=eb2f
@WynnD
WynnD marked this pull request as draft November 26, 2026 20:27
@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 548.
Case File Intake Report

Future reviews will auto-run 90 minutes after code updates are pushed.

  • Re-review sooner: Call @flare-autobot after push.
  • Opt-out: Include #autobot:ignore in the PR or any comment.

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review for Agents · Value Proposition · Case File

Recommendation: Changes Requested

The design is right (histograms recorded where flare_requests_completed_total is already incremented, no per-request storage, no new JSON fields, no flags); two cheap blockers, then the diff can shrink by about a quarter. Nothing here asks the author to add code.

Blockers:

  • flare_request_e2e_seconds records responses the runtime counts as cancelled. On the parallel-tool-limit path (http.rs:471-476, :526, :563-567) the terminal event still reaches Delivery::Complete (:598) and both arms observe e2e (:614-617, :631-635), while the runtime only bumps cancelled/finish_cancelled (runtime.rs:293-302, :1317/:1338/:1360/:1407). Cancellation also races the natural finish. Fix: guard on !encoder.tool_limit_reached, or narrow docs/api.md:312-313 to the five runtime histograms; add one tool-limit test.
  • Evidence overstates and does not reconcile. "Nothing about serving changes" is inaccurate: a clock read plus a lane loop per submitted step (runtime.rs:2187-2203), two stores per committed token (:1774-1775), blocking procfs reads per text scrape (server.rs:709 → process.rs:52-133, including all of /proc/stat for btime). Scrape deltas are 6 TTFR vs 5 runtime observations, include the agent session's traffic, attribute no sum to a request, and come from fork commit 5ffe4d5 + this diff, not main; "CI covers the first two" is an expectation since ebecef1 has no checks. Fix (description only): state per-step/per-scrape cost as known and unmeasured, restate the scrape as a smoke check with the population caveat, name the CI job or drop that sentence.

Should fix:

  • docs/api.md:305-313: split by eligibility — decode and time-per-output-token only with ≥2 generated tokens (metrics.rs:470-479; HELP at :1406-1418 already says so). Add "cumulative since server start" and name the two groups instead of "observe the served response".
  • docs/api.md:301-304 and :288-289, two one-clause edits: e2e ends at delivery and, for streams, only if the client drains the body (http.rs:614-617 vs :631-635, pinned by phase_tests.rs:4407-4434); and "Counter and gauge names start with flare_" is contradicted by the six process_* series documented at :315-318.
  • flare_request_prefill_seconds absorbs vision work: first_scheduled_ns is stamped before the GraphKind::Vision split (runtime.rs:2191-2203 vs :2208). One doc phrase, or narrow the stamp to prefill lanes.
  • Move OS reads into eos/ (AGENTS.md:20-21): _SC_PAGESIZE is flare_eos::page_size() (eos/src/unix.rs:73-75), RLIMIT_NOFILE is the call in raise_open_file_limit (:138-165, desired = 0), the /proc/self/fd count is already open_descriptors() (runtime_core/protection.rs:291-302). Leave only the /proc/self/stat and btime parsing.
  • Record a maintainer decision on Metrics: add request latency histograms and process metrics for monitoring parity with vLLM #536, or reframe the description around the defect (tail latency, queue delay, prefill time, decode rate unobservable from a scrape); vLLM-parity is a competitor, not an authorization under the charter.

Subtract / Simplify:

Could remove ~130 of +545 added lines (~100 inside process.rs):

  • process.rs: six if let (Some, Some) fallbacks for sources that cannot fail (:79-132) plus the "never fails" module doc, and the test asserting live kernel values (:157-183) — ~55 lines; the route test at phase_tests.rs:5377-5388 already covers the scrape.
  • Convert the three host-cache histograms to Histogram<8>/Buckets<8>: deletes HOST_*_BUCKETS (metrics.rs:200-210), host_cost_sums, the .position(..).unwrap() loop (:670-692) and the 37-line render loop (:1029-1065) — ~40 lines.
  • Observe e2e once before yield Delivery::Complete and move time_to_first_response onto Metrics: removes the duplicate observation, the metrics_handle() clone, the second impl block (latency.rs:122-131), render_histogram, server.rs:671 and the duplicate assertions at phase_tests.rs:4428-4471 — ~18 lines.
  • #[cfg(target_os = "linux")] on the module (metrics.rs:12) and the call (server.rs:709) instead of the let _ = text shim; optionally drop process_virtual_memory_bytes and process_max_fds (not in Metrics: add request latency histograms and process metrics for monitoring parity with vLLM #536's table).

Nits:

9 nits — duplicate process::metric emitter, parse_stat accepting any line with ), process_open_fds counting itself (+1 vs Prometheus), two expressions in Worker::publish not hoisted as complete does, the impossible {None, Some} test state, the missing note on why last_output_ns cannot substitute for last_token_ns, comment/prose weight, the separate impl block, and two description wording fixes. All listed with file:line in the case file.

To opt out, include #autobot:ignore in your post or comment.

A review of the previous commit found three defects. A response cancelled by
the parallel tool-call limit still reaches `Delivery::Complete`, so the HTTP arms
observed `flare_request_e2e_seconds` for a request the runtime counts as
cancelled, and both arms duplicated the same observation. The documentation
claimed request histograms cover "the served response" and named only `flare_`
series, contradicting the stream-drain condition, the two-token condition on
decode histograms, and the `process_*` series. And `process.rs` read page size,
the open-file limit, and the descriptor count with ad-hoc libc and procfs code
instead of the host helpers the repository already owns.

`generate` now observes the end-to-end histogram once, inside the delivery
stream, guarded by `!encoder.tool_limit_reached`, and the two delivery arms only
deliver. `disabled_parallel_calls_complete_http_and_stop_decoding` asserts that
every path and stream mode in that test records zero end-to-end observations,
which covers the cancellation path directly (it ran 326 tests in the `server::`
filter, with the one pre-existing template-fixture failure).

`docs/api.md` now separates the HTTP histograms, which count delivered responses
and require a drained stream, from the runtime histograms, which count completed
generations and record decode and time-per-output-token only with at least two
generated tokens; it states cumulative-since-start, notes that a request's first
model step can be a vision step, and exempts `process_*` from the `flare_`
prefix.

`process.rs` uses `crate::os::page_size()`, `crate::os::raise_open_file_limit(0)`
(read-only), and the descriptor counter that core protection already keeps,
re-exported within the crate; only `/proc/self/stat` and the `btime` parse stay
local. No behavior changes beyond the cancelled-request exclusion, and no new
cost on the serving path.

Signed-off-by: Wynn Drahorad <[email protected]>
Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=eb2f
@WynnD

WynnD commented Nov 27, 2026

Copy link
Copy Markdown
Author

@flare-autobot review the pushed changes. The per-request metrics PR is new; the other two carry review fixes.

Review nits on the previous commits: `Worker::publish` repeated the prompt and
generated-token expressions in the metric call and the terminal event, the
first-response histogram renderer sat in a second impl block, `parse_stat`
accepted any line containing `)`, and the histogram test used a state a real
request cannot reach (`first_scheduled_ns: None` with a token present).

`publish` now hoists the two values as `complete` does, the renderer lives in the
existing `FirstResponseSamples` impl, `parse_stat` rejects a line whose first
field after the command name is not a process state character, and the zero-work
case uses `RequestTimes::default()`, which is reachable through a zero-token
completion.

No behavior changes; the parsers and metrics output are unchanged for valid input.

Evidence: `cargo test --locked --release --manifest-path helios/Cargo.toml
--target-dir ~/.cache/hyperflare-target --features runtime-core,server --lib --
server::metrics` passed 20 tests, including the request histogram and both
process-metrics tests, and `-- server::` passed 326 with the one pre-existing
template-fixture failure.

Signed-off-by: Wynn Drahorad <[email protected]>
Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=eb2f
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

The design is right — histograms recorded where flare_requests_completed_total is already incremented, no per-request storage, no JSON change, no flags — and most of the previous round is fixed. Two cheap blockers remain, then the diff can shrink by about a quarter; nothing here asks the author to add code.

  • Blockers: 2
  • Should fix: 3
  • Subtractive suggestions: 5
  • Nits: 6

Have your agent review the Full Review for complete findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

The design is right — histograms recorded where flare_requests_completed_total is already incremented, no per-request storage, no JSON change, no flags — and most of last round is fixed. Two cheap blockers remain (a --features server build break, unreconciled evidence), then the diff can shrink by about a third; nothing here asks the author to add code.

  • Blockers: 2
  • Should fix: 4
  • Subtractive suggestions: 6
  • Nits: 6

Have your agent review the Full Review for complete findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

The process_* series (CPU time, resident and virtual memory, start time,
open and maximum file descriptors) describe the serving process, not request
latency, so they formed a second outcome inside a change whose purpose is
request histograms. Their renderer also read procfs on every text scrape and
called crate::runtime_core from server code, which does not compile when helios
is built with only the server feature.

This deletes helios/src/server/metrics/process.rs and its render call in the
/metrics handler, the docs/api.md paragraph and the naming exception that
described the series, the route-test assertion, and the open_descriptors
re-export that only the renderer used.

/metrics again exports only flare_-prefixed series, a text scrape reads no
procfs files, and the server-only build compiles.

cargo check --locked --manifest-path helios/Cargo.toml --features server is
clean. cargo test --features runtime-core,server --lib -- server::metrics
server::latency metrics_route_serves passed 23 tests. No GPU workload ran.

Signed-off-by: Wynn Drahorad <[email protected]>
Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=eb2f
`/metrics` has per-request histograms for end-to-end, queue, prefill, and
decode time, time per output token, and prompt size, but none for the other
per-request distributions vLLM exposes: time to first token inside the engine,
inter-token latency, time from first scheduling to the last token, generated
and freshly computed prompt tokens, the output limit, preemptions per request,
the `n` parameter, and the largest output among one prompt's choices. A
dashboard built on vLLM's metrics therefore has no Flare series to read for
them. The project maintainer approved bringing Flare's metrics to vLLM parity
for quantities Flare already has. Every one of these values already exists in
the runtime worker or the HTTP generation handler at the points where the
existing histograms record, so recording them there adds no instrumentation to
GPU or cache paths.

`Incoming.times` becomes `Incoming.record`, a `RequestRecord` that keeps the
lifecycle instants, the output limit taken at first admission (the prompt's
limit plus the tokens a reasoning budget defers), a preemption count that
`Worker::park_if_preempted` increments when it parks a preempted request, and a
19-bucket histogram of intervals between the request's committing steps.
`Worker::complete` calls `RequestRecord::tokens_committed` once per model step
that commits tokens for a request, so a speculative round that commits several
tokens adds one interval, as vLLM's per-iteration accounting does. The record
moves with the request through parking and readmission.
`Metrics::request_completed` takes the record and a `CompletedRequest` (prompt,
reused, and generated tokens) and now also records
`flare_time_to_first_token_seconds`, `flare_request_inference_seconds`,
`flare_request_prefill_computed_tokens` (prompt minus tokens reused at first
admission), `flare_request_generated_tokens`, `flare_request_max_tokens`, and
`flare_request_preemptions`, and merges the request's intervals into
`flare_inter_token_latency_seconds`. Cancelled and failed requests never reach
`request_completed`, so they stay out of every new histogram, as they do out of
the existing ones. The HTTP handler's end-to-end observation moves into
`Metrics::response_completed`, which also records `flare_request_choices` (the
`n` parameter) and `flare_request_max_choice_generated_tokens` once per prompt
of a successful response; only `/v1/completions` accepts `n` above one, and
each choice runs as its own model request. The prompt-token bucket constant is
renamed `TOKEN_COUNTS` because every token-count histogram uses it; the
preemption and `n` histograms use vLLM's default bounds, the preemption one with
an added zero bound so never-preempted requests stay separate.
`docs/api.md` defines each series, its units, and which requests it counts.

The claimed result is observability only: the distributions above become
scrapeable, and no admission, scheduling, or cache decision changes. The added
cost, stated from the code and not measured, is one bucket search over at most
19 bounds and two uncontended atomic adds per committing step per request, about
ten histogram observations and a 20-counter merge per completed request, two
observations per prompt per HTTP response, and 168 bytes per queued or active
request for the record's histogram, limit, and count.

Evidence: `cargo test --locked --manifest-path helios/Cargo.toml --features
runtime-core,server --target-dir /tmp/mc/target --lib -- server::metrics
server::runtime` passed 148 tests (one ignored).
`request_histograms_bucket_completed_request_timings` drives
`tokens_committed` through three committing steps and checks every new
histogram's buckets and sums, and that a zero-token completion adds only token
and preemption observations.
`response_histograms_count_choices_and_largest_choice_per_prompt` checks the
per-prompt grouping of choices.
`reasoning_budget_cuts_after_a_multi_token_speculative_completion` checks two
inter-token observations for three committing steps that include a three-token
speculative round, an output limit spanning the reasoning budget and its
remainder, and zero preemptions for a reasoning park.
`exercise_text_preemption` (through
`reasoning_budget_survives_preemption_and_checkpoint_recomputation`) checks that
the parked request carries one preemption and that the completed request lands
in the one-preemption bucket.
`prefill_computed_tokens_exclude_the_prefix_reused_at_admission` completes two
identical prompts and checks 13 computed tokens for the first and zero for the
second, which restored the first one's checkpoint. These tests run the worker
without a GPU; serving on hardware has not been run. Time to first token starts
at model-scheduler arrival rather than at HTTP arrival as in vLLM, and vLLM also
observes aborted requests, which Flare excludes.

Signed-off-by: Wynn Drahorad <[email protected]>
Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=eb2f
…ejections

Four quantities vLLM exposes as counters or gauges exist in Flare but no
series reports them. `flare_cache_lookups_total` counts GPU prefix lookups,
not the prompt tokens looked up, so the token hit rate that vLLM's
`prefix_cache_queries` and `prefix_cache_hits` give cannot be computed from
`flare_cache_reused_tokens_total` alone. `flare_requests_completed_total` does
not separate requests that stopped at their output limit from those that
stopped at EOS or a stop. `flare_pending_requests` reports only requests that
await their first admission, so requests parked for readmission after a
preemption, a reasoning budget cut, or a returned host-store restore are in no
gauge. HTTP 429 responses and the runtime's capacity and channel refusals are
not counted anywhere, unlike vLLM's `admission_rejections`. vLLM also reports
the tokens each engine step processes; Flare's existing per-kind launch counts
and token totals give only means, not that distribution. The project maintainer
approved bringing Flare's metrics to vLLM parity for quantities Flare already
has; each value here is already computed at the point where it is recorded.

`RequestScheduler::admit_planned_with_checkpoint_accounting` adds the prompt
length to `SchedulerStats::cache_lookup_tokens` beside `cache_lookups`, once per
admitted request; prompt-scoring requests, which skip the lookup, add nothing.
The field changes only when `cache_lookups` does, so the deferred-copy-out retry
key that embeds `SchedulerStats` changes no more often than before.
`CompletedRequest` gains `output_limit`, set where `Worker::publish` already
decides the `length` finish reason (its EOS test now runs before the metrics
call) and false on the token-stop completion in `Worker::complete`;
`Metrics::request_completed` counts it in
`flare_requests_output_limited_total`. A new `flare_requests_completed_total`
label was not used because it would change that series' identity, and a
separate counter by finish reason would duplicate it; stop completions are the
difference between the two counters, and cancelled and failed requests keep
their own counters. `Worker::publish_gauges`, extracted from the worker loop,
stores `flare_parked_requests` beside `flare_pending_requests`.
`Metrics::admission_rejected` counts `flare_admission_rejections_total{reason}`
where the 429 and capacity errors are produced: `admit_http` and the extra
choice slots in `http::generate` (`http_slots`) and
`ModelRuntime::enqueue_many` (`generation_capacity`, `request_queue`). Paused
admission and an unavailable runtime are not queue limits and stay uncounted.
`Worker::complete` observes `flare_model_step_tokens`, the prompt tokens
computed plus the generated tokens committed, for every completed prefill,
resume, decode, speculative, or mixed graph, using the values it already passes
to `Metrics::progress`. `docs/api.md` defines each series, and the pending
gauge's help and JSON field now say "first admission".

The claimed result is observability only; no admission, scheduling, or cache
decision changes. The added cost, from the code and not measured, is one
addition per admission, one histogram observation (a search over at most 21
bounds and two atomic adds) per completed text graph, one atomic store per
worker-loop pass with progress, and one atomic add per rejection.

Evidence: `cargo test --locked --manifest-path helios/Cargo.toml --features
runtime-core,server --target-dir /tmp/mc/target --lib -- server::metrics
server::runtime scheduler::tests` passed 236 tests (one ignored). The scheduler
admission tests check 192 lookup tokens for three admitted 64-token prompts and
none for refused attempts. `reasoning_budget_does_not_readmit_eos_or_user_stops`
checks that EOS, text-stop, and token-stop completions count no output-limit
stop, and `ignored_eos_at_the_output_limit_finishes_for_length` checks one,
together with two text-graph observations totalling three tokens.
`exercise_text_preemption` checks one parked and no pending request after a
preemption. `full_runtime_queue_limits_count_admission_rejections` fills the
worker channel and then the runtime capacity, and
`full_http_admission_counts_a_queue_limit_rejection` sends a completion through
the router with every HTTP slot held and checks the 429 and its count. These
tests run without a GPU; serving on hardware has not been run.

Signed-off-by: Wynn Drahorad <[email protected]>
Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=eb2f
An operator moving dashboards or alerts from vLLM to Flare has to find, for
each vLLM metric, the Flare series that measures the same quantity, the
arithmetic that derives it, or the fact that Flare does not provide it. Flare
deliberately exports no `vllm:` aliases and adds no second series for a
quantity it already reports, so that correspondence exists only as
documentation.

`docs/api.md` gains a "Correspondence with vLLM metrics" table under "Health
and metrics". It covers every metric in vLLM's General and Speculative Decoding
tables, plus vLLM's aggregate speculative counters and connector families. Each
row gives the Flare series or expression and the material difference in origin
or population: time to first token starts at model-scheduler arrival, prefix
lookup counters include readmissions, `num_requests_running` includes requests
waiting for a host restore, and Flare's per-request histograms exclude
cancelled and failed requests. Rows for corrupted requests, KV block residency,
FLOPs estimates, LoRA, watermarking, sleep state, and KV connectors state that
Flare does not provide them and why.

The claimed result is documentation only; no code changes.

Evidence: each Flare name in the table was checked against the renderer in
`helios/src/server/metrics.rs` and `helios/src/server.rs`, and each vLLM name
against vLLM's published production-metrics list and its Prometheus logger
source. The table has not been exercised by a dashboard.

Signed-off-by: Wynn Drahorad <[email protected]>
Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=eb2f
…assertions

docs/api.md described a narrower instrument than the code records. The
end-to-end histogram is observed once per delivered successful response, it
excludes /v1/messages/count_tokens and responses the runtime counts as
cancelled (including a parallel tool-limit stop), and it can be lower than
flare_requests_completed_total because a multi-choice response adds one
observation for several model-request completions and an abandoned stream adds
none. The closing sentence claimed cancelled and failed requests enter only two
counters, but flare_time_to_first_response_seconds observes a stream that
offered text before it failed. The runtime paragraph now also says a zero-token
completion still increments flare_requests_completed_total and enters the
prompt-token histograms, while the queue observation needs a model step and
time-to-first-token, prefill, and inference need a committed token. The vLLM
table rows and its intro state the same populations.

phase_tests.rs rendered the whole scrape three times in the failed-stream loop
for one assertion and re-rendered the first-response histogram that the
/metrics route test already exercises. Both duplicates are removed; the
end-to-end exclusion for a failed response is still asserted, once, and the
tool-limit count assertion is kept because it pins a distinct guard.

Validation: cargo check --locked --manifest-path helios/Cargo.toml --features
server (passes). cargo test --locked --manifest-path helios/Cargo.toml --features
runtime-core,server --lib -- server:: scheduler:: cache::: 816 passed, 1 failed
- the known server::protocol::decode::native_prompt_tests::
messages_image_hints_end_after_expansion_for_text_and_segmented_templates,
which needs FLARE_TEST_TEMPLATE_DIR.

Limitations: documentation and test-duplication only; no production code
changes. The test-only drift assertion in Cache::stats and the first-response
histogram on FirstResponseSamples are outside this change.

Signed-off-by: Wynn Drahorad <[email protected]>
Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=eb2f
@WynnD WynnD changed the title Add request latency histograms and process metrics Add per-request histograms and vLLM-parity request metrics Nov 28, 2026
@WynnD
WynnD marked this pull request as ready for review November 28, 2026 02:09
The request-histogram documentation and two expected rows of the counter
exposition test were inserted at the same lines as the KV-page gauge change
(NVIDIA#549) adds its paragraph and rows, so whichever of the two merged second
would stop on a textual conflict although the changes are independent.

The histogram paragraphs in docs/api.md now follow the paragraph about the
JSON format of the /metrics route instead of directly following the route's
introduction, and in counters_expose_fixed_names_without_request_payloads the
cache_lookup_tokens field and the parked_requests row move to the end of their
lists. The text and assertions are unchanged; the test checks each row with
`contains`, so row order does not matter.

The two changes now merge in either order without manual resolution.

cargo test --features runtime-core,server --lib -- server::metrics passed 19
tests, and `git merge-tree` of this branch with the KV-page branch reports no
conflict.

Signed-off-by: Wynn Drahorad <[email protected]>
Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=eb2f
@WynnD

WynnD commented Nov 28, 2026

Copy link
Copy Markdown
Author

Live validation summary. Hardware: one RTX PRO 6000 Blackwell serving the prepared local-inference-lab/Qwen3.8-Flash-Next-FLARE gb202 package behind llama-swap v250. The image was built from upstream main with this PR, #549, and #560 merged.

Check Result
New series exported all present
24 completed requests (Chat, Completions incl. n=2 and two prompts, Responses) completed-counter delta 24 = TTFT and generated-token histogram count deltas
Generated-token histogram sum vs flare_generated_tokens_total equal (3,112)
flare_request_e2e_seconds count 22, equal to delivered responses
Unit tests (server:: scheduler:: cache::) 814 passed; 1 unrelated template test needs FLARE_TEST_TEMPLATE_DIR

Not measured: this PR's always-on recording cost in isolation.

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

The design is right — histograms recorded where flare_requests_completed_total is already incremented, so counter and distributions cannot drift — and last round's two blockers are fixed. What remains is one Closes #536 overstatement plus an unversioned vLLM parity table, one latent HTTP-gate population bug, one histogram-convention gap, and roughly 245 of the 1,016 added lines that can be deleted rather than reviewed further.

  • Blockers: 0
  • Should fix: 3
  • Subtractive suggestions: 8
  • Nits: 6

Have your agent review the Full Review for complete findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

…ime after packing

The completion path spelled the seven sampling graph kinds inline to decide whether a
completed step contributes to flare_model_step_tokens, duplicating GraphKind::samples()
in helios/src/execution/manifest.rs, which the same file already uses to validate
sampling admissions. A sampling kind added to samples() would update its other
consumers but not this list, so the counter would silently stop counting it. In
reserve_and_pack, the first_scheduled_ns stamp preceded pack_inputs/pack_vision, which
can return Err, so a request whose packing failed kept a scheduled instant for a step
that never executed.

The completion path now tests kind.samples(). reserve_and_pack performs its single
monotonic_ns() read and the per-lane get_or_insert after packing returns Ok, so a
successful step stamps the same instant as before and a failed pack leaves
first_scheduled_ns unset.

flare_model_step_tokens counts the same steps: samples() lists exactly the seven
variants the inline list named (Prefill, TerminalPrefill, ScoredPrefill, Decode,
Speculative, Mixed, Resume), now from one source of truth. The queue-time and
prefill/inference histograms no longer record a scheduled instant for a step whose
packing failed.

cargo check --locked --manifest-path helios/Cargo.toml --features server finished with
four pre-existing warnings. cargo test --locked --manifest-path helios/Cargo.toml
--features runtime-core,server --lib -- server:: scheduler:: cache:: passed 814 tests
and failed one:
server::protocol::decode::native_prompt_tests::messages_image_hints_end_after_expansion_for_text_and_segmented_templates,
which requires FLARE_TEST_TEMPLATE_DIR and exercises no changed path. No GPU server run
was performed, so the emitted metrics were not checked end to end.

Signed-off-by: Wynn Drahorad <[email protected]>
Design-Signed-Off-By: enterprise/deepseek-v4.1-flash (omp agent); design-review=eb2f
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

Right design — histograms are recorded in the one function that already increments the completion counter, so the counter and distributions cannot drift — but the Closes #536 keyword overstates delivery, the vLLM parity table is unpinned, one latent HTTP-gate bug drops sibling choices' observations, and ~235 of the 1,016 added lines are deletable.

  • Blockers: 0
  • Should fix: 3
  • Subtractive suggestions: 7
  • Nits: 8

Have your agent review the Full Review for complete findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

The design is right — histograms are recorded where flare_requests_completed_total is already incremented, so counters cannot drift — and the new GraphKind::samples() reuse clears last round's item. Remaining: a Closes #536 overstatement with an unpinned vLLM table, one latent HTTP-gate bug, one histogram-convention gap, and ~235 deletable lines of 1,008 added.

  • Blockers: 0
  • Should fix: 3
  • Subtractive suggestions: 7
  • Nits: 8

Have your agent review the Full Review for complete findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

@lukealonso

Copy link
Copy Markdown
Collaborator

The core design looks good — recording the runtime histograms inside Metrics::request_completed keeps flare_requests_completed_total aligned with the distributions, cache_lookup_tokens only changes with cache_lookups so CopyoutResources is unaffected, and the PR description accurately discloses the combined-stack live validation and unmeasured overhead. A few items need to be addressed before merge:

Blocking

  1. Run mandatory TLA+ lifecycle conformance (verification/helios-lifecycle/check.py) and --release tests
    This PR modifies RequestScheduler::admit_planned_with_checkpoint_accounting (helios/src/scheduler.rs), Worker admission/completion/publish/park/shutdown paths (helios/src/server/runtime.rs), and helios/src/server/runtime/phase_tests.rs (which contains the ResponseLifecycle conformance harness). Per docs/design-review.md (Layer 3, current digest c3a9 on main), touching covered scheduler/runtime lifecycle paths requires running python3 verification/helios-lifecycle/check.py (TLC + observed-edge Rust conformance) and --release crate tests rather than only debug cargo test --lib.

  2. Pre-prefill requeue corrupts flare_request_queue_seconds / flare_request_prefill_seconds / flare_request_inference_seconds (helios/src/server/runtime.rs)
    Worker::reserve_and_pack stamps first_scheduled_ns on the first model step of any GraphKind, including GraphKind::Init and GraphKind::Restore. When Worker::retry_late_pool_answers cancels a request after Init/Restore (live.generated_tokens == 0) and calls self.requeue(handle, true), the request returns to self.parked, gets readmitted into Inbound, and waits for a host-store restore over network/disk. Because first_scheduled_ns stays frozen at the discarded Init/Restore step, flare_request_prefill_seconds and flare_request_inference_seconds absorb the entire park + host-restore wait while flare_request_queue_seconds ends early.

    Reset incoming.record.times.first_scheduled_ns = None in Worker::requeue (which only runs before any token is generated), and either update docs/api.md to note that Init/Restore is a request's first model step (not just "which can be a vision step") or stamp first_scheduled_ns only on step.kind.samples() || step.kind == GraphKind::Vision.

Should fix

  1. Change Closes #536
    Issue #536 asks for standard process_* metrics alongside the request histograms. Removing process_* was the right way to keep this PR focused on one coherent outcome, so use Part of #536 (rather than Closes #536) unless process metrics are explicitly closed out separately.

  2. Host-forced reasoning close can record 0s decode / TPOT samples (helios/src/server/metrics.rs, request_completed)
    When max_new_tokens == 1 under a reasoning budget with cut.after == 1 and forced == true, only one model step commits a token (first_token_ns == last_token_ns), and close_reasoning increments carried.generated_tokens += 1 (generated_tokens == 2) without running another model step. request_completed then sees generated_tokens > 1 and observes 0s into flare_request_decode_seconds and flare_time_per_output_token_seconds. Guarding decode/TPOT on having at least one post-first-token committing step avoids synthetic zero observations.

  3. docs/api.md scope and precision

    • External vLLM parity table: Repository docs specify Flare's own architecture and APIs; a 35-row unversioned table of vLLM metric names in docs/api.md will drift as vLLM changes (and its kv_cache_usage_perc row becomes stale as soon as #549 lands). Please remove the external vLLM mapping table from docs/api.md (or keep any migration note brief and decoupled from #549's current status).
    • Tool-limit exclusion: http.rs checks !encoder.tool_limit_reached, which excludes all responses stopped by parallel_tool_calls: false even when natural completion wins the worker cancellation race; phrase the docs/api.md rule around parallel_tool_calls: false stops rather than "responses the runtime records as cancelled".
    • http_slots scope: admit_http (helios/src/server.rs) also wraps /v1/messages/count_tokens, /v1/decisions, and /v1/systemone, so 429s on those routes also increment flare_admission_rejections_total{reason="http_slots"}.
  4. Avoid 160 bytes of atomics in single-threaded RequestRecord (helios/src/server/metrics.rs)
    Incoming.record is owned exclusively by the worker thread until completion, yet inter_token embeds Histogram<19> ([AtomicU64; 19] + AtomicU64 = 160 bytes) and executes atomic fetch_add on every committing step per request. Plain non-atomic storage (counts: [u32; 19], sum: u64 = 84 bytes) avoids atomic RMWs in the worker hot loop and nearly halves per-request memory growth.

Minor

  • In helios/src/server/http.rs, if !count && !encoder.tool_limit_reached has a dead !count check because if count { return ... } already returns before delivery.
  • Optional cleanup: unifying the three existing host-cache histograms in helios/src/server/metrics.rs onto Histogram<8> removes the duplicate hand-rolled rendering path and aligns # HELP / _sum / _count formatting.
  • Please re-review against the current docs/design-review.md (c3a9) when pushing the update.

The metrics module wrote histograms three ways. The request histograms used
`Histogram` and `Buckets`, with `# HELP` and `_sum` before `_count`. The three
host prefix-store lookup histograms (`flare_host_cache_missing_tokens`,
`flare_host_cache_estimated_transfer_ns`, `flare_host_cache_estimated_prefill_ns`)
used separate integer bound arrays, a sum array, and a hand-written render loop
without `# HELP` that printed `_count` before `_sum`. `Buckets` held `f64` bounds
in the exposed unit plus a `scale`, so every observation was divided before
comparison. `flare_time_to_first_response_seconds` was a `Histogram` owned by the
rolling first-response window and rendered through a separate hook in the
`/metrics` handler. Folding all of them onto one type gives every scrape one
histogram format and one bucket search.

`Buckets` now holds `u64` bounds on the observation grid (nanoseconds or
counts) ending at `u64::MAX`, and a `per_unit` divisor applied only when
rendering `le` labels and `_sum`. The three host lookup histograms are
`Histogram<8>` fields observed with `HOST_NANOSECONDS` and `HOST_TOKEN_COUNTS`
and rendered by `Histogram::render`; `host_cost_sums`, `HOST_TIME_BUCKETS`,
`HOST_TOKEN_BUCKETS`, and the custom loop are removed.
`flare_time_to_first_response_seconds` is a `Metrics` field observed through
`Metrics::first_response`, which `FirstResponse::output` calls through the
metrics handle it receives when the observation starts; the window keeps only its
rolling samples. A module doc names `Histogram` over `Buckets` as the form of
every observed histogram, and comments at `Metrics::store` and the retirement
render state that `flare_host_cache_retirement_seconds` copies counts owned by
the selene store.

Result: metric names, bucket bounds, and observed values are unchanged. The host
lookup histograms gain `# HELP` lines and emit `_sum` before `_count`, and their
nanosecond sums stay exact integers. Every `le` label renders the same text as
before because each integer bound divided by 1e9 is the same double as the
former decimal literal.

Evidence: the host lookup test asserts the `# HELP` line, bucket boundaries,
sums, counts, and `_sum` before `_count`; the first-response unit test asserts
one `flare_time_to_first_response_seconds` observation after two `output` calls.
Each nanosecond bound of `REQUEST_SECONDS` and `TOKEN_SECONDS` divided by 1e9
compares equal to its former literal in IEEE double arithmetic.
Build and tests: on the tree with this commit and the two that follow it,
`cargo check --locked --features server` succeeds and
`cargo test --locked --features runtime-core,server --lib -- server:: scheduler:: cache::`
reports 816 passed, 1 failed, 11 ignored. The failure is
server::protocol::decode::native_prompt_tests::messages_image_hints_end_after_expansion_for_text_and_segmented_templates,
which requires FLARE_TEST_TEMPLATE_DIR and exercises no changed path. No GPU
server run was performed, so a live scrape was not compared.

Signed-off-by: Wynn Drahorad <[email protected]>
Design-Signed-Off-By: enterprise/deepseek-v4.1-flash (omp agent); design-review=eb2f
One flag, `Encoder::tool_limit_reached`, gated the HTTP response histograms for
a whole response. When any choice reached the parallel-tool-call limit, the
response added no `flare_request_e2e_seconds`, `flare_request_choices`, or
`flare_request_max_choice_generated_tokens` observation, although the runtime
counts each choice as its own request and had already counted a sibling choice
that finished on its own as completed. The runtime termination of each choice is
what decides whether it counts as cancelled, so the HTTP gate records that
termination per choice and excludes only the cancelled choices. Only
`/v1/completions` accepts more than one choice and it rejects tools, so no public
request reaches a multi-choice tool-limit response today.

`Encoder::finish` records whether the runtime ended each choice as
`Termination::Cancelled`, before the tool-limit override of the finish reason,
and `Encoder::choice_generated_tokens` returns each choice's generated-token
count, or `None` for a cancelled choice. The HTTP handler passes that list to
`Metrics::response_completed` and no longer keeps its own per-choice count
vector or the `!count` condition, which never held because token-count requests
return before the delivery stream starts. `response_completed` observes
`flare_request_e2e_seconds` once when at least one choice was delivered, and per
prompt observes the delivered choice count and the largest delivered
generated-token count, skipping a prompt with no delivered choice. The
`# HELP` text of both choice histograms and the HTTP histogram paragraph and
vLLM table row in docs/api.md state the per-choice rule.

Result: a response whose only choices were cancelled is not observed, as
before, and a choice the runtime completed enters the response histograms even
when another choice of the same response reached the tool-call limit.

Evidence: a unit test drives an `Encoder` with two choices and parallel tool
calls disabled through two tool calls on choice 0, finishes choice 1 at EOS and
choice 0 as cancelled, asserts `[None, Some(5)]`, and asserts one e2e
observation, one choice, and a largest-choice sum of 5, with no observation for
an all-cancelled response. The existing HTTP tool-limit test still asserts zero
e2e observations for a single cancelled choice.
Build and tests: on the tree with this commit and the one that follows it,
`cargo check --locked --features server` succeeds and
`cargo test --locked --features runtime-core,server --lib -- server:: scheduler:: cache::`
reports 816 passed, 1 failed, 11 ignored. The failure is
server::protocol::decode::native_prompt_tests::messages_image_hints_end_after_expansion_for_text_and_segmented_templates,
which requires FLARE_TEST_TEMPLATE_DIR and exercises no changed path. No GPU
server run was performed, so a live scrape was not compared.

Signed-off-by: Wynn Drahorad <[email protected]>
Design-Signed-Off-By: enterprise/deepseek-v4.1-flash (omp agent); design-review=eb2f
…metric docs

Four review findings remained in the metrics and their documentation.
`flare_model_step_tokens` observed a 0-token sample for a step in which every
lane failed, lowering the mean without measuring work. The
`flare_admission_rejections_total` labels were a literal array that had to
track the declaration order of `AdmissionLimit` with nothing linking them. One
test checked a full completion and then a zero-token completion on the same
`Metrics`, so the zero-token assertions restated the first request's counts.
docs/api.md restated `# HELP` text in prose, omitted that decode time includes a
preemption stall and that the first model step of a request can be an
initialization step, and named vLLM's metric list without a source or date.

`Metrics::model_step` skips a step with zero tokens, which is a step in which
no lane made progress. `AdmissionLimit` has an `ALL` array, which also sizes
the counter array, and an exhaustive `reason` match that the render loop uses
for labels. The zero-token completion has its own test on a fresh `Metrics`
that asserts every interval histogram is empty and every token-count histogram
holds one observation. docs/api.md keeps the population rules (which requests
enter, the cancelled and failed exclusion, the two-token rule, the zero-token
rule, and the tool-limit rule from the HTTP histogram paragraph) and drops the
interval definitions the `# HELP` lines already carry. It states that decode
time, time per output token, and the spanning inter-token interval include the
wait for readmission; that the first model step can be an initialization or
vision step, so prefill time includes initialization; that a step without
progress is not observed; and that the vLLM table follows
https://docs.vllm.ai/en/latest/usage/metrics/ as checked on 2026-11-27.

Result: the model-step histogram counts only steps that did work, admission
reason labels are bound to their enum variants, the zero-token population is
tested in isolation, and the documentation describes each population without
duplicating the scrape. Metric names, labels, bucket bounds, and the vLLM table
rows are unchanged.

Evidence: the scheduler metrics test calls `model_step(0)` beside the two
nonzero steps and asserts `flare_model_step_tokens_count 2`, and still asserts
the three admission reason labels and their counts. The zero-token test asserts
zero counts for the queue, prefill, inference, time-to-first-token, decode,
time-per-output-token, inter-token, and max-token histograms, and one
observation in the prompt, computed-prompt, generated, and preemption
histograms.
Build and tests: on this commit's tree,
`cargo check --locked --features server` succeeds and
`cargo test --locked --features runtime-core,server --lib -- server:: scheduler:: cache::`
reports 816 passed, 1 failed, 11 ignored. The failure is
server::protocol::decode::native_prompt_tests::messages_image_hints_end_after_expansion_for_text_and_segmented_templates,
which requires FLARE_TEST_TEMPLATE_DIR and exercises no changed path. No GPU
server run was performed, so a live scrape was not compared.

Signed-off-by: Wynn Drahorad <[email protected]>
Design-Signed-Off-By: enterprise/deepseek-v4.1-flash (omp agent); design-review=eb2f
@flare-autobot flare-autobot added area:api Serving API, protocol encoding, tool parsing, and client-visible behavior. enhancement New feature or request triage:review Proposed change needs code review; this does not imply merge readiness. labels Nov 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:api Serving API, protocol encoding, tool parsing, and client-visible behavior. enhancement New feature or request triage:review Proposed change needs code review; this does not imply merge readiness.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants