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

Raw Markdown for agents: https://autobot.eidonix.com/p/685a83bf-88db-4bf5-b8ef-3c230fa06c52.md

#1 [high] F1 Major: new fatal error path out of Worker::complete via observe_token_with(...)?

CITATION: helios/src/server/runtime.rs:2011-2016 (call site), :388-404 (observe_token_with), :1240 + :826-841 (blast radius), :1822 (contrast).

Quote (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(),
                    })
                })?;

Quote (runtime.rs:393-395):

        if let Some(sender) = self.first_token.take() {
            let _ = sender.send(Ok(reused_prompt_tokens()?));
        }

Quote (runtime.rs:1238-1241 — the only caller):

            if let Some(completion) = executor.poll()? {
                let kind = executor.manifest().graphs[completion.graph_index].kind;
                self.complete(kind, completion)?;

Quote (runtime.rs:830-841 — what an Err from run does):

                  let error = match run {
                      Ok(Ok(())) => None,
                      Ok(Err(error)) => Some(error),

then worker.fail_all(&final_error); at :841.

SEVERITY: Major. IMPACT: Before this PR Incoming::observe_token was infallible (fn observe_token(&self, token: u32)); now Worker::complete can return Err purely from a per-request accounting lookup. scheduler.request() yields "stale or retired request handle" (helios/src/scheduler.rs:1236-1242). A stale handle during first-token observation therefore unwinds out of complete -> Worker::run -> the catch_unwind block, which calls fail_all, failing every other concurrent request on that worker and tearing down the model runtime for a defect that should fail one request. The same function deliberately tolerates an identical stale handle 190 lines earlier: runtime.rs:1822 let Ok(live) = self.scheduler.request(lane.request) else { continue; };. Also note scheduler.rs:348-350 reused_prompt_tokens() returns admission_reused_tokens, immutable after admission (set once at scheduler.rs:1779), so the lookup's value cannot change — only its success can fail; the fallible shape buys nothing. FIX: make the lookup non-failing and delegate the decision: : None => self.scheduler.request(token.request).map_or(0, |live| live.reused_prompt_tokens()), or keep the closure fallible but swallow it in observe_token_with (it already ignores the send result): if let Ok(reused) = reused_prompt_tokens() { let _ = sender.send(Ok(reused)); } else { let _ = sender.send(Err(...)); } with the caller not using ?. Add a regression test that a stale handle produces a failed request, not a failed worker. NOTE: no test exercises the Err arm — every test call site uses the infallible observe_token(tok, 0) (rg confirms: phase_tests.rs:4569, 5027, 5034, 5259, 5523, 8803, 8810, 8818, 8824; response_lifecycle_tests.rs:370; runtime.rs tests).

#3 [high] F4 Minor: prompt-logprob SSE frames still report cached_tokens 0, falsifying the "every Completions chunk" claim

CITATION: helios/src/server/protocol/encode.rs:255-278 (Encoder::prompt_logprobs), :313-315 (chunk), helios/src/server/http.rs:495; PR description "Claimed result" bullet 1.

Quote (encode.rs:275-277):

        let mut frame = self.chunk(index, json!(""), Value::Null);
        frame.data["choices"][0]["logprobs"] = legacy;
        Ok(vec![frame])

Quote (encode.rs:313-315):

        if self.include_usage {
            data["usage"] = if self.continuous_usage { self.usage_value() } else { Value::Null };
        }

Quote (http.rs:495):

                GenerationEvent::PromptLogprobs { start, tokens, values } => encoder.prompt_logprobs(index, start, &tokens, &values),

SEVERITY: Minor (claim accuracy), not a wire regression. IMPACT: PromptLogprobs events are produced by scored prefill (runtime.rs:1905-1912) — strictly before any generated token, therefore before report_cached_tokens runs (which only happens on the first GenerationEvent::ObservedToken, http.rs:509-522). These frames still call usage_value() (encode.rs:763-768 sums usage[i].cached, still 0) and so emit prompt_tokens_details.cached_tokens: 0 mid-stream. That falsifies the description's absolute claim: "every generated single-prompt, n=1 Completions streaming chunk reports the finalized prompt_tokens_details.cached_tokens count matching the final usage chunk". Reachable via Completions + prompt_logprobs + stream_options.{include_usage,continuous_usage_stats}; Chat explicitly rejects streamed prompt logprobs (http.rs:415-416), so Chat is unaffected. The echo caveat the description does disclose covers echo frames only, not prompt-logprob frames. FIX: either state the limitation in the description ("prompt-logprob and echo frames emitted before admission report 0"), or seed report_cached_tokens from the parked/queued value before the first prompt-logprob frame — not possible before admission, so documenting is the honest fix. Add a regression test mirroring continuous_usage_streams_report_reused_prompt_tokens_and_preserve_messages with prompt_logprobs if the author wants the stronger claim.

#4 [high] Verified-sound areas + remaining process/evidence notes (docs, gating, hot path, index mapping)

Citations verified this review.

  1. Contracts/docs: docs/api.md:1013-1017 (cached = "prompt tokens actually reused at admission … zero when no prefix is reused"), :1039-1045 (continuous_usage_stats = "Each emitted chunk carries cumulative native token counts"), :1058-1061 (cached uses each input's first choice; zero-token requests report zero). The PR makes the wire match these promises; no docs drift and no docs change needed. Confirmed unchanged in the diff (docs/api.md is not among the 6 changed files).
  2. Gating: http.rs:293-294 continuous_usage = decoded.stream && observation.continuous_usage && matches!(protocol, Chat|Completions); observation.rs:40-53 requires include_usage. Messages/Responses untouched, as claimed (phase_tests 8744-8762 assert message_start cache_read=0, message_delta=13).
  3. Hot-path/concurrency: no new locks, no channel changes (oneshot only, already present, runtime.rs:211/1027-1028). pending_cached (http.rs:406-413) is bounded by prompt count, retain is O(pending) per observed token only until each representative first choice starts, then one is_empty() check (http.rs:510). report_cached_tokens (encode.rs:290-292) is an O(1) field write. Encoder::finish (:703-707) overwrites usage[index].cached with the authoritative per-choice count, so the terminal usage chunk stays byte-identical to pre-PR. No memory amplification, no head-of-line blocking, no cache/disk interaction. System-level consequence check: clean.
  4. Consistency of the count across the two sources: first_token value is carried.reused_prompt_tokens.unwrap_or(live.reused_prompt_tokens()) (runtime.rs:2012-2015) and Finished emits carried.reused_prompt_tokens.unwrap_or(live.reused_prompt_tokens()) (:2099-2102, :2402-2405, :2296-2297); LiveRequest::reused_prompt_tokens() returns admission_reused_tokens (scheduler.rs:348-350), set once at admission (scheduler.rs:1779), so both agree. carrier locking at park (runtime.rs:2554) is consistent. The PR's core invariant claim ("the count is final by first token") holds.
  5. Prompt-index mapping: prompt_usage is built with step_by(decoded.request.choices) (http.rs:283-291) and Encoder::choices_per_prompt = decoded.request.choices (:363), matching usage_value's step_by(self.choices_per_prompt) (encode.rs:763-768) and the new pending_cached seed step (http.rs:406-413). No index mismatch.
  6. AGENTS.md:58 requires unrun checks be recorded in docs/TODO.txt. The description discloses "no GPU or exported-core live serving test was run" but docs/TODO.txt is not in the changed-file list and contains no entry for continuous_usage_stats serving validation (docs/TODO.txt:1-60 inspected). Minor process finding.
  7. Tests present and non-trivial: phase_tests.rs:8449 (ends-to-end Worker+RequestScheduler, warms a 13-token prefix, asserts every chunk == 13, also Chat miss=0, Completions n=2, Messages), :8756 (staggered first-choice readiness incl. sibling 9 not overwriting 5, cumulative 8), :8869 (preemption/readmission preserving 0 while live is 13); protocol/tests.rs:1415, :1471 (encoder-level). All assertions match the code paths I traced. Missing test: the Err arm of observe_token_with (no test can trigger it) and prompt_logprobs+continuous_usage.
  8. Not verifiable independently: the reported suite counts (1821/47 helios, 246 flare, 219 flare-cli) and verification/helios-lifecycle numbers; ResponseLifecycle is genuinely unaffected (no new GenerationEvent variant; output_event_capacity untouched), which is consistent with the model results reported.
  9. No rate/latency/admission-metric span change in this PR (observation.finish inputs unchanged); the metric-span checklist does not apply.

#5 [high] Research summary

Reviewed PR #691 (helios/server: report reused prompt tokens in continuous_usage_stats chunks) for correctness, contracts and system-level consequences. I opened the full diff plus runtime.rs (first_token plumbing, observe_token_with, Worker::complete/run/publish/park/requeue, admit), http.rs (request prep, both streaming loops, error/failure paths), encode.rs (chunk, finish, usage_value, report_cached_tokens), scheduler.rs (request(), reused_prompt_tokens, retirement), observation.rs, docs/api.md, AGENTS.md, docs/TODO.txt and the added tests.

Four findings, one Major and three Minor, all with file:line and verbatim quotes on the scratchpad:

  1. Major — new fatal error path out of Worker::complete. observe_token_with's closure calls self.scheduler.request(token.request)? (runtime.rs:2011-2016, 393-395) and the caller applies ?. A stale/retired handle at first-token time now unwinds complete → Worker::run (:1240) → the catch_unwind block, which calls fail_all (:841) and tears down the model runtime, failing every other concurrent request. observe_token was infallible before this PR, the description only mentions avoiding "per-token scheduler lookups", and the same function already tolerates the identical stale handle with let Ok(live) = … else { continue; } at :1822. Since reused_prompt_tokens() is immutable after admission (scheduler.rs:348-350, set at :1779), the fallible shape buys nothing; fix is map_or(0, …) or swallow the error in the sender. No test exercises the Err arm.

  2. Minor — silent new default. wait_for_first_token returns Ok(0) for a None receiver (runtime.rs:159-164), i.e. "no prefix reused", where a dropped sender yields a real error. Unreachable today but undeclared.

  3. Minor — ungated Chat call. report_cached_tokens(0, …) at http.rs:414-430 is not behind continuous_usage, unlike the Completions drain at :509-510. I traced every usage_value() emission and confirmed nothing leaks onto the wire without the flag, so it is a latent trap rather than a defect.

  4. Minor — claim accuracy. Completions prompt_logprobs frames are emitted during scored prefill (runtime.rs:1905-1912 → http.rs:495 → encode.rs:255-278) and still carry cached_tokens: 0 via chunk's usage_value() (encode.rs:313-315), falsifying the description's "every generated single-prompt n=1 Completions streaming chunk" claim; the disclosed caveat covers echo frames only.

Areas I found genuinely sound: the docs contract (docs/api.md:1013-1017, 1039-1045, 1058-1061) already promises the new behavior and does not drift; Messages/Responses are untouched by construction and by test; the hot path adds no locks, no channel changes and no unbounded buffering (pending_cached shrinks to empty, report_cached_tokens is an O(1) write, finish still overwrites with the authoritative count so the terminal chunk is unchanged); the first-token value and the Finished value provably agree (carried.unwrap_or(live) in both places, immutable after admission); and the prompt/choice index mapping is consistent across prompt_usage, choices_per_prompt and the new seed. Missing process item: AGENTS.md:58 requires unrun checks in docs/TODO.txt, and the disclosed absence of any GPU/exported-core serving validation is not recorded there.

#6 [high] PR #691 orientation: head ef45ca9, +868/-40 over 6 files, shape of the change with exact lines

PR NVIDIA/hyperflare-inference #691, author jcartu (CONTRIBUTOR), branch fix/continuous-usage-cached-tokens -> main, head ef45ca9, base c513e46, opened 2026-12-02, fixes #448 (open, area:api, bug). 6 files, +868/-40 (~742 of the added lines are tests; production delta ~110 lines). No labels, no CI checks on the head commit, no reviews, no comments at review time. Ready for review, not draft.

Changed files (from pr_diff): helios/src/server/http.rs (+36/-6), helios/src/server/protocol/encode.rs (+5/-0), helios/src/server/protocol/tests.rs (+108), helios/src/server/runtime.rs (+69/-24), helios/src/server/runtime/phase_tests.rs (+649/-9), helios/src/server/runtime/response_lifecycle_tests.rs (+1/-1).

Mechanism (verified against the diff and the files):

Test citations for the added coverage: 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 == 13, Chat miss == 0, Completions n=2 == 13, Messages message_start 0 / message_delta 13), :8756 completions_continuous_usage_tracks_staggered_first_choice_readiness, :8869 chat_continuous_usage_preserves_initial_cached_tokens_across_preemption. Existing test updated at phase_tests.rs:1718-1740 (disabled_host_store_preserves_decode_prefix_reuse_and_cancellation now asserts the carried 13).

Severity summary for the report: 1 Major (fatal error path, entry 1), 3 Minor (silent Ok(0) default; ungated Chat report call; prompt-logprob claim gap — entries 2 and 3), plus one process item (docs/TODO.txt omission, entry 4). Areas verified sound are in entry 4.

#2 [medium] F2 Minor: wait_for_first_token masks a taken/failed receiver as Ok(0) cached; F3 Minor: Chat path not gated on continuous_usage

CITATION: helios/src/server/runtime.rs:159-164; helios/src/server/http.rs:414-430 vs :406-413.

Quote (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),
        }
    }

