Subtraction and simplicity scratchpad · NVIDIA/hyperflare-inference #691

Raw Markdown for agents: https://autobot.eidonix.com/p/d65df3ec-703c-433e-bc1c-fb61b4a471a7.md

#1 [high] Simplicity lens findings for PR #691

PR #691 head ef45ca9. Production delta ~110 lines + 742 test lines.

F1 (http.rs:404-413, 509-526 + runtime.rs:166-183): pending_cached: Vec<usize> state machine plus two extra Generation methods (has_pending_first_token, take_reused_prompt_tokens) exist only to skip an O(prompts) scan. take_reused_prompt_tokens conflates "pending" with "consumed" (returns Option for both), which is the sole reason has_pending_first_token exists. Concrete replacement: delete pending_cached (and the Chat-path pending_cached.clear() at http.rs:421) and in the ObservedToken arm do

for i in (0..size).step_by(decoded.request.choices) {
    if let Some(generation) = generations[i].as_mut()
        && let Some(reused) = generation.take_reused_prompt_tokens()
    { encoder.report_cached_tokens(i, reused); }
}

Deletes 10 lines in http.rs, one pub(super) method + 14 lines in runtime.rs, and the pending_cached/None => generation.has_pending_first_token() bookkeeping. Scan is bounded by prompt count and gated on continuous_usage; PR offers no measurement of the saving it buys.

F2 (runtime.rs:385-404 + 2011-2016): observe_token_with takes impl FnOnce() -> Result<u64> and returns Result<()>; the fallibility exists for exactly one caller while observe_token swallows it (let _ =). Hot-loop higher-order closure for a laziness that a bool guard gives. Replacement: keep observe_token(token, reused) infallible and add fn first_token_pending(&self) -> bool; at Worker::complete do the lookup under that guard, ?-propagating before the call. Removes the FnOnce parameter, the Ok(()) tail, and the discarded-error wrapper.

F3 (runtime.rs:2011-2016 is the fifth copy of) carried.reused_prompt_tokens.unwrap_or(live.reused_prompt_tokens()): also at runtime.rs:1475, 2099-2102, 2402-2405, 2554, and 2296-2297 (unwrap_or(reused)). Suggest one helper, e.g. impl Carried { fn reused(&self, live: &LiveRequest) -> u64 } or a Worker accessor that resolves handle -> count, and route all six sites through it (this PR adds two of the six).

F4 (runtime.rs:159-164): wait_for_first_token's None => Ok(0) arm is unreachable in production (the only caller, http.rs:418, calls it once per Chat stream, and first_token is Some at construction: runtime.rs:1030) yet silently reports "zero cached tokens" instead of the previous Result<()> error path. Either delete the arm (make the receiver non-optional for the Chat path) or document it as an intentional consumed-once default; the PR description does not mention the change.

F5 (tests): fixture boilerplate filter duplicated 6x identical: phase_tests.rs:59-67, 4790-4798, 8480-8488, 8492-8500, 8883-8887, 8895-8899 -> extract Fixture::text_only(). New test drivers duplicate existing helpers: run_http_with_worker (phase_tests.rs:8515-8631) hand-rolls the completion-frame loop that completion() (362) / advance() (393) / budget_pass() (425) already encode, and 8938-9053 repeats the same loop inline again; http_generation_request (4459) already exists. Three separate SSE parsers inside the three new tests: parse_sse_json (8453), next_chunk (8791), inline filter_map(strip_prefix("data:")) (9060), on top of five existing ones in the file.

Verdict: production change is small and mostly idiomatic; F1 and F2 are the high-value subtraction edits; F5 is the main test-weight issue (AGENTS.md:119-121 warns against exhaustive inventories, AGENTS.md:43-70/repo-prose about test-inventory prose in the description).

#2 [high] Verbatim quotes for the report

Verbatim quotes for the report (from pr/691 head ef45ca9).

Q1 — http.rs:404-413

        // Prompt cached usage reads each prompt's first choice (`step_by(choices)`).
        // Track only representative first choices whose `first_token` is still pending.
        let mut pending_cached: Vec<usize> = if continuous_usage {
            (0..size)
                .step_by(decoded.request.choices)
                .filter(|&i| generations[i].is_some())
                .collect()
        } else {
            Vec::new()
        };

