Conventions and duplication review of PR #548 — Add request latency histograms and process metrics
PR #548 (draft, head ebecef1, base main, 8 files +545/−20, no reviews, no CI yet, author WynnD / oystersmiles, closes #536). Lens: conventions and duplication. I read every changed file in context and followed the callers of each changed function. No blocking finding. Five should-fix findings and one nit; each is a departure from an existing in-repo precedent, cited below.
Key findings
- (Should fix) A third histogram implementation lands in
metrics.rswith nothing migrated onto it.Buckets/Histogram(helios/src/server/metrics.rs:212-298) sits beside two hand-rolled fixed-bucket histograms in the same module, so three bucket encodings and three_count/_sumorders now coexist. - (Should fix)
metrics/process.rsre-implements OS helpers that already exist inruntime_core/protection.rsandeos/src/unix.rs, althougheos/is the repository-designated home for host OS operations (AGENTS.md:20-21). - (Should fix) The two HTTP-observed histograms in one PR are owned by two different structs and rendered through two different paths, giving
/metricsthree assembly points. - (Should fix)
docs/api.mdstill claims every counter and gauge starts withflare_, contradicted by the six newprocess_*series documented 27 lines below. - (Should fix) The
request_e2eobservation is duplicated inline twice in one function, in two accessor styles, against the file's own named-helper convention. - (Nit)
process::metricduplicatesmetrics::metricand does not inherit label escaping.
Should fix
1. Histogram/Buckets is the third Prometheus-histogram implementation in one module — metrics.rs:212-298
New in this PR: Buckets<const N> (metrics.rs:212-241, with REQUEST_SECONDS/TOKEN_SECONDS/PROMPT_TOKENS), Histogram<const N> (metrics.rs:245-257) with observe (metrics.rs:260-271) and render (metrics.rs:273-297).
The same module already contains two fixed-bucket histograms:
- Host cost histograms: bucket constants
HOST_TIME_BUCKETS/HOST_TOKEN_BUCKETS(metrics.rs:200-210), observation inline inMetrics::host_lookup_cost(metrics.rs:670-692 —limits.iter().position(...)thenbucket.fetch_add, plushost_cost_sums[index].fetch_add), rendering inline at metrics.rs:1029-1065 (+Infforlimit == u64::MAX). - Retirement histograms: bucket gauges filled in
store(metrics.rs:705-711), rendered at metrics.rs:851-876 with bounds scaled by*ms as f64 / 1000.0.
The new Histogram<21> is exactly what the host-cost site needs (same fixed bounds, per-bucket AtomicU64 counts, one sum atomic), but nothing in the PR converts either existing site. Consequences visible in the code:
- three bucket encodings in one file:
u64::MAXsentinel (metrics.rs:208, :1053),f64::INFINITY(metrics.rs:222, :281), millisecond integers vs seconds f64 (metrics.rs:851-876); - three different line orders:
_countthen_sum(metrics.rs:1060-1064),+Inf/_count/_sum(metrics.rs:867-876),_sumthen_count(metrics.rs:291-296); - the old path has an unchecked
position(...).unwrap()(metrics.rs:689), which the newobserveavoids withunwrap_or(N - 1)(metrics.rs:268).
Why it matters. AGENTS.md:188-193 rejects churn but asks for the smallest footprint in shared code; a second generic histogram left beside two hand-rolled ones is the form a fourth copy will take. The PR description states it and #537 "add different regions" of metrics.rs, so migrating the host-cost histograms is merge-order safe.
Fix. Express host_missing_tokens / host_transfer_ns / host_prefill_ns and host_cost_sums as Histogram<8> instances over Buckets<8>, deleting the bucket loop in host_lookup_cost (metrics.rs:672-691) and the render block at metrics.rs:1029-1065. If migration is deliberately out of scope, say so in the description so the third form is at least documented.
2. process.rs duplicates OS helpers already in eos/ and helios::os — metrics/process.rs:56, 65-77
The new helios/src/server/metrics/process.rs reads procfs and libc limits itself:
std::fs::read_dir("/proc/self/fd").ok().map(|entries| entries.filter_map(Result::ok).count() as u64)(metrics/process.rs:65-67) is character-for-characteropen_descriptors()in helios/src/runtime_core/protection.rs:290-302.libc::sysconf(libc::_SC_PAGESIZE)(metrics/process.rs:56) duplicateseos::page_size()(eos/src/unix.rs:73-75), which helios re-exports ascrate::os::page_size()(helios/src/os.rs:8) and uses incuda.rs(not opened). The duplication has already drifted: eos falls back to 4096, whileprocess.rsomitsprocess_resident_memory_bytesentirely (metrics/process.rs:97-105).libc::getrlimit(libc::RLIMIT_NOFILE, ...)(metrics/process.rs:68-77) duplicates the call insideeos::raise_open_file_limit(eos/src/unix.rs:138-165), whose doc comment says it "Returns the resulting soft limit whengetrlimitsucceeds" — i.e. exactlyprocess_max_fds. It is re-exported throughcrate::os.
Why it matters. AGENTS.md:20-21: "The eos/ crate holds the host operating-system operations that Helios and Selene use." A new file calling libc::sysconf/libc::getrlimit//proc/self/fd directly adds a fourth copy of that layer inside Helios instead of one getter in the designated module.
Fix. Add open_file_limit() -> Option<u64> (or return the limit from the existing helper) and open_descriptors() -> Option<u64> beside raise_open_file_limit in eos/src/unix.rs, call crate::os::page_size(), and leave only the /proc/self/stat and /proc/stat btime parsing in process.rs — I searched and found no existing Rust implementation of those two, so that part is genuinely new.
3. The TTFR histogram is owned outside Metrics while its sibling is inside — latency.rs:33-37, 108-119, 122-131; server.rs:671
FirstResponseSamples gains histogram: super::metrics::Histogram<21> (latency.rs:36). FirstResponse::output records the same duration twice — into the rolling window (latency.rs:111-112) and into the histogram (latency.rs:113-116). render_histogram (latency.rs:122-131) is called from the route handler at helios/src/server.rs:671. (The double bookkeeping itself is legitimate: the 60-second median is a documented JSON field, docs/api.md:329-336.)
The asymmetry is the finding. The other HTTP-observed histogram in this same PR, request_e2e, is a Metrics field (metrics.rs:327), set through Metrics::render (metrics.rs:1391-1392) alongside every runtime request histogram (metrics.rs:1413-1423), and observed via metrics_handle() from http.rs:615/:632. With state.first_response.render_histogram at server.rs:671 and metrics::process::render at server.rs:709, /metrics text is now assembled at three points with no stated rule, and flare_time_to_first_response_seconds cannot be discovered from Metrics at all.
Fix. Pick one rule and state it: move the histogram beside request_e2e in Metrics and observe it from FirstResponse::output through a handle, or keep the ownership and note in Metrics::render's doc comment that HTTP-owned histograms are appended by the route handler.
4. docs/api.md contradicts itself about the flare_ prefix — docs/api.md:287-289 vs 315-318
docs/api.md:287-289 (unchanged by this PR) reads "GET /metrics returns Prometheus text exposition format 0.0.4 by default. Counter and gauge names start with flare_, such as …". The PR adds six series that do not, emitted at metrics/process.rs:78-127 and documented at docs/api.md:315-318. The new paragraph is accurate, but it does not reconcile the older sentence, and the surrounding paragraphs invite {__name__=~"flare_.*"} scrape filters that would silently drop all six.
The names themselves are right — they are the standard Prometheus process-collector names #536 asked for. This is a documentation consistency finding only.
Fix. One clause at docs/api.md:288-289: "Counter and gauge names start with flare_, except the standard process_* series below…".
5. The request_e2e observation is written inline twice, in two styles — http.rs:615 and http.rs:632
In one function (deliver, the streaming/non-streaming split at http.rs:600-645):
- streaming branch, http.rs:615:
if !count { metrics.request_e2e.observe(&super::metrics::REQUEST_SECONDS, admitted_at.elapsed().as_nanos() as u64); }, wheremetricscame fromstate.model.metrics_handle()at http.rs:603; - non-streaming branch, http.rs:632:
if !count { state.model.metrics().request_e2e.observe(&super::metrics::REQUEST_SECONDS, admitted_at.elapsed().as_nanos() as u64); }.
The file's own convention for shared one-liners in this region is a named helper (failure_log, rejection, rejection_details, with_request_id, http.rs:39-69), and the closure already captures stream_state/id.clone() (http.rs:384-385, :601). This is also the one new observation not behind a Metrics method — the runtime histograms go through Metrics::request_completed (metrics.rs:449-478) — so the PR's own "record in one place" argument is not extended to the e2e histogram, which now has two call sites that must track three delivery branches.
Fix. One fn observe_e2e(&self, admitted_at: Instant) on the metrics handle, called from both branches; it also removes the repeated as_nanos() as u64 and REQUEST_SECONDS.
Nit
6. process::metric duplicates metrics::metric — metrics/process.rs:42-49 vs metrics.rs:1597-1602
Both emit # HELP/# TYPE/value; the copy differs only by not applying the flare_ prefix and by taking impl Display rather than u64. The prefix difference is why it was written, but the generalisation is a parameter. Note also that the copy does not use escape_prometheus_label (metrics.rs:1604-1615): harmless today (no process_* series takes a label), but the second emitter will not inherit escaping if one is added. Fix. Keep one emitter in metrics.rs, pass the full name, delete process::metric.
Verified non-findings
RequestTimesvsscheduler::RequestAccounting— not a duplicate.RequestAccounting(helios/src/scheduler/policy.rs:53-65) is scheduler-owned, reset byfinish, and not readable afterpark→resume_decoded_sequence(runtime.rs:1556-1575 rebuilds fromParked), while preempted requests must keep their stamps.CheckpointAccounting::initial_prefill_ns(scheduler/checkpoints.rs:24) is a prediction, not a measurement. No reusable mechanism exists.- latency.rs rename —
Mutex<Samples>→{ window, histogram }(latency.rs:33-37) updates every use site (latency.rs:73, 111, tests 198, 213, 222); no stale.0access remains. - Bucket reuse —
render_histogramreusesREQUEST_SECONDS(latency.rs:128) rather than defining a fourth bucket set, which matches #536's "same start and end points as the current median gauge". - SPDX header — process.rs:1 matches helios/src/server/latency.rs:1; not worth a finding.
times: Default::default()struct-literal additions (runtime.rs:913, :3254, phase_tests.rs:251) follow the existing pattern.
Open questions / not verifiable from the code
- Whether the author intends to migrate the host-cost histograms in this PR or a follow-up. The description says the PR and #537 touch different regions of
metrics.rs, which implies the migration is merge-order safe but does not say it is planned. That decision settles finding 1's fix scope. - Whether
request_e2eandtime_to_first_responseownership was a deliberate split (HTTP-layer vs runtime-layer metrics) that should be documented rather than unified. No design note in the repo states a rule either way;docs/design-review.mdwas checked and does not. - The live-scrape numbers in the PR description (counts,
_sumvalues, prompt-token buckets) cannot be re-verified here; they are consistent with the code paths but only a scrape on a running server would confirm them.