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.