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

Raw Markdown for agents: https://autobot.eidonix.com/api/v1/cases/00b4d268-9c5e-4497-afff-e5ed959c74ba

Opened by a workflow run, Dec 2, 2026 4:09 PM EST. decide malicious: all_clear (100%): No malicious content found

explore

Author: jcartu (CONTRIBUTOR, Discord jcartu) Motivation: Streaming clients that ask for cumulative usage (stream_options.continuous_usage_stats) were told prompt_tokens_details.cached_tokens: 0 in every intermediate chunk even when the scheduler had reused a cached prompt prefix, because the encoder only learned the reused count when the request finished. The PR makes that count known at first-token time so every chunk carries it, as docs/api.md already promises. Scale: +868 / −40 lines in 6 files (~86% of the added lines are tests) Proposal:

Full report · Notes

Value Proposition

Value Proposition — PR #691 (helios/server: report reused prompt tokens in continuous_usage_stats chunks)

Charter alignment: strong. Supporting the documented Chat Completions/Completions APIs "including token counting" is an explicit goal, and continuous_usage_stats was accepted but only partly implemented — precisely the "don't silently ignore API fields (#417)" failure. docs/api.md:1014-1017 and :1039-1045 already promise cumulative counts, so this aligns code with the documented contract. The count is filled where it becomes final (Carried::reused_prompt_tokens, admission-fixed per docs/core-design.md:1532-1533) instead of being patched in the encoder at emit time, satisfying "bug fixes need to address the root cause." Shared server code only: no per-model branch, no new flag, no config surface — consistent with "keep the runtime small and model-agnostic."

Novelty & status: genuinely additive. #448 (shieldstar, confirmed by yatesdr at 21a40f05) is still open; no merged commit reverses it and no other open PR changes cached-token reporting in streams. #548/#560/#692 conflict at file/line level only, not semantically. Nothing here is obsolete or superseded.