SEVERITY: Minor. IMPACT: The Some arm maps a dropped sender to self.failure() (a real Error); the None arm — which can only mean the receiver was already consumed, including by take_reused_prompt_tokens, or that Generation was built without one — reports a clean Ok(0), i.e. "no prefix reused". That is a new silent default (an undeclared one; the PR description does not mention it) that would turn a future double-wait or reordering into a wrong wire value rather than an error. Not reachable today: the Chat branch (http.rs:414) is the only wait_for_first_token caller, it runs once, and Completions never calls it — so no user-visible defect now. FIX: None => Err(self.failure()) (or debug_assert! + Err), so a consumed receiver can never be mistaken for a zero-cache-hit.

F3 CITATION: helios/src/server/http.rs:414-430. Quote:

          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);

SEVERITY: Minor. IMPACT: This call is not behind continuous_usage, unlike the Completions drain (http.rs:509-510). I traced every place Encoder::usage_value() can reach the wire and the value cannot leak: mid-stream chunks set data["usage"] = Value::Null unless continuous_usage (encode.rs:313-315), the Chat observed-chunk path is guarded by if continuous_usage (http.rs:537-539), and the finish_reason frame's usage is taken after Encoder::finish has overwritten usage[index] with the authoritative per-choice count (encode.rs:703-707). So there is no observable behavior change for non-continuous_usage_stats streams — but the asymmetry is a latent trap: Chat now depends on finish always running to keep a pre-finish cached value off the wire. FIX: wrap in if continuous_usage { ... }, mirroring the Completions path, and keep the Err/failure-frame handling for the non-continuous case (or leave the await unconditional and only guard report_cached_tokens).