Q1b — http.rs:509-523

                    if continuous_usage {
                        if !pending_cached.is_empty() {
                            pending_cached.retain(|&i| {
                                let Some(generation) = generations[i].as_mut() else {
                                    return false;
                                };
                                match generation.take_reused_prompt_tokens() {
                                    Some(reused) => {
                                        encoder.report_cached_tokens(i, reused);
                                        false
                                    }
                                    None => generation.has_pending_first_token(),
                                }
                            });
                        }

Q1c — runtime.rs:166-183

    pub(super) fn has_pending_first_token(&self) -> bool {
        self.first_token.is_some()
    }

    pub(super) fn take_reused_prompt_tokens(&mut self) -> Option<u64> {
        let receiver = self.first_token.as_mut()?;
        match receiver.try_recv() {
            Ok(Ok(reused)) => {
                self.first_token = None;
                Some(reused)
            }
            Ok(Err(_)) | Err(oneshot::error::TryRecvError::Closed) => {
                self.first_token = None;
                None
            }
            Err(oneshot::error::TryRecvError::Empty) => None,
        }
    }

Also http.rs:421 pending_cached.clear(); inside the Chat arm.

Q2 — runtime.rs:385-404

    fn observe_token(&self, token: u32, reused_prompt_tokens: u64) {
        let _ = self.observe_token_with(token, || Ok(reused_prompt_tokens));
    }
    fn observe_token_with(
        &self,
        token: u32,
        reused_prompt_tokens: impl FnOnce() -> Result<u64>,
    ) -> Result<()> {
        if let Some(sender) = self.first_token.take() {
            let _ = sender.send(Ok(reused_prompt_tokens()?));
        }

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

Q3 — six carried.reused_prompt_tokens.unwrap_or(...) sites: runtime.rs:1475, 2099-2102, 2296-2297, 2402-2405, 2554, and the new 2012-2014. Example (2554):

                  reused_prompt_tokens: Some(active.carried.reused_prompt_tokens.unwrap_or(reused)),

Q4 — 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),
        }
    }

