Correctness, Contracts & System-Level Consequences review — PR #691
helios/server: report reused prompt tokens in continuous_usage_stats chunks · head ef45ca9, base c513e46 · 6 files, +868/−40 (~742 added lines are tests; production delta ~110 lines) · fixes #448 · no CI checks, no reviews, no labels at review time.
Key findings
- Major — the change introduces a new fatal error path out of
Worker::complete.Incoming::observe_token_with's closure callsself.scheduler.request(token.request)?and the caller applies?(runtime.rs:2011-2016). A stale/retired handle at first-token time now unwindscomplete→Worker::run(:1240) → thecatch_unwindblock, which callsworker.fail_all(&final_error)(:841) and tears down the model runtime — failing every other concurrent request on that worker for a per-request accounting lookup.observe_tokenwas infallible before this PR, the description only claims to avoid "per-token scheduler lookups", and the same function already tolerates the identical stale handle 190 lines earlier (:1822). Becausereused_prompt_tokens()is immutable after admission (scheduler.rs:348-350, set once at:1779), the fallible shape buys no correctness. - Minor — new silent default:
wait_for_first_tokenreturnsOk(0)("no prefix reused") when the receiver is absent, while a dropped sender yields a real error (runtime.rs:159-164). Unreachable today; undeclared in the description. - Minor — asymmetric gating: the Chat
report_cached_tokens(0, …)call (http.rs:414-430) is not behindcontinuous_usage, unlike the Completions drain (http.rs:509-510). I traced everyusage_value()emission and nothing leaks onto the wire without the flag, so this is a latent trap, not a defect. - Minor — one claim in the description is too strong: Completions
prompt_logprobsframes are emitted during scored prefill (runtime.rs:1907-1912→http.rs:495→encode.rs:255-278) and still carrycached_tokens: 0throughchunk'susage_value()(encode.rs:313-315), so "every generated single-prompt, n=1 Completions streaming chunk reports the finalized … count" does not hold. The disclosed caveat coversechoframes only. - Process: no
docs/TODO.txtentry for the disclosed absence of any GPU/exported-core live-serving validation (AGENTS.md:58 requires recording unrun checks), and no test exercises the newErrarm.
System-level, contract and hot-path consequences are otherwise clean: no new locks, no channel-shape change, no unbounded buffering, terminal usage chunk byte-identical, Messages/Responses untouched, and the documented contract already promises the new behavior.
1. Correctness, safety & platform parity
F1 — Major: fallible first-token lookup can fail the whole worker (blast radius)
helios/src/server/runtime.rs:2011-2016:
request.incoming.observe_token_with(token.token, || {
Ok(match request.carried.reused_prompt_tokens {
Some(reused) => reused,
None => self.scheduler.request(token.request)?.reused_prompt_tokens(),
})
})?;
helios/src/server/runtime.rs:393-395 — the ? inside the sender path:
if let Some(sender) = self.first_token.take() {
let _ = sender.send(Ok(reused_prompt_tokens()?));
}
helios/src/server/runtime.rs:1238-1241 (only caller of complete):
if let Some(completion) = executor.poll()? {
let kind = executor.manifest().graphs[completion.graph_index].kind;
self.complete(kind, completion)?;
helios/src/server/runtime.rs:830-841 (what an Err from run does):
let error = match run {
Ok(Ok(())) => None,
Ok(Err(error)) => Some(error),
Err(_) => Some(error… "native model worker panicked")
};
…
worker.fail_all(&final_error);
Contrast, same function, helios/src/server/runtime.rs:1822:
let Ok(live) = self.scheduler.request(lane.request) else {
continue;
};
helios/src/scheduler.rs:1236-1242 shows the error source: .filter(|request| request.handle == handle).ok_or_else(|| "stale or retired request handle".into()).
Impact: a pre-existing, benign condition (a slot retired between submission and completion bookkeeping) is now escalated from "skip this lane" to "abort the worker and fail all in-flight requests". Under concurrent load — many requests, preemption/retirement, late cancel/license-eviction churn — this converts a single request's bookkeeping race into a server-wide failure burst: every peer request gets Error::execution(ExecutionError::Worker …), the runtime shuts down, and the prefix cache/store path is closed. Before this PR observe_token was infallible (fn observe_token(&self, token: u32)), so no comparable escalation existed. The description mentions only "avoiding per-token scheduler lookups" and says nothing about a new failure mode.
Fix: one of
- remove the failure:
None => self.scheduler.request(token.request).map_or(0, |live| live.reused_prompt_tokens()), - or keep the closure fallible but neutralize it in
observe_token_with(the send result is already discarded): sendErr(generation.failure())at worst, and haveWorker::completenot apply?— a per-request accounting miss should fail that request's stream, not the worker.
Add a regression test that a stale handle during first-token observation fails one request rather than the worker; today every test call site uses the infallible observe_token(tok, 0) (phase_tests.rs:4569, 5027, 5034, 5259, 5523, 8803-8824, response_lifecycle_tests.rs:370), so the Err arm has zero coverage.
F2 — Minor: Ok(0) for a consumed receiver is a new silent default
helios/src/server/runtime.rs:159-164:
pub(super) async fn wait_for_first_token(&mut self) -> Result<u64> {
match self.first_token.take() {
Some(receiver) => receiver.await.unwrap_or_else(|_| Err(self.failure())),
None => Ok(0),
}
}
The Some arm maps a dropped sender to a genuine error via self.failure(); the None arm — reachable only if the receiver was already consumed (including by take_reused_prompt_tokens at :170-183) or Generation was built without one — reports a clean "zero cached tokens". Not reachable in this diff: the Chat branch (http.rs:414) is the sole wait_for_first_token caller, runs once, and Completions never calls it. It is however an undeclared semantic default that would silently produce a wrong wire value if call order ever changes.
Fix: None => Err(self.failure()), or debug_assert!(false) plus the same error.
F3 — Minor: Chat's cached-token report is not gated on continuous_usage
helios/src/server/http.rs:414-430:
if streaming && protocol == Protocol::Chat {
…
if let Some(generation) = generations[0].as_mut() {
match generation.wait_for_first_token().await {
Ok(reused_prompt_tokens) => {
encoder.report_cached_tokens(0, reused_prompt_tokens);
pending_cached.clear();
versus the Completions path, helios/src/server/http.rs:509-510: if continuous_usage { if !pending_cached.is_empty() { … } }.
Impact: no observable behavior change today. I traced each emission of Encoder::usage_value(): mid-stream chunks only carry usage when self.include_usage && self.continuous_usage (encode.rs:313-315), Chat observed chunks assign usage only if continuous_usage (http.rs:537-539), and Encoder::finish overwrites usage[index] with the authoritative per-choice count before the finish_reason/final usage frame. So Chat now depends on finish always running to keep this pre-finish value off the wire — a latent invariant that the Completions side does not share.
Fix: wrap report_cached_tokens in if continuous_usage { … } (keeping the await and the Err → failure-frame handling unconditional), mirroring http.rs:509-510.
Message-count / protocol fan-out: sound
continuous_usage = decoded.stream && decoded.observation.continuous_usage && matches!(protocol, Chat | Completions) (http.rs:293-294 restricts to Chat/Completions); Anthropic Messages and Responses streaming are untouched by construction, and the tests assert it (phase_tests.rs Messages test asserting message_start zero and message_delta 13). No platform-specific code, no cfg(windows) surface, no panic paths added (report_cached_tokens is a plain field write, encode.rs:290-292).
2. Unintended system-level consequences
No contention, memory or failure-propagation issue beyond F1. Concretely verified:
- No new locks or channels. The one new synchronization object is the already-present
tokio::oneshot(runtime.rs:211,:1027), only its payload type changed (Result<()>→Result<u64>). - No unbounded buffering.
pending_cached(http.rs:406-413) is seeded from(0..size).step_by(decoded.request.choices)filtered to live generations, i.e. bounded by prompt count, and shrinks monotonically:retainreturnsfalseon a drained count and only keeps entries whosefirst_tokenis still pending (http.rs:511-521). Once empty, the per-token cost is a singleis_empty()check (http.rs:510).Encoder::report_cached_tokensis O(1). - Hot path when the flag is off:
pending_cachedis an emptyVec, so theObservedTokenarm does onlyis_empty();observe_token_withshort-circuits oncefirst_tokenis taken (:393). No regression on the uncontended/no-flag path. - Terminal chunk unchanged:
Encoder::finishstill writes the authoritative per-choice count, so the final usage frame is byte-identical to pre-PR; the change only alters intermediate frames (which is the point). - No memory amplification, no extra copies of prompt data, no disk/cache I/O interaction. The prefix-cache admission accounting (
scheduler.rs:348-350,:1779) is read-only here. - Failure propagation: the one exception is F1, which is precisely a case where a per-request defect is promoted to a worker-wide failure.
- Metric/rate/admission-pricing span check: not engaged. The PR does not change what any rate, latency or admission metric samples (
observation.finishinputs unchanged); it only fills a usage field earlier.
3. Architecture, contracts & charter compliance
- The documented contract already promised this.
docs/api.md:1013-1017("This counts the prompt tokens actually reused at admission, including restored prefixes; it is zero when no prefix is reused"),:1039-1045("Each emitted chunk carries cumulative native token counts … The final usage chunk is also emitted"),:1058-1061(cached uses the first choice's admission count per input; zero-token requests report zero). The PR makes the wire match the docs; no docs drift, anddocs/api.mdis correctly not among the changed files. The issue's alternative resolution (declarecached_tokensfinal-only) is not taken — and no longer needed. Note only that there is no release note that these values are now populated mid-stream; wire-visible value change, not a schema change. - Right layer. The count is finalized at first token in the runtime and handed to the HTTP layer; the encoder is not patched at emit time.
Encoder::usage_valuestill sums each prompt's representative first choice (encode.rs:755-788), matchingstep_by(self.choices_per_prompt). - No new wire, proto, captured-graph or event variant. No
GenerationEventvariant was added, soPrompt::output_event_capacityandResponseLifecycleare untouched — the description's claim checks out, which is why the TLA+ model results are consistent (I did not re-runverification/helios-lifecycle/check.py(not opened)). - Charter fit: shared server code, no per-model branch, no new flag/config key/env var, no dependency change, no core-format change (previously exported cores unaffected). Completes a field that was accepted (
continuous_usage_stats) but only partly implemented, consistent with #417's "implement or reject" rule. - Prompt/choice index mapping is consistent:
prompt_usageis built withstep_by(decoded.request.choices)(http.rs:283-291),Encoder::choices_per_promptisdecoded.request.choices,usage_valuesteps by the same, and the newpending_cachedseed (http.rs:406-413) steps identically. No off-by-one betweenreport_cached_tokens(i, …)and the encoder's usage slot. - Count consistency between the two sources is provable: the first-token value is
carried.reused_prompt_tokens.unwrap_or(live.reused_prompt_tokens())(runtime.rs:2011-2016), andFinishedemits the sameunwrap_orshape, whileLiveRequest::reused_prompt_tokens()returnsadmission_reused_tokens, immutable after admission (scheduler.rs:348-350, set at:1779). The PR's core premise — the count is final by first token — holds. - Process gap: AGENTS.md:58 asks that unrun checks be recorded in
docs/TODO.txt. The description discloses "no GPU or exported-core live serving test was run", butdocs/TODO.txtis not among the changed files. Minor.
4. Tests & claim accuracy
Present and non-trivial: protocol/tests.rs:1415 (continuous_usage_reports_cached_tokens_before_finish), :1471 (continuous_usage_multi_choice_reports_first_choice_cached_tokens_per_prompt), phase_tests.rs:8449 (continuous_usage_streams_report_reused_prompt_tokens_and_preserve_messages — real Worker + RequestScheduler, warms a 13-token prefix, asserts every chunk equals 13, plus Chat miss = 0, Completions n=2, Messages 0/13), :8756 (staggered first-choice readiness, sibling must not overwrite the representative count, cumulative 8), :8869 (chat_continuous_usage_preserves_initial_cached_tokens_across_preemption — the readmitted live count is 13 while the stream must keep reporting 0). The updated assertion in disabled_host_store_preserves_decode_prefix_reuse_and_cancellation (phase_tests.rs:1718-1740) is consistent with the new carried-value semantics. I traced each assertion to the code path it covers and found no mismatch.
F4 — Minor: prompt_logprobs frames still report cached_tokens: 0, falsifying the "every Completions chunk" claim
helios/src/server/protocol/encode.rs:275-277:
let mut frame = self.chunk(index, json!(""), Value::Null);
frame.data["choices"][0]["logprobs"] = legacy;
Ok(vec![frame])
helios/src/server/protocol/encode.rs:313-315:
if self.include_usage {
data["usage"] = if self.continuous_usage { self.usage_value() } else { Value::Null };
}
helios/src/server/http.rs:495:
GenerationEvent::PromptLogprobs { start, tokens, values } => encoder.prompt_logprobs(index, start, &tokens, &values),
Produced by scored prefill at helios/src/server/runtime.rs:1907-1912, i.e. strictly before any generated token and therefore before report_cached_tokens runs (which happens only when the first GenerationEvent::ObservedToken is handled, http.rs:509-522). Those frames sum usage[i].cached while it is still 0.
Impact: claim accuracy only, reachable via Completions + prompt_logprobs + stream_options.{include_usage, continuous_usage_stats}. Chat rejects streamed prompt logprobs (http.rs:415-416, "Chat rejects streamed prompt logprobs"), so Chat is unaffected. The disclosed echo caveat (http.rs:437-452) covers echo frames only, not prompt-logprob frames.
Fix: state the limitation in the description ("prompt-logprob and echo frames, emitted before admission, report 0"), or seed the cached count earlier for prompts whose admission count is already known; a regression test mirroring the Chat/Completions tests with prompt_logprobs enabled would pin the claim either way.
Evidence I could not verify
- The suite counts (helios 1821 passed / 47 ignored, 62 integration; flare 246; flare-cli 219) and the TLA+ numbers are self-reported; no CI ran on
ef45ca9. flare/flare-cli are not changed by this PR. The helios counts differ from the same author's same-day #692 for the same command, so the two were measured on different revisions and are not comparable. - No GPU, exported-core or live-serving validation exists in the PR (
tests/server/test_protocols.py(not opened) does not covercontinuous_usage_statsat all), and nothing records that indocs/TODO.txt.
Open questions / not found
- Can the
Errfromobserve_token_withactually fire in practice? No test exercises it;scheduler.request()returns "stale or retired request handle" (scheduler.rs:1236-1242) when the slot has been reused or the handle outdated. This is exactly the caseruntime.rs:1822guards against withelse { continue; }, which suggests the author considers it reachable — which is why F1 is Major rather than theoretical. - Merge-order hazard for maintainers: #692, #548 and #560 all still encode
first_token: oneshot::Receiver<Result<()>>and the pre-#691ObservedTokenarm in the same regions ofruntime.rs/http.rs; landing #691 first forces three rebases. No conflicts exist today — no commits onmainsince basec513e46touch the changed files. - #448 remains open and needs closing on merge; no comment records the choice to fix the code rather than amend
docs/api.md. - Not found: any measurement of the
retaincost per observed token while prompts are pending (structurally bounded, cost unmeasured), and any prior PR attempting this fix.