Full report — PR #548 "Add request latency histograms and process metrics"
Draft, head ebecef1, base main, 8 files, +545/−20, closes #536, author WynnD (Discord oystersmiles). No reviews, no CI checks on head.
Key findings
Right problem, right shape, not ready as-is. The core design needs no change: the five request histograms are observed in the single function that already increments flare_requests_completed_total (helios/src/server/metrics.rs:452-480), the two former direct fetch_add sites are now calls (helios/src/server/runtime.rs:1841-1846, :1993-1998), no per-request storage is added, Snapshot/format=json is untouched, and nothing crosses the preparation/runtime boundary, adds a flag, or branches per model.
Two blockers, both cheap (one code guard or one docs clause; one description rewrite). Five should-fix items, four of them one-clause doc/semantics repairs. The removable margin is large and concentrated in the one new file: ~130 of the +545 added lines, about 100 of them inside helios/src/server/metrics/process.rs. Nine nits.
Blockers
1. flare_request_e2e_seconds includes responses the runtime counts as cancelled — and the new docs say it cannot
Finding / evidence. On the parallel-tool-limit path the delivery loop drops non-terminal events (helios/src/server/http.rs:471-476), finishes the decoder with Termination::Cancelled (:526), and calls generation.cancel() (:563-567). The terminal Finished event still passes, the loop reaches yield Delivery::Complete(response) (http.rs:598), and both delivery arms observe e2e guarded only by !count (:614-617 streaming, :631-635 non-streaming). The runtime, meanwhile, counts that request in metrics.cancelled via finish_cancelled (helios/src/server/runtime.rs:1317, :1338, :1360, :1407; :293-302) and never reaches Metrics::request_completed (metrics.rs:452-480). So the response lands in flare_requests_cancelled_total and flare_request_e2e_seconds but in none of queue/prefill/decode/TPOT/prompt-tokens and not in flare_requests_completed_total. The cancel flag also races the natural finish (:1993-1998), so membership is timing-dependent rather than a fixed rule — worse for dashboards than either consistent choice.
Requested change (either). (a) Skip the e2e observation when encoder.tool_limit_reached — or thread the termination through Delivery::Complete and observe only successful terminations; or (b) narrow docs/api.md:312-313 to the five runtime histograms and say explicitly that e2e measures every response delivered to the client. Add one test that drives a request past the parallel tool limit and asserts flare_request_e2e_seconds_count against flare_requests_cancelled_total.
Why. docs/api.md:312-313 states the opposite as an absolute ("Cancelled and failed requests enter only flare_requests_cancelled_total and flare_requests_failed_total"), and the PR description repeats it. An operator reconciling flare_request_e2e_seconds_count with flare_requests_completed_total is comparing different populations while the page says they cannot differ. AGENTS.md:182-186 rejects a weakened guarantee; here the doc claims an invariant the code does not hold.
2. The Evidence section overstates coverage and does not reconcile; the change does touch the serving and scrape paths
Finding / evidence. "Nothing about serving changes" is inaccurate. The change adds a monotonic clock read plus a loop over step.lanes on every submitted step (runtime.rs:2187-2203), two stores per committed token (:1774-1775), and blocking procfs I/O on every text scrape — /proc/self/stat, the whole of /proc/stat just to find btime, read_dir("/proc/self/fd"), two sysconf, one getrlimit (helios/src/server.rs:709 → metrics/process.rs:52-133). (Note: the only production caller of Metrics::render is the /metrics route at server.rs:660 plus tests — the terminal dashboard uses snapshot() only, dashboard.rs:128-146 — so the cost is per text scrape, not per dashboard refresh.)
The scrape numbers do not reconcile: "counts gained 5 for each runtime histogram and 6 for the first-response histogram" over a window that also served the agent session's own requests; the prompt-token breakdown (le="64" +1, le="2048" +4) accounts for five runtime observations and leaves the sixth first-response observation unexplained; no sum is attributed to an individual request; and the tree measured is fork commit 5ffe4d54 with this change cherry-picked, not main. "CI covers the first two" is an expectation — head ebecef1 carries no checks, though the workflow does build and test Windows and the full helios suite (.github/workflows/native-serving.yml:20-21 (not opened), :63-68).
Requested change (description only). Say "no change to serving output" and list the per-step and per-scrape cost as known and unmeasured (reading all of /proc/stat for btime is avoidable); restate the live scrape as a smoke check with the population caveat explicit (6 TTFR vs 5 runtime observations, session traffic included, measured on 5ffe4d54 + this diff); keep the unit tests as the primary evidence; name the CI job or drop the sentence.
Why. AGENTS.md:194-199 and docs/design-review.md:97-105 (not opened) require validation and material limitations to be described honestly.
Should Fix
1. docs/api.md:305-313 — "one observation per completed generation" is false for decode and time-per-output-token
Metrics::request_completed observes prompt tokens unconditionally (metrics.rs:460-461), queue only with a scheduled stamp, prefill only with a first token, and decode/TPOT only when generated_tokens > 1 (:462-479) — as the PR's own HELP strings already say (metrics.rs:1406-1418) while the neighbouring HELP strings do not (:1395-1404, :1419-1424). A prompt-only request therefore appears in prompt tokens and the completed counter but in no timing family; the families do not share a denominator.
Change. Split the sentence by eligibility; add "cumulative since server start" (the "Totals count from server start" note at :329-330 sits beside a 60-second windowed median, so a reader can take the histograms as windowed); and replace the vague lead-in "Request histograms observe the served response" (:300-301) with the two groups: HTTP-level response timing (e2e, TTFR) and runtime per-request timing (queue, prefill, decode, per-token, prompt tokens). Keep the test at metrics.rs:1684-1697 that pins the generated_tokens > 1 exclusion — it is the only evidence for this doc fix. A one-line comment at metrics.rs:470-471 would also stop the next editor from "fixing" the guard.
2. docs/api.md:301-304 and :288-289 — two one-clause edits
Streaming observes e2e inside the SSE filter_map (http.rs:614-617), so only if the client drains the body to Delivery::Complete; non-streaming observes in the handler (:631-635) before the body is polled, so it records even if the client never reads. The asymmetry is pinned by the PR's own tests (phase_tests.rs:4407-4434 vs :4437-4473) but not stated, although the adjacent TTFR sentence does say "once the client reads it". Separately, "Counter and gauge names start with flare_" (:288-289, pre-existing) is contradicted by the six process_* series this PR documents at :315-318 and emits at process.rs:78-132; the surrounding text invites {__name__=~"flare_.*"} filters that would silently drop all six.
Change. "counts each successful generation whose response the client reads to the end, from admission to delivery completion", keeping the TTFR caveat; and scope the prefix rule to runtime metrics or add "except the standard process_* series below", following the precedent already set at docs/api.md:334-336.
3. flare_request_prefill_seconds silently includes vision work
first_scheduled_ns is stamped over every step.lanes entry (runtime.rs:2191-2203), before the if step.kind == GraphKind::Vision split at :2208, although step.lane_kind(row).is_prefill() is available and used elsewhere at :2281. For a multimodal request, "queue" ends at the first vision step and "prefill" covers vision+prefill until the first generated token — defensible, but the same page uses the narrower convention for prefill_tokens ("excluding padding and prefix reuse", docs/api.md:340).
Change (cheapest). One phrase in docs/api.md:307-308: "the request's first model step to its first committed generated token (including a vision step that runs first)". Alternative: narrow the stamp loop to prefill lanes.
4. The new module hand-rolls OS primitives that already live in eos/
AGENTS.md:20-21 ("The eos/ crate holds the host operating-system operations that Helios and Selene use") and the charter's "Solve the right problem in the right place":
libc::sysconf(_SC_PAGESIZE)(process.rs:55-58) isflare_eos::page_size()(eos/src/unix.rs:73-75; re-exported athelios/src/os.rs:8; unconditional dependency athelios/Cargo.toml:34), which needs nounsafeand defaults to 4096.getrlimit(RLIMIT_NOFILE)(process.rs:68-77, 10 lines + a SAFETY comment) duplicates the call insideflare_eos::raise_open_file_limit(eos/src/unix.rs:138-165), whose doc says it "Returns the resulting soft limit whengetrlimitsucceeds"; withdesired = 0it returns the soft limit unchanged without callingsetrlimit(:144-147).- The
/proc/self/fdcount (process.rs:65-67) is character-for-characteropen_descriptors()athelios/src/runtime_core/protection.rs:291-302— now two copies of one procfs read with two return conventions (Option<u64>vs inline.ok().map).
Change. Call flare_eos::page_size(); take the soft limit from eos (or add one open_file_limit() beside raise_open_file_limit); move open_descriptors() into eos and call it from both protection.rs and the renderer; leave only the /proc/self/stat and /proc/stat btime parsing in process.rs (no existing Rust reader for those two). Deletes ~25 lines, two unsafe blocks and one duplicate.
5. Authorization rests on an outside request framed as vLLM parity
The charter's "What gets merged" accepts a maintainer request, roadmap item, reproducible bug, measured performance/memory issue, or bad docs. AGENTS.md:165-169 and :201-202 make an explicit maintainer request the authorization; #536 is an outside request to port vLLM dashboards, and vLLM is a listed competitor, not a compatibility target (AGENTS.md:188-190 warns against speculative compatibility). The names do not match vLLM's either (vllm:time_to_first_token_seconds, vllm:e2e_request_latency_seconds), so "parity" is not literally achieved.
Change. Record a maintainer decision on #536, or reframe the description around the defect the metrics remove (tail latency, queue delay, prefill time and decode rate are currently unobservable from a scrape), which the charter does accept. Cheap; only the stated motivation is contested, not the code.
Subtract / Simplify
Could remove ~130 of the +545 added lines — about 100 of them inside the one new file — with no behaviour lost. Nothing in the request-histogram core should be cut.
metrics/process.rs: six fallbacks for sources that cannot fail, plus a test that asserts the kernel (~55 of 184 lines)./proc/self/stat,/proc/statand/proc/self/fdare kernel-provided for the calling process, andgetrlimit(RLIMIT_NOFILE)cannot fail for a valid resource, yetrender_linuxthreads sixif let (Some, Some)blocks (process.rs:79-132) plusOptionplumbing inparse_btime(:34-40), justified by a module doc promising "a scrape never fails" (:1-6) — exactly the fallback layerAGENTS.md:188-193rejects without a concrete requirement, and the repo's own precedent defaults the page size once (eos/src/unix.rs:74). Onelet Some(stat) = … else { return }, page size and fd limit from eos, and only the/procread fallbacks collapse five combinations to two and the doc comment to a sentence. Also droprender_reports_process_memory_descriptors_and_start_time(:157-183): it asserts live kernel values and fails only if the host kernel is broken, while the end-to-end scrape check already exists atphase_tests.rs:5377-5388. Keepparse_stat_reads_fields_after_a_parenthesized_command_with_a_paren(:148-155), which tests the one non-obvious parser.- The new
Histogram<N>was added beside the hand-rolled histograms it duplicates (~40 lines).Buckets/Histogram(metrics.rs:212-298) is exactly what the three host-cache cost histograms already hand-roll:HOST_TIME_BUCKETS/HOST_TOKEN_BUCKETS(:200-210), the parallel arrays andhost_cost_sums(:382-385), the.position(..).unwrap()loop inhost_lookup_cost(:670-692) and the 37-line render loop (:1029-1065). AsHistogram<8>overBuckets<8>those delete two constants,host_cost_sums, the zip/position loop (threeobservecalls remain) and the whole render loop (threerendercalls remain); the existing testhost_outcomes_and_capacity_have_bounded_labels_and_cost_histograms(:1740-1796) reads rendered text and keeps passing if the labels stay, with onlyflare_host_cache_*_sumchanging from a truncated integer to the same number divided byscale. It also removes the third bucket encoding, the third_count/_sumorder, and the uncheckedunwrap()at:689that the newobservealready avoids (unwrap_or(N-1),:268). Merge-order safe against #537 (different region ofmetrics.rs). - One e2e observation point, and the TTFR histogram belongs with the other six (~18 lines). Every successful request yields exactly one
Delivery::Complete(http.rs:598; failuresreturnright afterDelivery::Failedat:574-578), so the sameif !count { …observe(REQUEST_SECONDS, admitted_at.elapsed()…) }is written twice (:614-617,:631-635) and the streaming arm needsstate.model.metrics_handle()(:603) only to satisfy the'staticclosure. Observe once just before theyield, usingstate.model.metrics(); the timing is unchanged (that line is reached exactly when the two arms fire today), andencoder.tool_limit_reachedis in scope there, so the Blocker 1 guard belongs there too. Movingtime_to_first_responseontoMetricsdeletes the extra struct field, the secondimpl FirstResponseSamplesblock (latency.rs:122-131),render_histogramandserver.rs:671, leaving one stated rule for where/metricstext is assembled instead of three; then the duplicate assertions atphase_tests.rs:4466-4471and:4428-4432go, keeping the behavioural bits each test proves (0 after a failed stream, 1 after one offered body). - Smaller.
#[cfg(target_os = "linux")]onpub(super) mod process;(metrics.rs:12) and on the call (server.rs:709) deletes the non-Linux shim andlet _ = text(process.rs:8-14), matching howprotection.rs:291-302andcore/cache.rs(not opened) gate platform code — worth doing precisely because Windows was not built here. Optionally dropprocess_virtual_memory_bytes(process.rs:88-96) andprocess_max_fds(:124-132), neither of which is in #536's table, for ~18 lines plus two doc mentions and two test assertions; keepprocess_max_fdsif the fd-budget path is the motivation.
Keep. The five bucket lists (metrics.rs:219-241) are the #536 deliverable; RequestTimes and its two stamps (runtime.rs:1774-1775, :2187-2203) are the minimum for queue/prefill/decode, and preemption survival is free because parking moves Incoming whole (:2094-2121); request_completed as the single place that increments the counter and observes the histograms (metrics.rs:452-480) is the right consolidation.
Nits (9)
process::metric(process.rs:42-49) duplicatesmetrics::metric(metrics.rs:1597-1602) minus theflare_prefix, and does not inheritescape_prometheus_label(metrics.rs:1604-1615; harmless today since noprocess_*series takes a label). One emitter taking the full name, callers addingflare_, deletes the copy.parse_stat(process.rs:19-32) returnsSomefor any line containing), so a shifted/malformed line yields systematically wrong CPU/memory/start-time values instead of omitting them, contradicting the module doc. Require the expected field count.process_open_fds(process.rs:65-67) includes the directory read that counts it (+1 vs Prometheus'client_golang, which excludes it). The HELP string says so, so it is a documented deviation — noted only because #536's motive is stock process-dashboard parity.Worker::publishrecomputescarried.prompt_tokens.unwrap_or(prompt_tokens)andcarried.generated_tokens + generated(runtime.rs:1993-1998and again:2015-2019) whileWorker::completealready hoists them (:1838-1840); two locals make both call sites one shape (~4 lines).request_completednestsif let Some(first) = times.first_token_nsinsideif let Some(scheduled) = times.first_scheduled_ns(metrics.rs:462-469), a state that cannot occur — tokens are only committed for requests stamped inreserve_and_pack(runtime.rs:2191-2203,:1774). Flatten to siblings; and reshape the test's impossible{first_scheduled_ns: None, first_token_ns: Some}case (metrics.rs:1684-1697) into the realistic both-Noneprompt-only request — keeping the case, since it is the only evidence for the exclusion documented in Should Fix 1.last_token_nscannot be replaced byRequestAccounting::last_output_ns, which is set on publication (scheduler/policy.rs:270-275) rather than token commitment; the field is justified, but one comment saying so would save the next reader the lookup.- Comment/prose weight: four doc comments cover three
RequestTimesfields (metrics.rs:212-213,:243-244,:261-262,:300); the:261-262rounding note defends an invariant the type already guarantees;runtime.rs:2189-2190only parses if the reader already knowsreserve_and_packhas a second caller;process.rs:1-6is three sentences for a forty-line module;docs/api.md:300-313restates the HELP strings sentence for sentence (keep the two facts a scrape cannot give: histograms are absent fromformat=json, andprocess_*is Linux-only). render_histogramsits in a secondimpl FirstResponseSamplesblock (latency.rs:122-131) instead of the block at:63-101; it goes away entirely with the Subtract item above.- Description wording: "The existing first-response sampler observes … its median gauge and 60-second window are unchanged" — make the sampler the subject; and the cherry-pick sentence should say plainly that the measured tree is
ebecef1rebased onto5ffe4d54with no other code change, since the counts are load-bearing.
Verified sound (recorded so it need not be re-derived)
- Counter and histograms cannot diverge. The only increment of
completedismetrics.rs:459insiderequest_completed(:452-480); both former directfetch_addsites are now the calls atruntime.rs:1841-1846(user/text stop) and:1993-1998(natural finish). - Stamps survive preemption.
parkmovesIncominginto the parked list (runtime.rs:2094-2121) and readmission reuses it;get_or_insertkeeps the earliest stamp (:1774,:2201);phase_tests.rs:576-583exercises the parked/readmitted path. - Bucket math and render.
observeuses first-matchexposed <= boundwithunwrap_or(N-1)(metrics.rs:260-271); every bound list ends atf64::INFINITY;+Infequals_count; integer ns truncation is harmless against the 1 ms smallest bound; output is valid Prometheus 0.0.4. - Arithmetic is total.
generated_tokens > 1guards the decode/TPOT division (metrics.rs:470-478);saturating_subthroughout; timing families observed only when their stamps exist. - JSON untouched.
Snapshotgained no fields;format=jsonreturns atserver.rs:645-658before any histogram rendering. parse_statsplits after the last)so acommcontaining)or spaces cannot shift fields (process.rs:19-32).- Non-Linux build. Every
libcuse inprocess.rsis insidecfg(target_os = "linux");libcis already a helios dependency (helios/Cargo.toml:50); no new non-Linux compile risk visible (the Windows build was not run by the author, but CI does build and test it). - No architectural or charter violation in the change itself. No per-model branch, no flag, no environment switch, no prepared-metadata or captured-graph change, nothing crosses the preparation/runtime boundary.
/v1/messages/count_tokensexclusion is exactly thecountguard (http.rs:131, used at:615and:632), as described. The failure path never observes e2e (:574-578).- Description scheme and Discord line are compliant (
AGENTS.md:74-80,:142-150), and the merge-order note about #537 concerns a genuinely different region ofmetrics.rs.
Corrections to lens input (do not repeat their errors)
- The claim that
Metrics::renderis also called by the terminal dashboard is false:dashboard.rs:128-146uses onlysnapshot()andpersistent_worker_snapshot(). The per-scrape procfs cost is per/metricstext scrape only. - Rejected suggestions: dropping
scale: f64(thelelabels must print seconds, so the divisor is load-bearing — removing the field only moves the conversion into the renderer); deleting the half ofrequest_histograms_bucket_completed_request_timingsthat pins thegenerated_tokens > 1exclusion (it is the only evidence for the doc fix); folding the runtime histograms onto[u64; N]arrays (the opposite direction to the migration that shrinks the file); and making "record e2e at runtime completion" the required fix (a bigger change; offered only as the alternative under Blocker 1).
Open questions
- Is the tool-limit path supposed to appear in e2e (a client did receive a response)? That decides whether Blocker 1's fix is the code guard or the doc clause.
- Should a vision step terminate queue time, or should
first_scheduled_nsbe stamped only for prefill/generation lanes? - Does the author intend the host-histogram migration in this PR or a follow-up? It is the largest single saving and the decision sets the scope of Subtract item 2.
- "CI covers the first two" — settled only by naming the job, or by a run on
ebecef1. - The commit message body (required to follow the four-part scheme by
docs/design-review.md:139-145(not opened), plus theDesign-Signed-Off-Byacknowledgment referenced atAGENTS.md:38-41) could not be checked: the history view exposes only the subject line. - #549 (same author, same day) may edit the same
docs/api.mdmetrics section; if both land, the naming-rule edit in Should Fix 2 may need applying twice. Not diffed.