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:
Incoming/Generationfirst_tokenoneshot channel now carriesResult<u64>(the finalized reused prompt token count) instead ofResult<()>, set when the worker emits the first generated token.- New
Incoming::observe_token_withevaluates the scheduler lookup lazily only whilefirst_tokenis still pending, so later tokens pay nothing. - New
Encoder::report_cached_tokens(index, cached)writes the per-choice cached count beforeEncoder::finish. http.rsrecords the count before the Chat initial chunk; for Completions it drains ready counts only for representative first choices (0..size step_by(n)) onObservedToken.- Messages (
message_startzero,message_deltafinal) and Responses streaming deliberately unchanged; no newGenerationEventvariant. Touches: helios/src/server/runtime.rs(+69/−24): first-token signalling, new fallible path out ofWorker::complete.helios/src/server/http.rs(+36/−6): streaming loop,pending_cachedscan.helios/src/server/protocol/encode.rs(+5/−0): cached-token write. Related items:- #448
continuous_usage_statsintermediate Chat chunks reportcached_tokens: 0(open): the bug this fixes. - #692 helios: count output-layer stream failures under
requests_failed_total(open): same author, same day, same http.rs/runtime.rs (not opened)first_tokencode — merge-order conflict. - #548 Add per-request histograms and vLLM-parity request metrics (open): rewrites runtime.rs around the same
first_tokenplumbing. - #560 Emit vLLM-compatible per-request metrics from runtime instants (open): same
ObservedTokenarm andEncoder::finishwiring. - #674 improve prefix-cache hit rate (open): same file, different subject.
Link: https://github.com/NVIDIA/hyperflare-inference/pull/691
Autobot comments: No CI, no reviews, no comments; description is unusually complete but five things are undeclared:
wait_for_first_tokennow returnsOk(0)if the receiver was taken;observe_token_withis fallible and a stale scheduler handle can now propagate out ofWorker::complete(whose run loop thenfail_alls); nodocs/TODO.txtentry for the untested GPU/live path as AGENTS.md requires; docs untouched, so the natural alternative resolution offered in #448 (amend docs) was rejected silently; test-suite counts in the description differ from the same author's same-day #692, so the numbers were measured on different revisions. It also drops the second of #448's two options and creates a rebase debt for three open PRs.
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
- [✓]
triage:review: 99.9% -
triage:design-review: 0.0% -
triage:validation: 0.0% -
none: 0.0% -
triage:integration: 0.0% -
triage:partial: 0.0% -
triage:investigate: 0.0% -
triage:verify-for-closure: 0.0% -
triage:superseded: 0.0%
Priority
- [✓]
priority:P2: 94.1% -
none: 3.7% -
priority:P1: 2.2%
Type
- [✓]
bug: 96.3% -
enhancement: 43.8% -
community: 18.2% -
performance: 16.5% -
duplicate: 11.9% -
documentation: 0.0%
Area
- [✓]
area:api: 95.8% -
area:caching: 37.8% -
area:scheduling: 11.9% -
area:preparation: 1.8% -
area:selene: 0.6% -
area:engram: 0.5% -
area:memory: 0.4% -
area:rocenante: 0.2% -
area:kernels: 0.1% -
area:orbit: 0.1% -
area:packaging: 0.0%
Model
-
model:deepseek-v4: 0.4% -
model:inkling-small: 0.2% -
model:kimi-k3.1: 0.2% -
model:deepseek-v4.1: 0.1% -
model:muse-glimmer: 0.1% -
model:nemotron-3.5-bolt: 0.1% -
model:glm-5.3: 0.1% -
model:qwen3.8-flash-next: 0.0% -
model:mimo-v2.6: 0.0% -
model:qwen3.8-27b: 0.0% -
model:gemma4: 0.0%
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:
pending_cached(http.rs:404-413,:509-523,:421) is aVec<usize>state machine that only avoids an O(prompts) rescan in an arm already gated oncontinuous_usage; no measurement is offered. Replace with a plain loop over(0..size).step_by(decoded.request.choices)mirroringusage_value(encode.rs:763-768).Generation::has_pending_first_token(runtime.rs:166-168) exists solely becausetake_reused_prompt_tokens(:170-183) conflates "pending" with "consumed" viaOption<u64>; after (1) the distinction is unused.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_tokenthrows the error away (let _ =). Keep the infallible 2-arg form plus a bool guard.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); oneCarried::reused(&live)accessor covers all.- Test weight:
run_http_with_workerhand-buildsCompletionRecord/FrameCompletionbeside the existingcompletion()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.
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.
- Major — new fatal error path out of the worker.
observe_token_with's closure callsself.scheduler.request(token.request)?and the caller applies?(runtime.rs:2011-2016, :393-395). A stale/retired handle at first-token time now unwindscomplete→Worker::run(:1240) → the catch_unwind block, which callsworker.fail_all(:841), failing every other concurrent request.observe_tokenwas infallible before; the same function already tolerates the identical stale handle withlet Ok(live) = … else { continue; }(:1822); and sincereused_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 theErrarm. - Minor —
wait_for_first_tokenreturnsOk(0)for a consumed receiver while a dropped sender yields a real error (runtime.rs:159-164). Undeclared silent default; unreachable today. - Minor — Chat's
report_cached_tokens(0, …)(http.rs:414-430) is not gated oncontinuous_usage, unlike the Completions drain (http.rs:509-510). Nothing leaks today (encode.rs:313-315,finishoverwrites), but it is a latent trap. - Minor — Completions
prompt_logprobsframes are emitted during prefill (runtime.rs:1907-1912 → http.rs:495 → encode.rs:255-278) and still carrycached_tokens: 0, so the description's "every generated single-prompt n=1 Completions streaming chunk" claim does not hold; the disclosed caveat coversechoonly. - 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.
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
- 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_statsis off,pending_cachedis an unallocated emptyVecandObservedTokendoes not run (unlessreturn_token_idsis enabled); on the worker path,Incoming::observe_token_withevaluates the scheduler lookup only once whilefirst_tokenis stillSome(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 withdocs/api.md:1014-1017, 1039-1045, 1058-1061; terminal/final usage chunks, Anthropic Messages, and Responses streams are unchanged.
Walkthrough
helios/src/server/runtime.rs(+69/−24): Changedfirst_tokenoneshot payload onIncoming(:211) andGeneration(:117) fromResult<()>toResult<u64>, carryingcarried.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). AddedIncoming::observe_token_with(:388-404) for lazy first-token evaluation,Generation::has_pending_first_token(:166-168), andGeneration::take_reused_prompt_tokens(:170-183).helios/src/server/protocol/encode.rs(+5/−0): AddedEncoder::report_cached_tokens(index, cached)(:288-292) to record per-choice cached prompt tokens ahead ofEncoder::finish(:703-707), matchingEncoder::usage_value's representative-choice sum (:763-768).helios/src/server/http.rs(+36/−6): Recorded the reused count returned byGeneration::wait_for_first_tokenfor streaming Chat beforeencoder.start()(:414-430). For streaming Completions withcontinuous_usage_stats, seededpending_cachedwith representative first choices(0..size).step_by(decoded.request.choices)(:406-413) and drained ready first-token counts onGenerationEvent::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): AddedEncodertests for Chat/Completions single and multi-choice/multi-prompt streams (protocol/tests.rs:1415-1520), end-to-end HTTP +Worker+RequestSchedulertests covering prefix hit/miss,n=2, Messages invariance, staggered multi-prompt readiness, and post-token preemption/readmission (phase_tests.rs:8449-9076), and updated existingfirst_token/observe_tokencall sites (phase_tests.rs:1718-1740,response_lifecycle_tests.rs:370).
Pre-merge Checks
- [PASS] Security / malicious screen: No unsafe code, untrusted parsing changes, external dependencies, or prompt-injection/instruction anomalies found in the diff or comments.
- [PASS] Charter & value fit: Directly resolves open bug #448 and aligns
continuous_usage_statswire output withdocs/api.md:1013-1061in shared, model-agnostic server code with zero new flags or surface area. - [WARN] Related / duplicate / conflict check: No duplicate PR or drift against
main, but open PRs #692, #548, and #560 touch the samefirst_tokenandObservedTokenregions inruntime.rsandhttp.rsand will require rebasing depending on merge order. - [WARN] Tests & verification evidence: New tests are well-isolated (no shared mutable global state) and exercise real
http::generate,Encoder,Worker, andRequestSchedulerpaths, and the author reports passing--releaseCPU test suites (helios,flare,flare-cli) plusverification/helios-lifecycle/check.py(not opened) (with no GPU run disclosed); however, GitHub CI checks have not yet run onef45ca9and should pass before merge.
Blockers
None.
Should Fix
None.
Subtract / Simplify
- Optional: drop
pending_cachedandGeneration::has_pending_first_tokenfor a directstep_byscan (helios/src/server/http.rs:406-413, 421, 510-523,helios/src/server/runtime.rs:166-168). For typical prompt counts, loopingfor i in (0..size).step_by(decoded.request.choices)insideif continuous_usageand callinggeneration.take_reused_prompt_tokens()(an immediateNonecheck once consumed) mirrorsEncoder::usage_value's exact index set (encode.rs:763-768) and removes thepending_cachedVec, the Chatclear(), theretainclosure, andGeneration::has_pending_first_token. Keeppending_cachedonly if very large multi-prompt Completions batches are expected to dominate per-token CPU time. - 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 inruntime.rsresolve the locked-vs-live reused prompt token count inline. A smallCarried::reused_prompt_tokens(&self, live: u64) -> u64helper (used whereliveis already loaded) keeps that invariant in one place. - Optional: deduplicate test setup boilerplate in
helios/src/server/runtime/phase_tests.rs. The two new worker tests repeat the same 9-lineImageFeatureIndex | ImageFeatureSlotgraph-input strip four times (:8476-8484,:8488-8496,:8879-8887,:8891-8899) alongside three small SSEdata:parsers (:8453,:8791,:9062). Extracting aFixture::text_only()helper and reusing one SSE parser would trim ~50 lines of test boilerplate.
Nits
Generation::wait_for_first_tokenNone => 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 returningErr(self.failure())(ordebug_assert!+Err) onNonewould prevent silently fabricating0cached tokens if a future caller ever invoked it twice or aftertake_reused_prompt_tokens.- Chat gating symmetry (
helios/src/server/http.rs:420):encoder.report_cached_tokens(0, reused_prompt_tokens)runs unconditionally for streaming Chat rather than underif continuous_usage(unlike Completions at:509). This is completely benign becausereused_prompt_tokensis the true finalized count andusage_value()is not emitted mid-stream whencontinuous_usageis false (encode.rs:313-315,http.rs:537-539), though gating it oncontinuous_usagemakes the two paths symmetric.
Dropped on verification
- Correctness lens F1 ("Major: fallible
observe_token_withcan fail the whole worker on a stale/retired handle atruntime.rs:2014"): Verified false.runtime.rs:1822tolerates stale handles only because it iteratesstep.lanesfrom submission time before completion.RequestScheduler::complete_with_survivalskips stale/retired lanes atscheduler.rs:2736, 2754and never pushes them togenerated; insideWorker::complete'sfor token in generatedloop (runtime.rs:1931-2205), nothing retires or mutatesscheduler.slotsuntil:2206(self.retire) and:2208(self.park_grammar_transition), and the exact same loop already callsself.scheduler.request(token.request)?unconditionally at four existing sites (:1986,:2088,:2118,:2183). - Correctness lens F4 ("Minor: Completions
prompt_logprobsframes reportcached_tokens: 0, falsifying the PR's claim"): Verified false.ScoredPrefill(spec.prompt_logprobs == true) bypasses both GPU prefix-cache lookup (scheduler.rs:1545-1547) and host prefix-store lookup (runtime.rs:1561), so its finalizedreused_prompt_tokens()is always0. Reporting0onPromptLogprobschunks matches the true final count. - Subtraction lens #3 ("Collapse
observe_token_withinto infallibleobserve_token+fn first_token_pending(&self) -> bool { self.first_token.is_some() }"): Dropped because the suggested replacement does not compile:Incoming::first_tokenisstd::cell::Cell<Option<oneshot::Sender<Result<u64>>>>(runtime.rs:211), andCell<Option<NonCopy>>has no.is_some()or.get()method. Usingobserve_token_with(&self, ..., impl FnOnce() -> Result<u64>)withself.first_token.take()is idiomatic zero-cost interior mutability for&selfcallers. - Subtraction lens #5 sub-claim ("
Fixture::new()already strips image inputs at:59-67andrun_http_with_workerduplicatescompletion()"): Partially false. Lines59-67ofphase_tests.rsare insideFixture::reasoning(), notFixture::new()(:30-32), andcompletion()(:362-391) applies oneOption<u32>across all lanes whereasrun_http_with_worker(:8586-8617) tracks per-slot generation counts for multi-choicen=2steps. Retained only the verifiedFixture::text_only()and SSE-parser deduplication part above. - Process claim ("Missing
docs/TODO.txtentry for unrun GPU test /AGENTS.md:119-121test-inventory complaint"): Dropped as low-signal.AGENTS.md:57-59contrastsdocs/TODO.txtagainst writing follow-ups in design documents, and this change is pure CPU Rust server/SSE usage accounting with no GPU-specific execution path; the PR description follows the four-part order andDiscord:line required byAGENTS.md:72-145and honestly discloses that tests ran on CPU without GPUs.
Classify triage
Selected: triage:review
Threshold: 65%
Triage
- [✓]
triage:review: 99.4% -
triage:validation: 0.2% -
none: 0.2% -
triage:design-review: 0.1% -
triage:integration: 0.0% -
triage:investigate: 0.0% -
triage:partial: 0.0% -
triage:verify-for-closure: 0.0% -
triage:superseded: 0.0%
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.