Q5 — duplicated fixture strip, 6 copies, e.g. phase_tests.rs:8883-8887

                graph.inputs.retain(|binding| {
                    !matches!(
                        binding.source,
                        crate::model::contract::ValueSource::ImageFeatureIndex
                            | crate::model::contract::ValueSource::ImageFeatureSlot

occurrences: 59-67, 4790-4798, 8480-8488, 8492-8500, 8883-8887, 8895-8899. Test-loop duplication: phase_tests.rs:8586-8617 builds CompletionRecord/FrameCompletion by hand next to the existing completion() helper at 362-391; existing http_generation_request at 4459-4468 duplicates the driver inside the new tests; three new inline SSE parsers at 8453, 8791, 9060 vs five pre-existing. Note: existing http_generation_request_observed (4470-4499) builds http_state from plain Fixture::new() with no strip, so whether the new strips are needed at all is worth checking before factoring.

#4 [high] Research summary

Subtraction, Simplicity & Conventions lens — PR #691 (helios/server: report reused prompt tokens in continuous_usage_stats chunks, head ef45ca9)

The production change is small (~110 lines of the +868; ~742 are tests) and mostly idiomatic: Encoder::report_cached_tokens (encode.rs:288-292) is minimal, and threading the count through the existing first-token oneshot avoids a new GenerationEvent variant, so Prompt::output_event_capacity and ResponseLifecycle stay untouched. Five things can still be deleted or collapsed.

1. pending_cached (http.rs:404-413, 509-523, plus pending_cached.clear() at :421) should be deleted. The Vec<usize> of representative first-choice indices, its .retain(...) closure, and its seeding filter exist only to avoid rescanning (0..size).step_by(choices) per observed token. That scan is bounded by prompt count and the arm is already gated on continuous_usage, so it costs nothing when the feature is off; the PR measures no saving. Replace both blocks with a plain loop over (0..size).step_by(decoded.request.choices) that calls take_reused_prompt_tokens() and report_cached_tokens(i, reused) on Some — the same step_by that Encoder::usage_value (encode.rs:763-768) already defines as the source of truth. ~10 lines out of http.rs, and the filter(|&i| generations[i].is_some()) seeding becomes redundant.

2. Generation::has_pending_first_token (runtime.rs:166-168) exists only because take_reused_prompt_tokens (runtime.rs:170-183) conflates "still pending" with "consumed" — its Option<u64> carries three states and the caller has to interrogate the receiver twice. Once suggestion 1 lands, the caller no longer needs to distinguish them; delete has_pending_first_token and clear the receiver on any completed outcome.

3. Delete Incoming::observe_token_with's impl FnOnce() -> Result<u64> (runtime.rs:385-404) and its single caller's closure (runtime.rs:2011-2016). A generic closure parameter plus a Result return on the worker's per-token hot path, added for one caller, while observe_token discards the error (let _ =). Keep the infallible two-argument observe_token as the only entry point (all existing tests keep working), add a two-line first_token_pending() bool, and hoist the scheduler lookup into a plain if/unwrap_or before the call. That also leaves the question of whether the lookup's ? should propagate to the correctness lens instead of baking it into a closure.

4. carried.reused_prompt_tokens.unwrap_or(live.reused_prompt_tokens()) now appears six times — runtime.rs:1475, the new 2012-2014, 2099-2102, 2296-2297, 2402-2405, 2554. This PR adds two of the six. One accessor on Carried (or a Worker::reused_prompt_tokens(handle) -> Result<u64> beside scheduler.request) should serve all of them and give the "finalized count, then locked" invariant a single home.

5. Test weight re-implements existing helpers. The text-only fixture strip is copied verbatim six times (phase_tests.rs:59-67, 4790-4798, 8480-8488, 8492-8500, 8883-8887, 8895-8899; the last four are adjacent pairs — ~40 removable lines) and may not even be needed, since http_generation_request_observed (:4470-4499) builds state from plain Fixture::new() without it. run_http_with_worker (:8515-8631) hand-builds CompletionRecord/FrameCompletion (:8586-8617) beside the existing completion() helper (:362-391), copies budget_pass's lane-generates predicate (:442-444), and the whole loop is written out again inline at :9026-9053. Three new inline SSE parsers (:8453, :8791, :9060) join five already in the file.

Conventions: AGENTS.md:119-121 warns against inventories of files and tests — the description names five tests and four whole-suite counts against a ~110-line production delta — and AGENTS.md:129-132 asks to drop assurances that add no technical evidence. AGENTS.md:57-59 requires unrun checks in docs/TODO.txt; the disclosed GPU/exported-core/live-serving gap has no entry, and TODO.txt is not among the changed files. docs/api.md (not opened) is legitimately untouched: it already promises the behavior this PR implements, so nothing drifts.

Deletion-shaped items handed to the correctness lens rather than duplicated here: wait_for_first_token's None => Ok(0) arm (runtime.rs:159-164) is unreachable in production — the only caller is http.rs:418 and first_token is always Some at construction (runtime.rs:1030) — so it should either not exist or not silently report zero; and take_reused_prompt_tokens swallowing Ok(Err(_)) is the same silent-zero pattern in miniature.

Findings, verbatim quotes and safety checks are in scratchpad notes 1-3.

#5 [high] Final report as delivered (simplicity lens)

Review lens: Subtraction, Simplicity & Conventions. PR #691, head ef45ca9. Status reported: met.

OPENING FRAME (positive assessment to keep): The production change is small (~110 lines of +868; ~742 are tests) and mostly idiomatic. Encoder::report_cached_tokens (encode.rs:288-292) is minimal. Routing the count through the existing first-token oneshot instead of adding a GenerationEvent variant is the right call and keeps Prompt::output_event_capacity and ResponseLifecycle untouched. Wiring is gated on continuous_usage (http.rs:293-294) / set_continuous_usage (encode.rs:280-282) so nothing is spent when the option is off. docs/api.md is legitimately unchanged: docs/api.md:1039-1045 and :1058-1061 already promise cumulative per-chunk counts, so the PR closes a gap rather than creating drift.

FIVE SUGGESTIONS (final wording, in priority order):

  1. Delete pending_cached (http.rs:404-413, 509-523, clear() at :421). It exists only to skip an O(prompts) rescan; the arm is already gated on continuous_usage and the PR measures no saving. Replace with the plain loop over (0..size).step_by(decoded.request.choices) calling take_reused_prompt_tokens() + report_cached_tokens(i, reused), mirroring usage_value's step_by(self.choices_per_prompt) (encode.rs:763-768). ~10 lines out; seeding filter(|&i| generations[i].is_some()) becomes redundant.
  2. Delete Generation::has_pending_first_token (runtime.rs:166-168). It exists solely because take_reused_prompt_tokens (runtime.rs:170-183) returns Option for both "pending" and "consumed". After #1 the caller no longer needs the distinction; clear the receiver on any completed outcome.
  3. Delete Incoming::observe_token_with's impl FnOnce() -> Result<u64> (runtime.rs:385-404) and its one caller's closure (runtime.rs:2011-2016). Generic closure + Result on the per-token hot path for one caller, whose error observe_token deliberately discards (let _ =). Keep infallible observe_token(token, reused) as the only entry point (all existing tests unchanged), add a two-line first_token_pending(), hoist the lookup into an if/unwrap_or before the call. Also lets the correctness lens decide whether the ? should propagate at all instead of it being baked into a closure.
  4. Six copies of carried.reused_prompt_tokens.unwrap_or(live.reused_prompt_tokens()): runtime.rs:1475, 2012-2014 (new), 2099-2102, 2296-2297, 2402-2405, 2554. This PR adds two. One accessor on Carried, or Worker::reused_prompt_tokens(handle) -> Result<u64> beside scheduler.request (scheduler.rs:1236), should serve all six.
  5. Test weight re-implements existing helpers: text-only fixture strip copied 6x (phase_tests.rs:59-67, 4790-4798, 8480-8488, 8492-8500, 8883-8887, 8895-8899; last four are adjacent pairs, ~40 removable lines) and possibly unnecessary since http_generation_request_observed (:4470-4499) uses plain Fixture::new() with no strip; run_http_with_worker (:8515-8631) hand-builds CompletionRecord/FrameCompletion (:8586-8617) beside completion() (:362-391) and copies budget_pass's lane-generates predicate (:442-444), with the loop written out again inline at :9026-9053; three new inline SSE parsers (:8453, :8791, :9060) join five already in the file.

CONVENTIONS:

HANDED TO CORRECTNESS LENS (not duplicated as my findings, stated as deletion-shaped):

Evidence basis: full diff of the two production files read; all six call sites of the unwrap_or pattern located; both callers of the oneshot API enumerated; diff of phase_tests.rs and protocol/tests.rs read; no code was compiled or executed.

#3 [medium] Safety checks and convention citations

Checks confirming the suggestions are safe to state as simplification-only: