Skip to content

helios/server: report reused prompt tokens in continuous_usage_stats chunks - #691

Open
jcartu wants to merge 1 commit into
NVIDIA:mainfrom
jcartu:fix/continuous-usage-cached-tokens
Open

jcartu wants to merge 1 commit into
NVIDIA:mainfrom
jcartu:fix/continuous-usage-cached-tokens

Conversation

@jcartu

@jcartu jcartu commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Fixes #448

Why

When Chat or Completions streaming is requested with "stream_options": {"include_usage": true, "continuous_usage_stats": true}, intermediate SSE chunks previously reported prompt_tokens_details.cached_tokens: 0 even when the Helios scheduler reused a cached prefix, while only the terminal and final usage chunks reported the reused token count. Clients cancelling a stream early or inspecting per-chunk cumulative usage observed inconsistent cache counts relative to the documented cumulative usage behavior in docs/api.md.

Encoder::usage_value reads each prompt's cached count from its representative first choice (Encoder::usage.iter().step_by(choices_per_prompt)), which was previously populated only in Encoder::finish upon receiving GenerationEvent::Finished. A request's reused prompt token count is already finalized by the time the worker observes its first generated token: pre-token requeue transitions (failed host-restore fallback in Worker::service_store and late pool-lookup upgrades in Worker::retry_late_pool_answers) occur only before any token is generated, and any later preemption, reasoning-budget cut, or speculative grammar transition locks the initial count into Carried::reused_prompt_tokens.

What changed

  • helios/src/server/runtime.rs: Changed the per-request first_token oneshot channel on Incoming and Generation from Result<()> to Result<u64>, carrying carried.reused_prompt_tokens.unwrap_or(live.reused_prompt_tokens()) when the worker observes the first generated token (including forced close tokens in Active::close_reasoning). Added Incoming::observe_token_with so Worker::complete evaluates the scheduler lookup lazily only while first_token is still pending, avoiding per-token scheduler lookups on subsequent tokens. Stored Generation::first_token as Option<oneshot::Receiver<Result<u64>>> and added Generation::has_pending_first_token and Generation::take_reused_prompt_tokens for single consumption. No GenerationEvent variant was added, leaving Prompt::output_event_capacity and ResponseLifecycle unchanged.
  • helios/src/server/protocol/encode.rs: Added Encoder::report_cached_tokens(index, cached) to populate self.usage[index].cached before Encoder::finish.
  • helios/src/server/http.rs: Recorded the reused prompt token count returned by Generation::wait_for_first_token before encoder.start() emits the initial Chat assistant chunk. For Completions with continuous_usage_stats, tracked only pending representative first choices ((0..size).step_by(decoded.request.choices)) and drained ready first_token counts on GenerationEvent::ObservedToken, eliminating scanning once all representative first choices have started. Anthropic Messages (message_start reports zero cache reads; message_delta reports final counts) and Responses streaming behavior are unchanged.
  • helios/src/server/protocol/tests.rs & helios/src/server/runtime/phase_tests.rs: Added Encoder unit tests covering Chat, Completions, zero prefix reuse, and multi-prompt n=2 streams, plus HTTP + Worker + RequestScheduler streaming tests covering Chat prefix reuse hit and miss, post-token preemption/readmission, Completions n=2 prefix reuse, staggered multi-prompt n=2 first-choice readiness, and Messages message_start/message_delta behavior.

Claimed result

With stream_options.include_usage and stream_options.continuous_usage_stats enabled:

  • Every Chat streaming chunk (from the initial assistant role chunk through intermediate content/observed chunks to the final usage chunk) and every generated single-prompt, n=1 Completions streaming chunk reports the finalized prompt_tokens_details.cached_tokens count matching the final usage chunk (0 when no prefix is reused), and retains that initial count across post-token preemption and readmission.
  • Multi-choice (n > 1) and multi-prompt Completions streams report the cumulative reused prompt tokens across prompts whose representative first choice (prompt_index * n) has reached its first generated token, without letting sibling choices overwrite a prompt's admission count, and match the final usage chunk once all representative first choices have started.
  • Completions streams with echo: true emit echo frames before worker admission, so echo frames precede first-token readiness and continue to report 0 cached tokens.

Evidence

Executed on Linux CPU without GPUs (no GPU or exported-core live serving test was run):

  • cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server: 1821 unit tests passed (47 ignored), 62 integration tests passed (36 ignored), 0 failed. Ignored tests require local CUDA GPU hardware, exported cores, or external model checkpoint/tokenizer snapshots. Covers continuous_usage_reports_cached_tokens_before_finish, continuous_usage_multi_choice_reports_first_choice_cached_tokens_per_prompt, continuous_usage_streams_report_reused_prompt_tokens_and_preserve_messages, completions_continuous_usage_tracks_staggered_first_choice_readiness, and chat_continuous_usage_preserves_initial_cached_tokens_across_preemption.
  • cargo test --locked --release --manifest-path flare/Cargo.toml: 246 unit tests passed (4 ignored: 3 requiring FLARE_LEGACY_FIXTURE, 1 helper child process spawned by the interrupted-acquisition test), 8 integration tests passed, 0 failed.
  • cargo test --locked --release --manifest-path flare-cli/Cargo.toml: 219 unit tests passed (3 ignored: FLARE_LEGACY_FIXTURE and explicit multi-host hardware/distribution fixtures), 26 integration tests passed, 0 failed.
  • python3 verification/helios-lifecycle/check.py: all 8 TLA+ models and Rust observed-transition conformance checks passed, including ResponseLifecycle.tla (868,192 states generated, 117,991 distinct states, 365,508 checked Rust transitions) and all 12 targeted lifecycle regression tests.

