Case file: PR #691 — helios/server: report reused prompt tokens in continuous_usage_stats chunks
https://github.com/NVIDIA/hyperflare-inference/pull/691 · fixes #448 · author jcartu (CONTRIBUTOR, Discord jcartu) · branch fix/continuous-usage-cached-tokens → main · head ef45ca9, base c513e46 · opened 2026-12-02 20:54, last updated same minute · 6 files, +868/−40 · ready for review, no labels, no CI checks, no reviews, no comments.
Key findings
What a reader cannot learn from the description:
- New silent default.
Generation::wait_for_first_tokennow returnsOk(0)when the receiver was already taken (helios/src/server/runtime.rs:159-164), i.e. a path that used to be aResult<()>check now reports "zero cached tokens" rather than an error. Undeclared. - New failure path out of the worker.
Incoming::observe_token_withis fallible and its closure callsself.scheduler.request(token.request)?(runtime.rs:2011-2016). A retired/stale handle at first-token time now propagates anErrout ofWorker::complete, and the worker'srunloop returns it andfail_alls outstanding requests. Before this PRobserve_tokenwas infallible. The description says only that the lookup avoids "per-token scheduler lookups". - Docs were deliberately not touched, although the bug issue offered two resolutions — fix the code, or amend
docs/api.mdto callcached_tokensfinal-only (see #448 body). The PR takes the first option and leavesdocs/api.md:1013-1045unchanged; the docs already promised the new behavior, so nothing drifts, but there is also no release note that these values are now populated mid-stream. - No
docs/TODO.txtentry for the untested GPU/live-serving path, althoughAGENTS.md:58requires recording unrun checks there.docs/TODO.txtis not among the changed files. - Test-weight and inconsistent suite counts. ~742 of the +868 lines are tests (
helios/src/server/runtime/phase_tests.rs+649/−9,helios/src/server/protocol/tests.rs+108/−0); production delta is ~110 lines. The description's helios counts (1821 passed / 47 ignored) differ from the same author's same-day #692 (1884 / 84) for the same command, so the numbers were measured on different revisions and are not directly comparable. - Merge-order debt. #692 (same author, same day), #548 and #560 all still carry the pre-#691
first_token: oneshot::Receiver<Result<()>>and the pre-#691ObservedTokenarm, so landing #691 first forces rebases in three open PRs (one the author's own, two WynnD's). - Engagement: none. Zero comments, zero reviews, no CI run, and the repo's
flare-autobotreviewer — which posts intake reviews on other PRs within minutes (e.g. #560) — has not posted here yet.
The change
Plain terms: with "stream_options": {"include_usage": true, "continuous_usage_stats": true}, intermediate Chat/Completions SSE chunks reported prompt_tokens_details.cached_tokens: 0 while only the terminal usage chunk reported the reused-prefix count. The count is already final when a request produces its first token (pre-token requeue transitions happen before generation; later preemption/close/grammar transitions lock the count into Carried::reused_prompt_tokens). The PR therefore hands the count to the HTTP layer through the existing first-token oneshot and writes it into the encoder's per-choice usage before any text chunk is emitted.
File map (verified against the diff):
helios/src/server/runtime.rs(+69/−24)Generation::first_tokenbecomesOption<oneshot::Receiver<Result<u64>>>;wait_for_first_tokenreturnsResult<u64>(runtime.rs:159-164); newhas_pending_first_token(:166) andtake_reused_prompt_tokens(:170-183,try_recv-based, clears the receiver onOkandErr/Closed).Incoming::observe_token(token, reused)delegates to newobserve_token_with(token, impl FnOnce() -> Result<u64>)(:385-404); the closure runs only while the sender is present (:393), so subsequent tokens do no scheduler lookup.Active::close_reasoninggains areused_prompt_tokensargument, so forced close tokens also carry the count.Worker::completecallsobserve_token_with(token, || Ok(carried.reused_prompt_tokens.unwrap_or(self.scheduler.request(token.request)?.reused_prompt_tokens())))(runtime.rs:2011-2016); the forced-reasoning-close path uses the samecarried…unwrap_or(reused)shape.- No
GenerationEventvariant, soPrompt::output_event_capacityandResponseLifecycleare untouched — the description states this and the diff confirms it.
helios/src/server/protocol/encode.rs(+5/−0): one new method,report_cached_tokens(index, cached)→self.usage[index].cached = cached(encode.rs:288-292). No validation ofindex; the value is overwritten later byEncoder::finishwith the authoritative per-choice count.helios/src/server/http.rs(+36/−6):pending_cached: Vec<usize>seeded from(0..size).step_by(decoded.request.choices)filtered togenerations[i].is_some(), only whencontinuous_usage(http.rs:404-413).- Chat:
generation.wait_for_first_token().await→report_cached_tokens(0, reused)andpending_cached.clear(), beforeencoder.start()emits the initial role chunk (http.rs:414-431);Erryields the existing failure frame. - Completions: on
GenerationEvent::ObservedToken, ifcontinuous_usage,pending_cached.retain(...)drains ready counts viatake_reused_prompt_tokens()and re-arms onhas_pending_first_token()(http.rs:509-526). Once the list empties the scan is a singleis_emptycheck.
- Tests:
helios/src/server/protocol/tests.rs(+108) —continuous_usage_reports_cached_tokens_before_finish,continuous_usage_multi_choice_reports_first_choice_cached_tokens_per_prompt;helios/src/server/runtime/phase_tests.rs(+649/−9) —continuous_usage_streams_report_reused_prompt_tokens_and_preserve_messages,completions_continuous_usage_tracks_staggered_first_choice_readiness,chat_continuous_usage_preserves_initial_cached_tokens_across_preemption, plus an updated assertion indisabled_host_store_preserves_decode_prefix_reuse_and_cancellation;runtime/response_lifecycle_tests.rs(+1/−1) — mechanicalobserve_token(1)→observe_token(1, 0).
Description vs diff: the description's claims about what changed match the code, with the exceptions in Key findings 1–4 above. Also worth noting: the mechanism is coupled to generate_many_observed — ObservedToken only exists on that path (http.rs:330-331, selected when continuous_usage), so no separate event was needed. max_tokens: 0 requests (moved to zero, http.rs:311-315, 453-466) are never polled, so they keep reporting zero cached tokens, consistent with docs/api.md:1058-1061. Completions echo frames are emitted before the event loop (http.rs:437-452) and necessarily carry zero — the description discloses this.
The why
- #448 "
continuous_usage_statsintermediate Chat chunks reportcached_tokens: 0although the docs promise cumulative counts" — shieldstar, opened 2026-11-21, labelsarea:api,bug, still open. Repro: same generation, intermediate chunkcached_tokens: 0, final chunk3. Citeddocs/api.md:806-812(cumulative promise) andencode.rs:618-640(usage_value); encoder-level unit test only, no GPU. - yatesdr (2026-11-21) confirmed at main
21a40f05thatcached_tokenswas filled only inEncoder::finish(encode.rs:566-570at the time) and noted the docs state cumulative counts without saying which fields — the only comment on the issue. - Age and breadth: the field has been silently zero since
continuous_usage_statslanded in commit6ad1582b(Martin Vit, 2026-10-18, "Report cumulative native token usage in completion streams") — about six weeks.search_historyshows no other commit touchingcontinuous_usagesince then until this PR'sef45ca9. The gap was reported once and confirmed once; interest is narrow but explicit. - Root cause as the PR states it:
Encoder::usage_valuesums the cached count from each prompt's representative first choice (encode.rs:760-768,step_by(choices_per_prompt)), and that slot was populated only inEncoder::finishonGenerationEvent::Finished. - Line drift since the issue: the docs lines moved — cumulative promise now
docs/api.md:1039-1045, cached definitiondocs/api.md:1014-1017, Messages caveat:1030-1032;usage_valueis nowencode.rs:755-788.
Related work
- #692 (open, jcartu, same day) "helios: count output-layer stream failures under
requests_failed_total", +1068/−32, touches http.rs, runtime.rs, runtime/phase_tests.rs. Verified atpr/692:http.rs:403still reads&& let Err(error) = generation.wait_for_first_token().awaitandruntime.rs:305/359still hasfirst_token: oneshot::Receiver<Result<()>>. Direct textual conflict in the same http.rs region and the sameGenerationstruct; whichever lands second rebases. Not stacked on this PR, no cross-reference either way. - #548 (open, WynnD) "Add per-request histograms and vLLM-parity request metrics" — base of #560; at
pr/548,http.rs:411andruntime.rs:116/158/190hold the pre-#691Result<()>first_token; #548 rewrites big parts of runtime.rs and already carries thereused_prompt_tokens: Some(carried…unwrap_or(live.reused_prompt_tokens()))shape that exists in main now, so #691'sobserve_token_withclosure would also sit in #548's timing hook if both land. - #560 (open, WynnD) "Emit vLLM-compatible per-request metrics from runtime instants", stacked on #548, +2185/−163. At
pr/560,http.rs:497-504is the sameObservedTokenarm #691 extends, andencode.rs:650 finish/encode.rs:758 usage_valueare the functions #691 writes beside. Conceptually orthogonal (metrics vs cached-token reporting). flare-autobot's last review on #560 says "Ready to Merge after #548". - #689 (open, jcartu) touches the http.rs request-preparation failure path, not the streaming loop — no conflict expected.
- #674 (open, yatesdr) "improve prefix-cache hit rate…" touches runtime.rs; different subject, no conflict expected, not verified line-by-line.
- #567 (closed) "Preserve resident prefixes on ordinary completion of message requests" and #327 (open, host prefix-cache reuse accounting) surfaced only by name matching on
reused_prompt_tokens/cached_tokens; both are about cache accounting, not SSE usage emission. jcartu commented on #327 on 2026-11-20 asking for a repeat measurement. - No other open or recently merged PR changes cached-token reporting for streaming. Nothing supersedes or reverses this work; the feature's original author (Martin Vit) has not engaged.
Recent activity
- Same-day scheduler/cache churn on main by PCCessna:
cc0a49d2#681,ef38cb93#661,07e666e6#665 (prefix-cache eviction),4cc6f2fd#660 (checkpoint budget). Luke Alonso landed2acc3f3a#670 and1fbcc3c9#667 on 2026-12-01/02. yatesdr landed8489d504#663 (pricing). - Orientation packet: no commits on main since #691's base
c513e46touch its changed files, so there is no rebase drift today. - The change builds on, rather than reverses, two recent pieces:
1946d19f(yatesdr, 2026-11-19) "Count host-cache hits and reused tokens when the restore succeeds", which made the reused count trustworthy; and #416 (jcartu, merged) "Refresh host prefix-cache recency on request completion". Nothing recent conflicts semantically — conflicts with #692/#548/#560 are file/line-level only.
People
- Author: jcartu, CONTRIBUTOR, Discord jcartu. Last 180 days: 3 merged, 3 closed, 10 open. Merged work in exactly these files: #418 (strict function-tool schemas, http.rs + protocol), #416 (host prefix-cache recency on completion, runtime.rs), #505 (FP32 parameter binding). Follows cache-reuse accounting (#327 comment).
- Ten open PRs at once, three of them (#691, #692, #689) editing
helios/src/server/http.rson the same day. - Area owners: helios/src in the last 180 days — Luke Alonso (237 commits), Martin Vit (52), yatesdr (49). Martin Vit wrote
continuous_usage_stats; yatesdr confirmed #448 and owns much of the runtime scheduler/cache surface (#674, #663, #628, #459, #415, #176, #167, #333). - Who would care: shieldstar and yatesdr (#448); gateway/early-cancel streaming users (#551/#552/#560 discuss llama-swap reading usage fields).
- Engagement so far: none — no comments, no reviews, no labels, and no flare-autobot intake review yet.
Community
Nothing found: no comments, no reviews, no inline review comments, no reactions, no linked discussions, no labels (pr_comments returns "No comments").
Project fit
- Charter goals: "Support the documented Chat Completions, Completions, Responses, and Messages APIs (including token counting)" — squarely in scope. "Bug fixes need to address the root cause" — the count is filled at the point it becomes final rather than patched in the encoder at emit time. "Don't silently ignore API fields… either implement it according to the spec or reject it (#417)" —
continuous_usage_statswas accepted and only partly implemented; this completes it. - PR shape:
AGENTS.md:72-112and the charter's "PR descriptions" require why/what/result/evidence; #691 has all four with explicit headings. - Tension 1 — test-inventory padding:
AGENTS.md:132and the charter warn against "process assurances that add no technical evidence" and exhaustive inventories of changed files/tests. The description names five tests and four whole-suite counts, and ~86% of the diff is tests. Reviewers may weigh evidence-per-line. - Tension 2 — TODO.txt:
AGENTS.md:58says "Record unresolved defects, unrun checks, and pending measurements indocs/TODO.txt". The PR discloses that no GPU/exported-core live serving test ran but adds no TODO entry, anddocs/TODO.txtis not among the changed files. - Verification guidance:
AGENTS.md:490-495calls for TLA+ when protocol states or asynchronous ordering change; the author ranverification/helios-lifecycle/check.py(not opened) and argues ResponseLifecycle is unchanged because no event variant was added — consistent withPrompt::output_event_capacitybeing untouched. - Documented contract the change must satisfy:
docs/api.md:1014-1017("counts the prompt tokens actually reused at admission … zero when no prefix is reused"),docs/api.md:1039-1045(continuous_usage_stats: "Each emitted chunk carries cumulative native token counts … The final usage chunk is also emitted"),docs/api.md:1058-1061(cached usage uses the first choice's admission count per input; zero-token requests report zero),docs/api.md:1030-1032(Messagesmessage_startzero,message_deltafinal — deliberately preserved). Invariant relied on:docs/core-design.md:1532-1533"Admission reuse counts remain fixed even as the request publishes additional shared ancestors", implemented byscheduler.rs:348-350(reused_prompt_tokens()→admission_reused_tokens, set atscheduler.rs:1779). Gating:continuous_usage = decoded.stream && observation.continuous_usage && protocol ∈ {Chat, Completions}(http.rs:293-294), withinclude_usage: truerequired (observation.rs:40-52(not opened)). - Charter non-goals: no per-model branch or new flag is introduced; the change is in shared server code, so the "runtime small and model-agnostic" rule is respected.
Claims and evidence
All evidence is self-reported; no CI ran on ef45ca9 and nothing was executed during this review.
| Claim | Backing |
|---|---|
| helios suite: 1821 passed, 47 ignored, 0 failed; 62 integration passed | Not independently verifiable. The five named tests exist at protocol/tests.rs:1415, :1471 and phase_tests.rs:8449, :8756, :8869. Counts differ from #692's same command (1884/84), so they were measured on different revisions. |
| flare 246 / flare-cli 219 tests pass | Neither crate is changed by this PR, so unaffected by construction. |
verification/helios-lifecycle/check.py (not opened) all 8 models pass; ResponseLifecycle 868,192 states / 117,991 distinct / 365,508 Rust transitions |
365,508 matches #692's independently reported ResponseLifecycle conformance figure, so the two are at least mutually consistent. The description does not show the TLC jar path or mutation counts that #692's does. |
| Every Chat chunk reports the finalized count | phase_tests.rs:8646-8666 (real Worker + RequestScheduler, warms a 13-token prefix, asserts every chunk == 13) and protocol/tests.rs:1415-1466. |
| Count retained across post-token preemption/readmission | chat_continuous_usage_preserves_initial_cached_tokens_across_preemption (phase_tests.rs:8869-9074), including the case where the readmitted request's live count is 13 while the stream must keep reporting 0. |
| Multi-choice does not let siblings overwrite the first choice's count; cumulative across prompts | protocol/tests.rs:1471-1521 (4 choices / 2 prompts; sibling 9 must not overwrite 5; cumulative 8) and phase_tests.rs:8756-8866 (staggered readiness). |
| Messages unchanged | phase_tests.rs:8744, :8750 assert message_start zero and message_delta final. |
| "no GPU or exported-core live serving test was run" (disclosed) | Consistent: tests are CPU fixture-based; tests/server/test_protocols.py:196-259 (test_cached_usage_buffered_and_streaming) does not cover continuous_usage_stats at all — no match for the option anywhere under tests/. |
| "eliminating scanning once all representative first choices have started" | True structurally (pending_cached shrinks to empty), but no measurement of the per-token retain cost is offered; cost is bounded by prompt count. |
Reach
- Users: OpenAI-SDK clients with
continuous_usage_statsnow see non-zerocached_tokensmid-stream where they saw 0. Wire-visible value change, not a schema change;Encoder::finishstill overwrites with the authoritative per-choice value, so the terminal chunk is byte-identical to before. - Gateways/billing tooling that summed or diffed per-chunk usage (llama-swap-style, cf. #551/#552/#560) could double-count cached tokens if they previously summed across chunks reading 0. Cumulative semantics are what
docs/api.md:1039-1045already promises, so a correct client is unaffected. - Protocols: Chat and single-prompt
n=1Completions gain the value on all chunks; multi-choice/multi-prompt report the cumulative sum over prompts whose representative first choice has started; Anthropic Messages and Responses unchanged by construction (continuous_usage_statsgated to Chat/Completions athttp.rs:293-294; Responses builds usage fromresponse/response.completed,encode.rs:740-750,:784-786). - Operators/config: no new flags, config keys, env vars or defaults; nothing in
config.rs(not opened),cli-design.md(not opened) ortests/clichanged. Zero-config. - Dependencies/deployment: no new crates (existing
tokio::oneshot), no protobuf or core-format change, so previously exported cores are unaffected (AGENTS.md:435-448compatibility rule not engaged). - Documentation: unchanged, and it already promises the new behavior — so no drift, but no release note either.
- Performance: everything extra is gated on
continuous_usage; when off,pending_cachedis an emptyVecand only anis_emptycheck runs. The one near-unconditional change isobserve_token_with's closure, which short-circuits oncefirst_tokenis taken (runtime.rs:393).
Process
- Open, ready for review (not draft). Base
c513e46, headef45ca9, branchfix/continuous-usage-cached-tokens. Opened and last updated 2026-12-02 20:54 — effectively brand new, one day of life at review time. - CI: "no checks" on the head commit; no status has ever run.
- Reviews: none. No labels; flare-autobot has not triaged it (it does so within minutes on other PRs, e.g. #560 in ~22 minutes), so this is untriaged rather than rejected.
- Size: +868/−40, ~742 added lines of tests; production delta ~110 lines.
- Merge-order hazard (repeat from Key findings): #692, #548 and #560 all encode the old
Result<()>contract in the same files; #548 is the base of #560, so the practical order matters. #691 first means three rebases; #692 or #548 first means #691 must adapt its closure and its ObservedToken drain. - Issue closure: #448 is still open and would need closing on merge. The issue's alternative — amending
docs/api.mdto say cached is final-only — is not taken and no comment records the choice.
Open questions / not found
- Whether
flare-autobotwill accept the PR structure givenAGENTS.md:132's warning about test inventories; no precedent found on jcartu's other merged PRs. - Whether the new fallible first-token path (
observe_token_withpropagatingscheduler.request(handle)?) can actually fire in practice — no test exercises anErrfrom that closure; the tests cover onlyOkcounts and receiver-closed cases. - No measurement of the Completions
pending_cachedretaincost per token while prompts are pending; the claim of eliminating scanning is structural only. - No GPU, exported-core, or live-serving validation anywhere in the PR; no TODO.txt entry recording that.
- No reaction from the domain owners of the scheduler/cache accounting (yatesdr, Martin Vit, PCCessna — though PCCessna's authorship is on scheduler commits; the orientation packet credits Luke Alonso/Martin Vit/yatesdr as helios/src owners).
- Not found: any prior PR attempting this fix, any linked discussion thread, and any mention of
continuous_usage_statsundertests/.