Subtraction, Simplicity & Conventions review — PR #691 (helios/server: report reused prompt tokens in continuous_usage_stats chunks), head ef45ca9
Key findings
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 a minimal 3-line setter, and threading the count through the existing first-token oneshot rather than adding a GenerationEvent variant is the right structural call: it leaves Prompt::output_event_capacity and ResponseLifecycle untouched and keeps the encoder's step_by ownership intact. Wiring is gated on continuous_usage (http.rs:293-294), so nothing is spent when the option is off, and docs/api.md:1039-1045 (not opened) / :1058-1061 already promised cumulative per-chunk counts — the PR closes a documented gap rather than creating drift. No new config flags, env vars, crates, or per-model branches.
Five things can still be deleted or collapsed, in priority order:
pending_cachedis aVec<usize>state machine that buys an unmeasured O(prompts) saving —http.rs:404-413,:509-523, pluspending_cached.clear()at:421. Replace with the plainstep_byscan the encoder already defines as the source of truth. ~10 lines out of http.rs.Generation::has_pending_first_token(runtime.rs:166-168) exists only to disambiguatetake_reused_prompt_tokens's overloadedOption<u64>. Delete both once (1) lands.Incoming::observe_token_with(runtime.rs:388-404) adds a genericFnOnce() -> Result<u64>closure and a fallible tail to the per-token hot path for exactly one caller whose errorobserve_tokendeliberately discards. Keep the infallible two-argument form plus a bool guard.carried.reused_prompt_tokens.unwrap_or(<live count>)now has six copies (this PR adds two); oneCarriedaccessor should own the "finalized then locked" invariant.- Test weight re-implements helpers that already exist in
phase_tests.rs—run_http_with_workerhand-builds completion records besidecompletion(), and adds three more inline SSE parsers.
Conventions: two real deviations — AGENTS.md:119-121 (no inventories of tests/files) and AGENTS.md:57-59 (record unrun checks in docs/TODO.txt).
1. Delete pending_cached and its retain bookkeeping (highest value)
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()
};
http.rs:509-523 (the GenerationEvent::ObservedToken arm):
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(),
}
});
}
and http.rs:421, inside the Chat arm: pending_cached.clear();
What it buys: the Vec exists solely so the loop stops rescanning (0..size).step_by(choices) on every observed token. That scan is bounded by prompt count (single digits in practice) and the whole arm is already inside if continuous_usage, which is itself the gate that selects generate_many_observed (http.rs:330-331) — so when the feature is off the cost is zero either way. The description claims "eliminating scanning once all representative first choices have started" but offers no measurement, and the state has a real price: the seeding filter(|&i| generations[i].is_some()) (:409) must be kept in sync with the drain's own let Some(generation) = ... else { return false } (:512-514) — the same emptiness test written twice, plus a third clear() special case for the Chat path (:421).
Replace both blocks (and :421) with:
if continuous_usage {
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);
}
}
This mirrors Encoder::usage_value's own definition of a prompt's representative choice — encode.rs:763-768:
let cached: u64 = self
.usage
.iter()
.step_by(self.choices_per_prompt)
.map(|u| u.cached)
.sum();
so the drain loop and the authoritative terminal sum are visibly the same index set, instead of one being a cached copy of the other. Net deletion: ~10 lines in http.rs (the Vec declaration with its if/else, the retain closure, the clear()), and it removes the None => generation.has_pending_first_token() term — i.e. suggestion 2 below falls out for free.
2. Delete Generation::has_pending_first_token and simplify take_reused_prompt_tokens
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,
}
}
Option<u64> here means three things at once — "no receiver", "still pending (Empty)", and "consumed with an outcome I am swallowing" — and has_pending_first_token exists for no other reason than to let the caller tell the last one from the first two. That is the definition of a state machine the caller should not have to hold. Once suggestion 1 makes pending_cached go away, no caller needs the distinction: the loop above simply re-polls every representative choice each observed token, and a None (pending, already consumed, or failed) simply means "nothing to report yet". Delete has_pending_first_token (3 lines) and its pub(super) surface. first_token.is_some() is checked nowhere else after this change — the four take_reused_prompt_tokens/has_pending_first_token uses are all in the arm quoted above.
I am deliberately leaving the semantic question of the swallowed Ok(Err(_)) (a failed first token silently becoming "zero cached") to the Correctness & Contracts lens; the simplicity point is only that the third state must not exist.
3. Collapse observe_token_with back into observe_token
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 its single caller, 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(),
})
})?;
Three pieces of machinery were added for one call site: a monomorphised impl FnOnce parameter, a Result<()> return on the worker's per-token path, and a closure that captures &self plus request to defer a scheduler lookup. The deferral is not the point — the guard is: the lookup only runs while first_token is still pending. observe_token itself (:385-386) immediately throws the error away with let _ =, so the fallibility exists at the Incoming API surface purely for the caller at :2011 (which is the sole non-test user of the _with form).
Replace with an infallible two-argument observe_token(token, reused) — which all existing tests already call (phase_tests.rs:8801, :8822, etc., and the runtime unit tests pass 0) — plus a two-line predicate, e.g. fn first_token_pending(&self) -> bool { self.first_token.is_some() }, and hoist the lookup to the call site:
let reused = match request.carried.reused_prompt_tokens {
Some(reused) => reused,
None if request.incoming.first_token_pending() => {
self.scheduler.request(token.request)?.reused_prompt_tokens()
}
None => 0, // never sent: first_token already taken
};
request.incoming.observe_token(token.token, reused);
request.last_token = Some(token.token);
This deletes the FnOnce parameter, the Ok(()) tail, and the || Ok(...) wrapper at :386. It also decouples a decision that should not be hidden inside a closure: whether scheduler.request(handle)? may abort Worker::complete and fail_all outstanding requests is a question for the Correctness lens; as written the ? is baked into a lazily-evaluated closure, which is precisely the shape that makes such a question hard to see.
4. Six copies of the same "finalized, else live" expression — give it one home
Searching runtime.rs for reused_prompt_tokens.unwrap_or returns :345, :1475, :2297, :2554; the multi-line forms add :2099-2102 and :2402-2405, and this PR adds the closure copy at :2012-2014. Representative sites:
runtime.rs:1475 (existing):
reused_prompt_tokens: Some(active.carried.reused_prompt_tokens.unwrap_or(live.reused_prompt_tokens())),
runtime.rs:2099-2102 (existing):
reused_prompt_tokens: request
.carried
.reused_prompt_tokens
.unwrap_or(live.reused_prompt_tokens()),
runtime.rs:2554 (existing):
reused_prompt_tokens: Some(active.carried.reused_prompt_tokens.unwrap_or(reused)),
This PR does not invent the pattern — it adds two of the six instances (:2012-2014 and the forced-close path) — but it is the moment the count reaches six, and the expression encodes a subtle live invariant (docs/core-design.md:1532-1533 (not opened): admission reuse counts stay fixed even as the request publishes more shared ancestors). Six hand-copied unwrap_or sites mean six places where a future change to that invariant can silently disagree. One accessor — e.g. impl Carried { fn reused(&self, live: &LiveRequest) -> u64 }, or Worker::reused_prompt_tokens(handle) -> Result<u64> sitting beside scheduler.request — should serve all six, letting the new closure at :2011-2016 become Ok(request.carried.reused(...)) too. :345's unwrap_or(0) sibling is the same shape with a different fallback and should be reviewed with it.
5. Test weight re-implements helpers already in the file (structural, not nitpicking)
phase_tests.rs:8586-8617 builds CompletionRecord/FrameCompletion by hand inside the new run_http_with_worker (:8515-8631) even though completion() at :362-391 and advance() at :393 already encode that record construction, and the same driver loop is then written out again inline at :9026-9053. The new tests also introduce three more inline SSE parsers — parse_sse_json (:8453), next_chunk (:8791), and a filter_map(strip_prefix("data:")) inline at :9060 — joining five that already exist in the file. Three private variants of the same parse are how these tests will drift apart.
The text-only fixture strip is copied six times, verbatim: :59-67, :4790-4798, :8480-8488, :8492-8500, :8883-8887, :8895-8899 — the last four in adjacent pairs within two new tests:
for graph in &mut fixture.config.contract.graphs {
graph.inputs.retain(|binding| {
!matches!(
binding.source,
crate::model::contract::ValueSource::ImageFeatureIndex
| crate::model::contract::ValueSource::ImageFeatureSlot
:59-67 is inside Fixture's own constructor with the comment "Prepared text prompts have no image arrays or image graph inputs" — so the four new copies re-run a strip the constructor it calls already performed. Before factoring it into e.g. Fixture::text_only(), check whether the new strips are needed at all: the pre-existing http_generation_request_observed (:4470-4499) builds its http state from plain Fixture::new() with no strip. Either way, ~40 removable lines.
Material repo conventions
AGENTS.md:119-121— "Avoid exhaustive inventories of changed files, preserved properties, buffers, and tests" — andAGENTS.md:129-132— "Remove process assurances that add no technical evidence". The description names five tests individually and quotes four whole-suite pass counts (helios 1821/47, flare 246/4, flare-cli 219/3) against a ~110-line production delta; neither flare crate is changed by this PR, so those two counts cannot evidence anything about it. The per-test assertions are the evidence; the counts and the enumeration are the noise the convention targets.AGENTS.md:57-59— "Record unresolved defects, unrun checks, and pending measurements indocs/TODO.txt". The description explicitly discloses "no GPU or exported-core live serving test was run", and nodocs/TODO.txtentry records it (docs/TODO.txtis not among the six changed files). This is the one convention gap with operational consequence — the untested path is live serving under real prefix reuse.
No other structural convention issues: the change is in shared server code with no per-model branch and no new flag (respects the charter's model-agnostic and zero-config rules), no new dependency (tokio::oneshot was already in use), and no protobuf/core-format change.
Deletion-shaped items handed to the Correctness & Contracts lens (not duplicated here)
wait_for_first_token'sNone => Ok(0)arm (runtime.rs:159-164) reports "zero cached tokens" for a receiver that was already taken. It is unreachable in production — the only caller ishttp.rs:418, andfirst_tokenisSomeat construction (runtime.rs:1030) — so the arm should either not exist or not silently look like a valid zero.take_reused_prompt_tokensswallowingOk(Err(_))(runtime.rs:177-180) is the same silent-zero pattern in miniature.- Whether the newly fallible first-token scheduler lookup (
runtime.rs:2014) can propagate out ofWorker::completeandfail_alloutstanding requests is a correctness question; my suggestion 3 only proposes that the?stop hiding inside a closure.
Open questions / not found
- Whether the four new fixture strips are needed at all (see 5) — I did not execute the tests, so I cannot say whether removing them breaks the new cases; only that the pre-existing equivalent does not use them.
- Whether reviewers will accept an O(prompts) rescan per observed token in place of
pending_cached; the PR provides no measurement either way, so this is a judgment call, not a regression risk (the scan is gated oncontinuous_usageand bounded by prompt count). - The PR has no CI run on
ef45ca9, no reviews, and no labels, so none of the above has been checked by a build; my findings come from reading the diff atpr/691only, with no code compiled or executed.