Correctness and contracts report · NVIDIA/hyperflare-inference #691

Raw Markdown for agents: https://autobot.eidonix.com/p/3ebb04b4-b83a-4dc8-a10f-7cb389f465c1.md

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

  1. Major — the change introduces a new fatal error path out of Worker::complete. Incoming::observe_token_with's closure calls self.scheduler.request(token.request)? and the caller applies ? (runtime.rs:2011-2016). A stale/retired handle at first-token time now unwinds complete → Worker::run (:1240) → the catch_unwind block, which calls worker.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_token was 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). Because reused_prompt_tokens() is immutable after admission (scheduler.rs:348-350, set once at :1779), the fallible shape buys no correctness.
  2. Minor — new silent default: wait_for_first_token returns Ok(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.
  3. Minor — asymmetric gating: the Chat report_cached_tokens(0, …) call (http.rs:414-430) is not behind continuous_usage, unlike the Completions drain (http.rs:509-510). I traced every usage_value() emission and nothing leaks onto the wire without the flag, so this is a latent trap, not a defect.
  4. Minor — one claim in the description is too strong: Completions prompt_logprobs frames are emitted during scored prefill (runtime.rs:1907-1912 → http.rs:495 → encode.rs:255-278) and still carry cached_tokens: 0 through chunk's usage_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 covers echo frames only.
  5. Process: no docs/TODO.txt entry for the disclosed absence of any GPU/exported-core live-serving validation (AGENTS.md:58 requires recording unrun checks), and no test exercises the new Err arm.

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

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:

3. Architecture, contracts & charter compliance

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

Open questions / not found

  1. Can the Err from observe_token_with actually 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 case runtime.rs:1822 guards against with else { continue; }, which suggests the author considers it reachable — which is why F1 is Major rather than theoretical.
  2. Merge-order hazard for maintainers: #692, #548 and #560 all still encode first_token: oneshot::Receiver<Result<()>> and the pre-#691 ObservedToken arm in the same regions of runtime.rs/http.rs; landing #691 first forces three rebases. No conflicts exist today — no commits on main since base c513e46 touch the changed files.
  3. #448 remains open and needs closing on merge; no comment records the choice to fix the code rather than amend docs/api.md.
  4. Not found: any measurement of the retain cost per observed token while prompts are pending (structurally bounded, cost unmeasured), and any prior PR attempting this fix.