Discord: jcartu

@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 691.
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 flare-autobot added area:api Serving API, protocol encoding, tool parsing, and client-visible behavior. bug Something isn't working priority:P2 Normal bug priority: workflow failure or diagnosis with narrower impact or an available workaround. triage:review Proposed change needs code review; this does not imply merge readiness. labels Dec 2, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Ready To Merge

PR #691 cleanly fixes #448 by carrying each request's finalized admission prefix-reuse count through the existing first_token oneshot channel and populating Encoder::usage[index].cached before Encoder::finish, with no code blockers remaining. Wait for CI on ef45ca9 and coordinate merge order with #692, #548, and #560.

  • Blockers: 0 · Should fix: 0 · Subtract/Simplify: 3 · Nits: 2
Walkthrough
  • helios/src/server/runtime.rs (+69/−24): Changed first_token oneshot payload on Incoming (:211) and Generation (:117) from Result<()> to Result<u64>, carrying carried.reused_prompt_tokens.unwrap_or(live.reused_prompt_tokens()) on first observed token (:2011-2016) and forced reasoning-close tokens (Active::close_reasoning, :531-549, :2296-2303). Added Incoming::observe_token_with (:388-404) for lazy first-token evaluation, Generation::has_pending_first_token (:166-168), and Generation::take_reused_prompt_tokens (:170-183).
  • helios/src/server/protocol/encode.rs (+5/−0): Added Encoder::report_cached_tokens(index, cached) (:288-292) to record per-choice cached prompt tokens ahead of Encoder::finish (:703-707), matching Encoder::usage_value's representative-choice sum (:763-768).
  • helios/src/server/http.rs (+36/−6): Recorded the reused count returned by Generation::wait_for_first_token for streaming Chat before encoder.start() (:414-430). For streaming Completions with continuous_usage_stats, seeded pending_cached with representative first choices (0..size).step_by(decoded.request.choices) (:406-413) and drained ready first-token counts on GenerationEvent::ObservedToken (:509-526).
  • helios/src/server/protocol/tests.rs (+108/−0), helios/src/server/runtime/phase_tests.rs (+649/−9), helios/src/server/runtime/response_lifecycle_tests.rs (+1/−1): Added Encoder tests for Chat/Completions single and multi-choice/multi-prompt streams (protocol/tests.rs:1415-1520), end-to-end HTTP + Worker + RequestScheduler tests covering prefix hit/miss, n=2, Messages invariance, staggered multi-prompt readiness, and post-token preemption/readmission (phase_tests.rs:8449-9076), and updated existing first_token/observe_token call sites (phase_tests.rs:1718-1740, response_lifecycle_tests.rs:370).
Merge Risk: Low · up to ef45ca9
  • Production changes are confined to shared server streaming/usage plumbing (helios/src/server/runtime.rs, http.rs, protocol/encode.rs) with no new locks, channels, event variants, config flags, dependencies, or GPU/core-format changes.
  • Hot-path impact is negligible: when continuous_usage_stats is off, pending_cached is an unallocated empty Vec and ObservedToken does not run (unless return_token_ids is enabled); on the worker path, Incoming::observe_token_with evaluates the scheduler lookup only once while first_token is still Some (runtime.rs:393-395).
  • Wire-visible change is limited to intermediate SSE chunks under stream_options: {"include_usage": true, "continuous_usage_stats": true} for Chat and Completions, bringing them into alignment with docs/api.md:1014-1017, 1039-1045, 1058-1061; terminal/final usage chunks, Anthropic Messages, and Responses streams are unchanged.
Pre-merge checks: ✅ 2 passed · ⚠️ 2 warnings

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

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

@lukealonso

Copy link
Copy Markdown
Collaborator

Need a rebase

@jcartu
jcartu force-pushed the fix/continuous-usage-cached-tokens branch from ef45ca9 to d99fa77 Compare December 3, 2026 10:06
@jcartu

jcartu commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main (3d1614cc), resolving the helios/src/server/http.rs conflict with #689. Local cargo test (2,408 passed across flare-helios, flare, and flare-cli, 0 failed) and touched-file clippy (zero new warnings) are green on d99fa77f. Note: overlaps #692 in the chat first-token block; I will rebase whichever lands second immediately. @lukealonso

@jcartu

