Review — PR #692 helios: count output-layer stream failures under requests_failed_total
Head 348c06c, base main (c513e46) against pr/692. Tool caveat: pr_diff failed for every path with git: error: Could not read c513e46a79f3b6ac510235aaf09bcf055b841958, so all verification below was done by reading head files (ref: pr/692) and main files (ref: main) side by side. Every line number is from read_file output on head, not reconstructed.
Key findings
The mechanism does what the description says: RequestOutcome is a monotonic six-state Arc<AtomicU8> whose transitions each CAS into an absorbing terminal state with the counter increment inside the successful Ok(_) arm only, so no request is counted twice and nothing is ever decremented. The worker cancellation sites, fail_output's fail-before-cancel ordering, and emit_finished's reserve→record→send ordering are all correct as described. No new lock, buffering growth, or extra copy enters the hot path; the added state is one Arc<AtomicU8> on a path that already allocates a channel, two oneshots and a semaphore permit.
What is not sound is the contract and verification surface:
- Major — the counters' documented meaning silently changes, and differs per entry point.
completedandcancelledkeep model-generation HELP text but now mean "worker finished and the HTTP consumer validated output" for HTTP/Decisions, while still meaning "worker finished" for in-process callers. - Major — the formal/conformance gate in
docs/design-review.mdis not satisfied. Six new protocol states and rewritten cancellation/completion transitions get no TLA+ action, no conformance transition, no mutation guard; the existing harness structurally cannot reach the deferred half of the machine. - Minor — one
Delivery::Failedexit records no failure at all (themax_new_tokens = 0/ zero-token finish arm), so the claim "output-layer rejections incrementfailedexactly once" does not hold there. - Minor —
emit_finished'sClosedarm incrementscompletedwith no consumer having receivedFinished. - Minor — the two Python counter suites closest to this semantic change were not run and are not listed as unrun.
1. Correctness, safety, ordering
1.1 maybe — emit_finished's Closed arm counts completion nobody observed (Minor)
helios/src/server/runtime.rs:562-573:
match self.events.try_reserve() {
Ok(permit) => {
self.outcome.record_generated();
permit.send(event);
}
Err(async_mpsc::error::TrySendError::Closed(())) => {
self.cancelled.store(true, Ordering::Release);
self.outcome.record_generated();
}
With defer_completion = false, record_generated() from PENDING targets OUTCOME_COMPLETED (runtime.rs:142-147) and does self.metrics.completed.fetch_add(1, ...) (:155-157). The receiver is gone (that is why Closed was returned), so completed rises for a request no consumer ever saw. This preserves pre-PR behaviour for direct generate/generate_many/test callers and is therefore not a regression, but it is the one place the PR's own invariant ("completion means the reader settled it", stated at runtime.rs:564-566: "Record worker completion after reserving the channel slot so an event-budget overflow fails instead of marking completed, and before sending so the consumer observes the settled state") is deliberately not held, and the description does not call it out.
Impact: small and intentional-looking, but a reviewer or a future refactor reading emit_finished as "the completion site" will get the wrong model of when completed moves. Fix: comment the arm as the direct-caller compatibility path, or route it through on_reader_drop()/record_cancelled() so the state machine is uniform (checking first whether any SDK caller depends on the old count).
1.2 The zero-token output failure is attributed to nothing (Minor)
Zero-token choices are removed from the submitted prompts, so no Generation exists for them — helios/src/server/http.rs:311-315:
if p.prompt.max_new_tokens == 0 && !p.prompt.prompt_logprobs {
zero.push(i);
} else {
prompts.push(p.prompt);
}
and http.rs:346-348 builds generations with None at those indices. Their Encoder::finish failure therefore takes the Delivery::Failed exit with no Generation to settle — http.rs:445-450:
Err(e) => {
decoders[i].abort(crate::output::Termination::ExecutionError);
let frame = encoder.failure(&e);
yield Delivery::Failed(e, frame);
return;
}
Compare the sibling arms, which do call generation.fail_output() (http.rs:402-410, :426-434, :582-590). The description's phrasing is careful ("called generation.fail_output() on any active Generation"), but the claimed result — "Output-layer rejections … increment flare_requests_failed_total exactly once" — is false for this exit: the client gets an error frame and failed does not move.
Impact: this is pre-existing (nothing was submitted for those indices before the PR either), so it is not a regression; it is an uncovered hole inside the scope the PR claims to close, and it also means a mixed n > 1 request where a zero-token sibling throws during finish and the encoder errors leaves the failing choice entirely unattributed while other choices land in cancelled. Fix: either submit zero-token choices so they own an outcome, or document this exit as unattributed in the description and in the Delivery::Failed comment block.
1.3 Verified sound in this area
RequestOutcome(runtime.rs:109-296) is genuinely absorbing:record_generatedPENDING→GENERATED|COMPLETED (:138-162), READER_DROPPED→CANCELLED|COMPLETED (:163-185);record_completedPENDING|GENERATED→COMPLETED (:191-212);record_cancelledPENDING|READER_DROPPED→CANCELLED (:214-235);record_failedPENDING|GENERATED|READER_DROPPED→FAILED (:237-258);on_reader_dropPENDING→READER_DROPPED, GENERATED→CANCELLED (:260-295). Everyfetch_addsits inside the successful CAS arm; there is no path that decrements and none that increments twice.fail_output()records FAILED beforecancel()(runtime.rs:352-357), matching its comment "Record failure before signalling cancellation so the worker cannot classify the aborted request as cancelled." A subsequentrecord_cancelledfrom any worker site is a no-op out of FAILED.emit_finishedchecksfailurefirst (runtime.rs:554-561) so a prior worker failure suppressesFinished; then reserves beforerecord_generated(), soFullgoes toself.fail(...)(:574-580) →finish_error→record_failed(:583-595) rather than tocompleted.finish_errorrecords FAILED before notifying admission/first-token/events (:589-594), closing the race where HTTP drops its receiver the instant admission fails.- All four worker cancellation sites go through
record_cancelled()(runtime.rs:1650,:1670,:1683,:1738per the head files read); no directmetrics.completed/cancelled/failed.fetch_addremains outsideRequestOutcome. Generation::drop(runtime.rs:378-383) callson_reader_drop()thencancel(), so an unconsumed deferred request lands in CANCELLED and a genuine disconnect is CANCELLED, as claimed.
No race, panic, poisoned-lock, or platform-parity issue found in the touched code: the Mutex<Option<Error>> accesses all use unwrap_or_else(|e| e.into_inner()) (runtime.rs:365-369, :554-558, :584), matching the pre-existing style; nothing touched is Unix/Windows-conditional.
2. Unintended system-level consequences
No new contention or amplification. The outcome word is one Arc<AtomicU8> per request alongside allocations that already exist at runtime.rs:1198-1245 (bounded channel, admission/first-token oneshots, owned semaphore permit). No mutex was added on the decode path; emit_finished replaces a fetch_add + emit pair with try_reserve + CAS + send, which is the same bounded-channel operation the previous emit performed (TrySendError::Full was already handled). Incoming::emit's other callers are untouched.
One genuine behaviour reversal worth naming: the bounded event budget can now convert a successful generation into a failure — runtime.rs:574-580:
Err(async_mpsc::error::TrySendError::Full(())) => {
self.fail(Error::execution(
ExecutionError::Completion,
"generation exceeded its output event budget",
));
self.cancelled.store(true, Ordering::Release);
}
This is the intended fix for defect #3 in the description (previously Full failed and could later double-count as cancelled, via record_cancelled; out of FAILED that is now a no-op), and the client is told failed. Blast radius is per-request only: fail stores into that request's failure and signals its own channels; nothing shared or coalesced is poisoned. Ordering note for a maintainer: the cancelled.store(true) after fail is now belt-and-braces (the state machine already prevents a second increment), which is harmless but makes the invariant harder to read.
Failure-propagation blast radius is contained. fail_output() is idempotent through the state machine (record_failed out of FAILED returns immediately, runtime.rs:255), so the multiple fail_output() sites on one path (http.rs:561-565 then :582-590) cannot double count even when both run for the same generation.
Admission capacity retention is unchanged in kind: emit_finished still sends through the same bounded channel, and Generation still holds _capacity until drop; deferral only changes which counter moves.
3. Architecture, contracts & charter compliance
3.1 Major — completed/cancelled change definition without a contract update
helios/src/server/metrics.rs:1076-1090 (unchanged by the PR) still promises model-generation semantics:
(
"requests_completed_total",
"Requests whose model generation completed successfully, including explicit token stops.",
&self.completed,
),
...
(
"requests_cancelled_total",
"Queued or active model requests cancelled before completion.",
&self.cancelled,
),
and docs/api.md:330 repeats it: | completed | Requests whose generation completed successfully | flare_requests_completed_total |.
Under the new machine the same counter means two things:
generate_for_output→enqueue_many(prompts, observation, true)(runtime.rs:1145-1151) used by HTTP (http.rs:333) and Decisions (protocol/decisions/mod.rs:840) parks worker completion inOUTCOME_GENERATED(runtime.rs:143-147); a reader drop from GENERATED incrementscancelled(runtime.rs:275-291), so a request whose model generation completed successfully is counted cancelled and never completed.generate/generate_many→defer_completion = false(runtime.rs:1136-1143) still records COMPLETED for the same event.
Impact: operators who plot or alert on completed/cancelled (including the #541 Grafana example, which plots completed and failed) see a definition change with no doc/HELP change and no release note. The PR's premise — "the documented meaning already matched" — is true of failed (metrics.rs:1092-1095, docs/api.md:332) but not of completed or cancelled.
Fix: update metrics.rs:1076-1090 HELP strings and docs/api.md:330 (which has no cancelled row at all — worth adding) to the end-to-end definition, and say explicitly that HTTP/Decisions now measure delivered-and-validated output while the in-process SDK entry points measure model generation.
3.2 Major — the mandatory lifecycle gate is run but not updated
docs/design-review.md:234-240:
Never touch covered code without running and updating its simulator and formal checks. Modifying the Helios scheduler, admission, speculation, cancellation, … without running—and updating when behavior, transitions, or supported bounds change—the applicable TLA+ models, Rust conformance fixtures, Kani harnesses, and scheduling simulator is a blocking design failure, regardless of whether CPU unit tests pass.
and :241-246: "When a change adds protocol states … update the model, conformance fixture, or Kani harness to cover the added domain rather than leaving it unverified."
The PR adds six protocol states (runtime.rs:109-114) and rewrites every completion/cancellation transition, but the conformance harness exercises only the non-deferred half and bypasses the new emission site:
helios/src/server/runtime/response_lifecycle_tests.rs:120-122drives the harness throughself.runtime.generate_many(...)—defer_completion = false.- The terminal action emits directly through
Incoming::emit, notemit_finished—response_lifecycle_tests.rs:151-165:
3 => {
row.producer
.as_ref()
.unwrap()
.emit(GenerationEvent::Finished { ... });
row.sent += 1;
row.terminal = 1;
}
so the try_reserve-then-record_generated ordering at runtime.rs:562-568 — the one place the event budget can turn a completion into a failure — is outside the harness entirely, as is every GENERATED → COMPLETED|CANCELLED|FAILED transition, which is precisely the half the PR exists to fix.
The PR reports the check.py (not opened) --mutations run, which is the "running" half; the "updating when transitions change" half is missing, and the repo's own wording makes that blocking regardless of the 1,884 passing CPU tests.
Fix: extend ResponseLifecycle.tla and the conformance fixture to model PENDING→GENERATED→{COMPLETED,CANCELLED,FAILED} plus reader-drop-from-GENERATED, have the harness call emit_finished and drive a &mut Generation consumer op (complete_output/fail_output/drop) instead of emit, and add a mutation guard that the terminal ordering is actually asserted.
3.3 Charter fit
Reads acceptable on the other clauses: root cause is fixed at the site where the counters live (metrics.rs untouched, no new flag, no config, no per-model branch, no wire-schema change). The description has all four required parts. No performance claim is made, so the #210 benchmark rule does not apply. The internal-API reduction (generate_observed → #[cfg(test)] at runtime.rs:1131-1134, generate_many_observed deleted) is an API change the description glosses as "removing the single-caller wrapper" — not a defect, but it deserves a line in "What Changed" since generate_for_output becomes the required entry point for anything producing user-visible output.
4. Tests & claim accuracy
Backed by real code: the terminal-overflow and drop-ordering unit tests, the 3×3×2×128 Barrier concurrency test asserting exactly one increment, and the HTTP↔Worker integration tests described all exist in the head files and cover the interleavings that matter for the deferred and direct paths (helios/src/server/runtime.rs tests region, helios/src/server/runtime/phase_tests.rs (not opened) integration region).
Not run and not disclosed as unrun (Minor): the two Python suites whose assertions sit exactly on the counters whose semantics change — tests/server/test_protocols.py:663-676 (an n=4 streaming disconnect must raise flare_requests_cancelled_total) and tests/server/test_decisions.py:221-263 (cancelling a decision client mid-score() must raise cancelled). Reading the code, both probably still hold: the n=4 client reads one line and cancels, so no choice consumes Finished first and each drop lands PENDING→READER_DROPPED→CANCELLED (runtime.rs:163-185); score() holds one Generation in PENDING (protocol/decisions/mod.rs:840-886), so the drop lands READER_DROPPED and the worker's record_cancelled increments. But the PR's evidence lists only cargo and check.py (not opened), so this is unverified runtime behaviour on the exact contract being changed. Fix: run both suites (or list them as unrun in Limitations) and adjust expectations to the end-to-end definition.
Claim accuracy: two places where the description overstates:
- "Output-layer rejections … increment
flare_requests_failed_totalexactly once" — not for the zero-token finish arm (§1.2). - The description presents the metric meaning as already documented; that holds for
failedonly (§3.1).
Everything else I checked in the description matches the code, including the defer_completion matrix (runtime.rs:1136-1151), the fail-before-cancel claim, the "fail-then-cancel cannot double count" claim, and the unchanged parallel_tool_calls: false behaviour (http.rs:571-575 still just generation.cancel()).
Open questions / not found
- Whether the
docs/design-review.md:241-246"added protocol states" clause is satisfied by runningcheck.py(not opened) without extending the model — I judge not (§3.2), but no maintainer has stated a position. - Merge order against #548 / #560 (same three files, same
GenerationEvent::Finished) and against the author's own #691 (sameIncoming/Generationstructs, samewait_for_first_tokencall site). None of these reference #692 and #692 references none of them. - Whether any in-crate non-test producer of user-visible output still calls
generate/generate_manyand therefore keeps the old immediate-completion semantics — I converted-verified onlyhttp.rs:333andprotocol/decisions/mod.rs:840; a crate-wide sweep for remaininggenerate(callers inhelios/src/serveroutside tests was not completed. - Whether
docs/api.md:700-702's "cancelled rather than completed, despite the successful API response" note for the parallel-tool-limit path should be amended: the machinery it describes is rewritten, the outcome it documents is not. - Whether
emit_finished'stry_reserve()can hand back a permit that is later dropped without sending, leaving the request in GENERATED — nothing in the head files drops and discards the reservedPermit, and the tests coverFullandClosedbut not a reservation dropped without send. - No CI on
348c06c, no review, no label, no maintainer engagement; all quantitative evidence remains self-reported.