Value: narrow but explicit, and wire-visible. OpenAI-SDK clients and gateway/billing tooling (cf. #551/#552/#560) currently see cached_tokens: 0 mid-stream with the true count only in the terminal chunk. Evidence is honest but CPU-only: fixture tests with a real Worker + RequestScheduler cover Chat hit/miss (phase_tests.rs:8646-8666), post-token preemption/readmission (:8869-9074), n=2 multi-choice/non-overwrite (protocol/tests.rs:1471-1521) and Messages invariance (phase_tests.rs:8744, :8750). No GPU, exported-core or live-serving validation exists, self-disclosed.

Cost and open risks. Production delta is ~110 lines, but it adds two undeclared behaviours: wait_for_first_token returning Ok(0) when the receiver was already taken (runtime.rs:159-164), and a newly fallible first-token path where observe_token_with can propagate scheduler.request(handle)? out of Worker::complete and fail_all outstanding requests (runtime.rs:2011-2016) — no test exercises that Err. AGENTS.md:58 requires a docs/TODO.txt entry for the unrun GPU check; none was added. ~742 of +868 lines are tests, which sits against AGENTS.md:132. Landing first forces rebases in #692 and #548 (hence #560). No CI, no reviews, and #448's alternative (document cached_tokens as final-only) was never acknowledged.

Verdict: Worth it with changes. Required: add the docs/TODO.txt entry for the unrun GPU/live-serving check; declare and either test or justify the Ok(0) default and the fallible first-token path; agree merge order with #692/#548; get CI green before merge. Scope, layer and root cause are right — a correct fix, not a padded feature.

Full report Decide Value: yes (100%): This change is worth reviewing: it provides value to the project in line with its charter.

Classify intake

Selected: triage:review, priority:P2, bug, area:api

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

Applied: +triage:review, +priority:P2, +bug, +area:api

Subtraction and simplicity

Simplicity lens on PR #691. The production delta (~110 lines of +868) is lean and idiomatic: routing the reused count through the existing first-token oneshot instead of adding a GenerationEvent avoids touching output_event_capacity/ResponseLifecycle, and report_cached_tokens is a 3-line setter. Everything is gated on continuous_usage, docs/api.md (not opened) already promised the behavior, and no config knobs, flags, crates, or fallbacks were added.

Five subtraction findings, highest value first:

  1. pending_cached (http.rs:404-413, :509-523, :421) is a Vec<usize> state machine that only avoids an O(prompts) rescan in an arm already gated on continuous_usage; no measurement is offered. Replace with a plain loop over (0..size).step_by(decoded.request.choices) mirroring usage_value (encode.rs:763-768).
  2. Generation::has_pending_first_token (runtime.rs:166-168) exists solely because take_reused_prompt_tokens (:170-183) conflates "pending" with "consumed" via Option<u64>; after (1) the distinction is unused.
  3. Incoming::observe_token_with (runtime.rs:388-404) — impl FnOnce() -> Result<u64> plus a fallible tail on the per-token hot path, for one caller. observe_token throws the error away (let _ =). Keep the infallible 2-arg form plus a bool guard.
  4. carried.reused_prompt_tokens.unwrap_or(<live>) now has six copies (this PR adds two: runtime.rs:1475, 2011-2016, 2099-2102, 2297, 2402-2405, 2554); one Carried::reused(&live) accessor covers all.
  5. Test weight: run_http_with_worker hand-builds CompletionRecord/FrameCompletion beside the existing completion() helper (:362-391) and adds three more inline SSE parsers; the fixture strip is duplicated 6x.

Conventions: AGENTS.md:119-121 (no test/file inventories) and AGENTS.md:57-59 (record unrun checks in docs/TODO.txt) are the two real deviations.

Open: whether the duplicated fixture strips are needed at all (http_generation_request_observed builds state from plain Fixture::new()), and whether the reviewer accepts #1's O(prompts) rescan over the pending list.

Full report · Notes

Correctness and contracts

PR #691 (helios/server: report reused prompt tokens in continuous_usage_stats chunks, head ef45ca9) is directionally correct and contract-aligned, but one Major correctness/blast-radius issue must be fixed before merge.

  1. Major — new fatal error path out of the worker. observe_token_with's closure calls self.scheduler.request(token.request)? and the caller applies ? (runtime.rs:2011-2016, :393-395). A stale/retired handle at first-token time now unwinds complete → Worker::run (:1240) → the catch_unwind block, which calls worker.fail_all (:841), failing every other concurrent request. observe_token was infallible before; the same function already tolerates the identical stale handle with let Ok(live) = … else { continue; } (:1822); and since reused_prompt_tokens() is immutable after admission (scheduler.rs:348-350, set :1779), the fallible shape buys nothing. Fix: map_or(0, |l| l.reused_prompt_tokens()), or don't apply ?. No test covers the Err arm.
  2. Minor — wait_for_first_token returns Ok(0) for a consumed receiver while a dropped sender yields a real error (runtime.rs:159-164). Undeclared silent default; unreachable today.
  3. Minor — Chat's report_cached_tokens(0, …) (http.rs:414-430) is not gated on continuous_usage, unlike the Completions drain (http.rs:509-510). Nothing leaks today (encode.rs:313-315, finish overwrites), but it is a latent trap.
  4. Minor — Completions prompt_logprobs frames are emitted during prefill (runtime.rs:1907-1912 → http.rs:495 → encode.rs:255-278) and still carry cached_tokens: 0, so the description's "every generated single-prompt n=1 Completions streaming chunk" claim does not hold; the disclosed caveat covers echo only.
  5. Process — no docs/TODO.txt entry for the disclosed absence of GPU/exported-core serving validation (AGENTS.md:58); suite counts are self-reported and no CI ran.

Sound: docs/api.md:1013-1017, 1039-1045, 1058-1061 already promise this behavior, so no docs drift; Messages/Responses untouched by construction and test; no new locks, channels or unbounded buffering (pending_cached is bounded by prompt count and shrinks to empty); terminal usage chunk byte-identical; prompt/choice index mapping consistent; first-token value provably equals the Finished value; no metric-span change.

Open: whether the new Err path can fire in practice; merge-order debt with #692/#548/#560; #448 needs closing.

Full report · Notes

Final review

Recommendation: Ready To Merge

PR #691 cleanly fixes #448 by carrying each request's finalized admission prefix-reuse count (u64) through the existing first_token oneshot channel and populating Encoder::usage[index].cached before Encoder::finish. The implementation is small (~110 production lines), preserves Prompt::output_event_capacity and ResponseLifecycle without adding a GenerationEvent variant, handles pre-token requeues, post-token preemption/readmission, reasoning-budget cuts, speculative grammar rollbacks, and multi-choice/multi-prompt Completions accurately, and adds solid Encoder and real Worker + RequestScheduler + HTTP streaming tests. Wait for CI to run on ef45ca9 before merging and coordinate merge order with open PRs touching the same regions (#692, #548, #560); no code blockers remain.

Merge Risk

Level: Low

Walkthrough

Pre-merge Checks

Blockers

None.

Should Fix

None.

Subtract / Simplify

  1. Optional: drop pending_cached and Generation::has_pending_first_token for a direct step_by scan (helios/src/server/http.rs:406-413, 421, 510-523, helios/src/server/runtime.rs:166-168). For typical prompt counts, looping for i in (0..size).step_by(decoded.request.choices) inside if continuous_usage and calling generation.take_reused_prompt_tokens() (an immediate None check once consumed) mirrors Encoder::usage_value's exact index set (encode.rs:763-768) and removes the pending_cached Vec, the Chat clear(), the retain closure, and Generation::has_pending_first_token. Keep pending_cached only if very large multi-prompt Completions batches are expected to dominate per-token CPU time.
  2. Optional: centralize the repeated carried.reused_prompt_tokens.unwrap_or(...) helper (helios/src/server/runtime.rs:1475, 2012-2014, 2099-2102, 2297, 2402-2405, 2554). With this PR, six sites in runtime.rs resolve the locked-vs-live reused prompt token count inline. A small Carried::reused_prompt_tokens(&self, live: u64) -> u64 helper (used where live is already loaded) keeps that invariant in one place.
  3. Optional: deduplicate test setup boilerplate in helios/src/server/runtime/phase_tests.rs. The two new worker tests repeat the same 9-line ImageFeatureIndex | ImageFeatureSlot graph-input strip four times (:8476-8484, :8488-8496, :8879-8887, :8891-8899) alongside three small SSE data: parsers (:8453, :8791, :9062). Extracting a Fixture::text_only() helper and reusing one SSE parser would trim ~50 lines of test boilerplate.

Nits

  1. Generation::wait_for_first_token None => Ok(0) default (helios/src/server/runtime.rs:159-164): Unreachable today because Chat streaming (http.rs:418) is the sole caller and invokes it once before the event loop, but returning Err(self.failure()) (or debug_assert! + Err) on None would prevent silently fabricating 0 cached tokens if a future caller ever invoked it twice or after take_reused_prompt_tokens.
  2. Chat gating symmetry (helios/src/server/http.rs:420): encoder.report_cached_tokens(0, reused_prompt_tokens) runs unconditionally for streaming Chat rather than under if continuous_usage (unlike Completions at :509). This is completely benign because reused_prompt_tokens is the true finalized count and usage_value() is not emitted mid-stream when continuous_usage is false (encode.rs:313-315, http.rs:537-539), though gating it on continuous_usage makes the two paths symmetric.

Dropped on verification

Full report

Classify triage

Selected: triage:review

Threshold: 65%

Triage

Apply labels

No label changes Decision to Test: no (53%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with.