jcartu commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Rebased onto main (452c3686) at 111e27c5, resolving the append-only test conflict at the end of helios/src/server/runtime/phase_tests.rs (re-anchored below worker_admit_isolates_admission_and_stop_matcher_failures_without_killing_worker) with zero code/test diff drift. Local --locked cargo test passed (full suite on def91796: 1,940 flare-helios + 255 flare + 246 flare-cli; phase_tests on 452c3686: 147 passed, 0 failed).

Still overlaps #692/#705 at the http.rs / phase_tests.rs tails; will re-rebase in merge order.

Discord: jcartu

…chunks

With stream_options.include_usage and stream_options.continuous_usage_stats
enabled, intermediate Chat and Completions SSE chunks previously reported
prompt_tokens_details.cached_tokens as 0 even when the scheduler reused a
cached prefix, while only the terminal and final usage chunks reported the
reused token count. Encoder::usage_value read each choice's cached count
from Encoder::usage, which was only populated inside Encoder::finish when
GenerationEvent::Finished arrived. A request's reused prompt token count is
already finalized when its first generated token is observed: pre-token
requeue paths (failed host-restore fallback and late pool-lookup upgrades)
occur only before the first generated token, and subsequent preemption,
reasoning-budget cuts, or speculative grammar transitions lock the initial
count into Carried::reused_prompt_tokens.

Carry the finalized reused prompt token count across the existing per-request
first_token oneshot channel in helios/src/server/runtime.rs instead of
waiting until GenerationEvent::Finished, computing
carried.reused_prompt_tokens.unwrap_or(live.reused_prompt_tokens()) lazily
via Incoming::observe_token_with only while first_token is still pending so
later tokens incur no scheduler lookup. Add Generation::has_pending_first_token,
Generation::take_reused_prompt_tokens, and Encoder::report_cached_tokens
(helios/src/server/protocol/encode.rs). In helios/src/server/http.rs, record
the count returned by Generation::wait_for_first_token before emitting the
initial Chat assistant delta chunk, and track only pending representative
first choices (`step_by(choices)`) to drain ready counts on
GenerationEvent::ObservedToken for Completions while continuous_usage_stats
is active. Anthropic Messages and Responses streaming paths remain unchanged:
Messages still reports zero cache reads on message_start and the final counts
on message_delta. No new GenerationEvent variant is introduced, preserving
Prompt::output_event_capacity and ResponseLifecycle invariants.

With stream_options.include_usage and stream_options.continuous_usage_stats
enabled:
- Every Chat streaming chunk (initial assistant delta through intermediate
  content/observed chunks to final usage) and every generated single-prompt,
  n=1 Completions chunk reports the finalized
  prompt_tokens_details.cached_tokens count matching the final usage chunk
  (and 0 when no prefix is reused), preserved across preemption/readmission.
- Multi-choice (n > 1) and multi-prompt Completions streams report the
  cumulative reused prompt tokens across prompts whose representative first
  choice has reached its first token, matching the final usage chunk once all
  representative first choices have started; Completions echo frames emitted
  before worker admission continue to report 0 cached tokens.

Verified with CPU crate tests and TLA+ lifecycle conformance on Linux (no GPU
or exported-core live serving run was performed):
- cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server: 1821 unit passed (47 ignored), 62 integration passed (36 ignored), 0 failed; ignored tests require GPU hardware, exported cores, or external model checkpoint/tokenizer snapshots. Includes Encoder unit tests (Chat, Completions, zero reuse, multi-prompt n=2) and HTTP + Worker + RequestScheduler tests covering Chat prefix hit and miss, post-token preemption/readmission, Completions n=2 prefix hit, staggered multi-prompt n=2 readiness, and Messages message_start/message_delta preservation.
- cargo test --locked --release --manifest-path flare/Cargo.toml: 246 unit passed (4 ignored: 3 requiring FLARE_LEGACY_FIXTURE, 1 child helper spawned by the interrupted-acquisition test), 8 integration passed, 0 failed.
- cargo test --locked --release --manifest-path flare-cli/Cargo.toml: 219 unit passed (3 ignored: FLARE_LEGACY_FIXTURE and explicit multi-host hardware/distribution fixtures), 26 integration passed, 0 failed.
- python3 verification/helios-lifecycle/check.py: all 8 TLA+ models and observed-transition conformance checks passed, including ResponseLifecycle.tla (868,192 states generated, 117,991 distinct states, 365,508 checked Rust transitions) and all 12 targeted lifecycle regression tests.

Signed-off-by: Joshua Cartu <jcartu@users.noreply.github.com>
Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b
@jcartu
jcartu force-pushed the fix/continuous-usage-cached-tokens branch from 00cbbdd to 111e27c Compare December 3, 2026 18:58
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. bug Something isn't working priority:P2 Normal bug priority: workflow failure or diagnosis with narrower impact or an available workaround. 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.

continuous_usage_stats intermediate Chat chunks report cached_tokens: 0 although the docs promise cumulative counts

3 participants