Skip to content

helios: count output-layer stream failures under requests_failed_total - #692

Open
jcartu wants to merge 1 commit into
NVIDIA:mainfrom
jcartu:fix/output-stream-failure-accounting
Open

jcartu wants to merge 1 commit into
NVIDIA:mainfrom
jcartu:fix/output-stream-failure-accounting

Conversation

@jcartu

@jcartu jcartu commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #679

Why

In Helios, flare_requests_failed_total counts model requests failed by admission, execution, grammar, or output processing (helios/src/server/metrics.rs). Previously, only Incoming::finish_error inside the model worker (helios/src/server/runtime.rs) incremented metrics.failed, while the worker eagerly incremented metrics.completed before trailing stop flushes, GenerationEvent::Finished channel delivery, or output decoding ran, and incremented metrics.cancelled whenever cancelled was set or the event channel closed.

When the HTTP output layer rejected a streamed or buffered response—for example, when the ChatML tool parser (helios/src/output/chatml.rs) rejected an empty or duplicate parameter name or rejected an incomplete tool call at end-of-sequence—http::generate (helios/src/server/http.rs) encoded an error frame, returned Delivery::Failed, and dropped its Generation receiver. Three accounting defects followed:

  1. Mid-stream output rejections while the worker remained active caused Generation::drop and Incoming::emit (TrySendError::Closed) to set cancelled, so the worker incremented flare_requests_cancelled_total while flare_requests_failed_total remained zero.
  2. Output rejections occurring after the worker emitted GenerationEvent::Finished (during end-of-sequence decoding in Decoder::finish / Encoder::finish, or when buffered tokens raced ahead of the HTTP task), as well as terminal event-budget overflow during stop flushing or Finished emission, left flare_requests_completed_total incremented while flare_requests_failed_total stayed zero.
  3. Worker event-budget overflow (TrySendError::Full) called self.fail(...) and then set cancelled = true, allowing a subsequent Worker::admit() pass to increment flare_requests_cancelled_total on top of flare_requests_failed_total.

A shared atomic outcome state machine between Incoming and Generation with deferred completion for output-layer consumers resolves all three cases without decrementing monotonic Prometheus counters.

What Changed

  • helios/src/server/runtime.rs:
    • Added RequestOutcome, a monotonic AtomicU8 state machine (PENDING, GENERATED, READER_DROPPED, COMPLETED, CANCELLED, FAILED) shared by each (Incoming, Generation) pair, driven by a single CAS helper (RequestOutcome::transition). Each metric counter (completed, cancelled, failed) increments only on a compare-exchange into its absorbing terminal state, so every request increments at most one counter at most once and never decrements a counter.
    • Replaced premature metrics.completed increments with Incoming::emit_finished, called after scheduler lookup and trailing stops.finish() emission. emit_finished suppresses Finished if a prior worker failure is already recorded and uses try_reserve() to reserve the bounded channel slot before calling record_generated() and sending Finished. Both emit_finished and emit share Incoming::event_budget_exceeded() on TrySendError::Full so terminal event-budget overflow fails the request instead of recording completion.
    • Added ModelRuntime::generate_for_output, which sets defer_completion = true so normal worker completion parks in GENERATED until the consumer validates output and calls Generation::complete_output(), rejects output and calls Generation::fail_output(), or drops Generation (on_reader_drop()).
    • When defer_completion is true, dropping Generation without confirming output validation transitions GENERATED -> CANCELLED (in on_reader_drop()) or READER_DROPPED -> CANCELLED (in record_generated()), so unread client disconnects and aborted multi-choice sibling responses count as cancelled rather than completed. Direct ModelRuntime::generate, generate_many, and test-only generate_observed callers retain immediate worker completion (defer_completion = false, settling PENDING | READER_DROPPED -> COMPLETED) while still using RequestOutcome so event-budget overflow cannot double-count failure and cancellation.
    • Reordered Incoming::finish_error to record FAILED before notifying admission, first-token, and event channels, moved self.outcome.record_cancelled() into Incoming::finish_cancelled before emitting GenerationEvent::Finished, and kept direct record_cancelled() calls on pending-drop cancellation paths in Worker::admit.
  • helios/src/server/http.rs:
    • Switched HTTP request submission to state.model.generate_for_output (removing the single-caller generate_many_observed wrapper).
    • On GenerationEvent::Finished, settled generations[index].take() with complete_output() when decoding and encoding succeed or fail_output() when they return an error.
    • On every Delivery::Failed exit (wait_for_first_token, echo application, zero-token finish, and the event loop's single Err(e) arm covering both mid-stream and Finished errors), aborted the failing decoder once with Termination::ExecutionError and called generation.fail_output() on any active Generation before yielding Delivery::Failed.
  • helios/src/server/protocol/decisions/mod.rs:
    • Switched decision scoring to generate_for_output and settled each Generation with complete_output() on success or fail_output() on probability validation, event-count, or channel errors.
  • helios/src/server/metrics.rs and docs/api.md:
    • Updated Prometheus # HELP descriptions (flare_requests_completed_total, flare_requests_cancelled_total), Snapshot::completed docs, and the docs/api.md metrics documentation to reflect validated output completion and unread/unvalidated disconnects for served HTTP and Decisions traffic while noting that direct in-process ModelRuntime::generate* callers retain model-generation completion semantics.
  • helios/src/server/runtime/response_lifecycle_tests.rs:
    • Switched both terminal emission call sites (the observed-edge ResponseLifecycle harness and the HTTP terminal-frame retention test) from raw emit(GenerationEvent::Finished { ... }) to emit_finished(GenerationEvent::Finished { ... }) so the ResponseLifecycle conformance suite exercises the production terminal entry point.
  • helios/src/server/runtime.rs and helios/src/server/runtime/phase_tests.rs:
    • Added unit tests for terminal event-budget overflow (both direct and deferred streams, on trailing stop tokens and on Finished), deferred vs direct reader-drop orderings, and a 2-thread Barrier-synchronized concurrency test across all worker/consumer outcome pairs.
    • Added HTTP-to-Worker integration tests (sharing a wait_for_admitted helper) covering streaming ChatML duplicate-parameter rejections on /v1/chat/completions, /v1/messages, and /v1/responses; mid-stream and end-of-sequence output rejections after worker completion (streaming and non-streaming); genuine client disconnects before and after worker completion; normal streaming and non-streaming completions; and multi-choice (n = 2) output failures with both still-active and already-generated sibling choices.

Claimed Result

  • Output-layer rejections across streaming and non-streaming Chat, Completions, Messages, Responses, and Decisions endpoints increment flare_requests_failed_total exactly once and leave flare_requests_cancelled_total and flare_requests_completed_total unchanged, including when worker generation finishes before output decoding rejects buffered events or when terminal emission overflows the event budget.
  • Genuine client disconnects without an output error (whether before worker generation completes or after worker generation completes but before output validation) increment flare_requests_cancelled_total without incrementing flare_requests_failed_total or flare_requests_completed_total.
  • Normal validated completions increment flare_requests_completed_total without double-counting, and multi-choice (n > 1) output failures record the failing choice under failed while cancelling undelivered sibling choices (whether still active or already generated in the channel) under cancelled.
  • Response admission-capacity retention and ResponseLifecycle.tla producer/reader ownership invariants remain unchanged.

Supporting Evidence and Limitations

All commands below ran on Linux CPU with non-gated chat templates prepared by tests/frontend/prepare_templates.py via FLARE_TEST_TEMPLATE_DIR and a 512 MiB locked-memory limit (parallel Engram staging tests exceed 64 MiB when all unit tests run concurrently):

  • cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server: 1,884 passed, 0 failed, 84 ignored across lib (1,822 passed, 47 ignored) and 14 integration test binaries (62 passed, 37 ignored), including the added unit, 2-thread concurrency, and HTTP/Worker integration tests.
  • cargo test --locked --release --manifest-path flare/Cargo.toml: 254 passed, 0 failed, 4 ignored.
  • cargo test --locked --release --manifest-path flare-cli/Cargo.toml: 245 passed, 0 failed, 3 ignored.
  • python3 verification/helios-lifecycle/check.py --tlc-jar <path/to/tla2tools.jar> --mutations: exited 0; all 8 TLA+ models passed, Rust trace conformance checked 1,710 transitions against Lifecycle.tla, 1,291 against RankProtocol.tla, 7,940 against DispatchRing.tla, 8,490 against OffloadTransfer.tla, 222,817 against CacheOwnership.tla, 13,566 against Speculation.tla, 365,508 against ResponseLifecycle.tla (states=65989 edges=365508 depth=10, with terminal emission routed through Incoming::emit_finished), and 68 against CheckpointReservation.tla, all 13 TLA+ mutations, 26 Rust guard mutations (including unread response admission, unfinished producer admission, generation group admission, and undersized response queue), and 1 observed-edge safety violation (DispatchRing SlotReuseSafe) were detected, and all conformance suites passed after source restoration.

Limitations:

  • Checkpoint- and GPU-gated integration tests (84 ignored in helios, 4 in flare, 3 in flare-cli) and live GPU serving through flare run were not run on this CPU-only verification pass.
  • Kani harnesses were not run because no completion-vector or state-view validators were modified.

Discord: jcartu

@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 692.
Case File Intake Report

Future reviews will auto-run 90 minutes after code updates are pushed.

  • Re-review sooner: Call @flare-autobot after push.
  • Opt-out: Include #autobot:ignore in the PR or any comment.

@flare-autobot flare-autobot added area:api Serving API, protocol encoding, tool parsing, and client-visible behavior. bug Something isn't working priority:P2 Normal bug priority: workflow failure or diagnosis with narrower impact or an available workaround. triage:review Proposed change needs code review; this does not imply merge readiness. labels Dec 2, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

The core fix for #679 is technically sound — the shared RequestOutcome atomic state machine eliminates mid-stream cancellation and post-generation output-rejection misattribution with no correctness or concurrency blockers found. Before merge, update the metric # HELP/API docs for the new deferred completed/cancelled semantics, route the ResponseLifecycle harness through emit_finished, and get CI green on head 348c06c.

  • Blockers: 0 · Should fix: 2 · Subtract/Simplify: 2 · Nits: 3
Walkthrough
  • helios/src/server/runtime.rs: Adds RequestOutcome (:109-296), a six-state monotonic AtomicU8 (PENDING, GENERATED, READER_DROPPED, COMPLETED, CANCELLED, FAILED) where each Prometheus counter increments only inside a successful CAS into an absorbing terminal state. Replaces eager metrics.completed increments with Incoming::emit_finished (:553-582), which suppresses Finished after a prior worker failure and reserves the channel slot via try_reserve() before recording generation. Adds ModelRuntime::generate_for_output (:1145-1151, defer_completion = true) while keeping generate/generate_many on immediate worker completion. Orders finish_error (:583-595) to record FAILED before waking consumers and routes all four worker cancellation sites in Worker::admit (:1650, :1670, :1683, :1738) through record_cancelled(). Adds unit tests for overflow/drop orderings and a 2-thread Barrier concurrency test (:4471-4649).
  • helios/src/server/http.rs: Switches submission to generate_for_output (:328-334), settles GenerationEvent::Finished with complete_output() or fail_output() (:561-566), and aborts the decoder with Termination::ExecutionError (idempotent at helios/src/server/output.rs:384-396) plus calls generation.fail_output() on every Delivery::Failed exit holding an active Generation (:402-410, :426-434, :582-590).
  • helios/src/server/protocol/decisions/mod.rs: Switches score() (:830-893) to generate_for_output and explicitly settles every exit with complete_output() or fail_output().
  • helios/src/server/runtime/phase_tests.rs: Adds four tokio HTTP-to-Worker integration tests (:8441-9021) covering ChatML duplicate-parameter rejections across /v1/chat/completions, /v1/messages, and /v1/responses; mid-stream and at-EOS failures after worker completion (streaming and non-streaming); genuine client disconnects before and after worker completion; normal completions; and multi-choice (n = 2) output failures with both active and already-generated siblings.
Merge Risk: Medium · up to 348c06c
  • Hot-path request-outcome rewrite: Replaces every request completion, cancellation, and failure counter site across helios/src/server/runtime.rs, helios/src/server/http.rs, and helios/src/server/protocol/decisions/mod.rs with a shared Arc<AtomicU8> state machine (RequestOutcome), changing when completed and cancelled increment for all HTTP and Decisions traffic.
  • No CI runs on head (348c06c): All test and lifecycle-check results are currently self-reported and await CI execution.
  • Active conflict surface: Touches the exact same structs (Incoming, Generation), GenerationEvent::Finished sites, and wait_for_first_token path as open PRs #691 (same author), #548, and #560.
Pre-merge checks: ✅ 2 passed · ⚠️ 2 warnings
  • ✅ Security / malicious screen: No prompt injection, suspicious I/O, unsafe code, or trust-boundary weakening found in the diff or PR conversation.
  • ✅ Charter & value fit: Fixes operator-reported P2 bug Output-layer stream failures (tool-call parse rejection) are counted as cancellations; requests_failed_total stays 0 #679 at the root cause with no new config flags, wire changes, or per-model branches; PR description includes all four required sections.
  • ⚠️ Related / duplicate / conflict check: Genuinely additive (not superseded), but textually overlaps open PRs #691 (same author, Incoming/Generation and wait_for_first_token), #548, and #560 (same counter/finish sites); needs rebase coordination.
  • ⚠️ Tests & verification evidence: Substantial, well-isolated CPU unit/concurrency/integration tests exist and exercise real production http::generate/Worker/Decoder/Encoder paths, and check.py --mutations is reported passing, but no GitHub CI checks have run on head 348c06c yet.

Have your agent review the Full Review for complete verified findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

@jcartu
jcartu force-pushed the fix/output-stream-failure-accounting branch from 348c06c to 7f29869 Compare December 2, 2026 22:17
@jcartu

jcartu commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@flare-autobot Addressed every review item in 7f298698:

  • Should fix Congratulations! #1 (helios/src/server/metrics.rs, docs/api.md): Updated Prometheus # HELP descriptions (flare_requests_completed_total, flare_requests_cancelled_total), Snapshot::completed docs, and the docs/api.md metrics documentation (including flare_requests_cancelled_total and output-failure/event-budget detail on failed) to describe validated output completion and unread/unvalidated disconnects for served HTTP/Decisions traffic while noting that direct in-process ModelRuntime::generate* callers retain model-generation completion semantics.
  • Should fix flare run fails at "Prepare execution": cuGraphAddKernelNode_v2 CUDA_ERROR_INVALID_VALUE (qwen3.8-flash TP2, RTX PRO 5000 Blackwell 48 GB) #2 (helios/src/server/runtime/response_lifecycle_tests.rs): Switched both terminal emission sites (the ResponseLifecycle observed-edge harness and the HTTP terminal-frame retention test) from raw .emit(GenerationEvent::Finished { ... }) to .emit_finished(GenerationEvent::Finished { ... }).
  • Subtract / Simplify Congratulations! #1 (helios/src/server/runtime.rs): Collapsed the five RequestOutcome CAS loops into a single private transition helper with identical memory orderings (Acquire/AcqRel/Relaxed) and transition behavior.
  • Subtract / Simplify flare run fails at "Prepare execution": cuGraphAddKernelNode_v2 CUDA_ERROR_INVALID_VALUE (qwen3.8-flash TP2, RTX PRO 5000 Blackwell 48 GB) #2 (helios/src/server/runtime.rs): Extracted a shared Incoming::event_budget_exceeded helper used by both emit_finished and emit on TrySendError::Full.
  • Nits (helios/src/server/runtime.rs, helios/src/server/runtime/phase_tests.rs): Collapsed the 7 admission-polling loops in phase_tests.rs into wait_for_admitted(&mut worker, count) (5s timeout), added a clarifying comment on emit_finished's Closed arm documenting READER_DROPPED settlement for deferred vs direct callers, and moved self.outcome.record_cancelled() into Incoming::finish_cancelled while preserving direct record_cancelled() calls on pending-drop paths.

Re-verified on Linux CPU (non-gated templates via FLARE_TEST_TEMPLATE_DIR, 512 MiB memlock):

  • cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server: 1,884 passed, 0 failed, 84 ignored
  • cargo test --locked --release --manifest-path flare/Cargo.toml: 254 passed, 0 failed, 4 ignored
  • cargo test --locked --release --manifest-path flare-cli/Cargo.toml: 245 passed, 0 failed, 3 ignored
  • python3 verification/helios-lifecycle/check.py --tlc-jar <tla2tools.jar> --mutations: all 8 TLA+ models and conformance checks passed (365,508 observed transitions on ResponseLifecycle.tla via emit_finished), all 40 mutations detected (13 TLA+, 26 Rust guards, 1 observed-edge violation), and conformance re-verified after restore.

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Ready To Merge

Commit 7f298698 cleanly resolves every Round 1 item — metrics # HELP/API docs, routing terminal emission through emit_finished, collapsing the five CAS loops into RequestOutcome::transition, and shared test helpers — with no correctness, concurrency, or performance regressions. The shared RequestOutcome atomic latch closes all three #679 misattribution paths by construction across streaming/non-streaming HTTP and Decisions endpoints.

  • Blockers: 0 · Should fix: 0 · Subtract/Simplify: 2 · Nits: 1
Walkthrough
  • helios/src/server/runtime.rs: Adds RequestOutcome (:109-207), a six-state monotonic AtomicU8 (PENDING, GENERATED, READER_DROPPED, COMPLETED, CANCELLED, FAILED) driven by one CAS helper transition (:138-156) that increments each Prometheus counter only on a successful CAS into its absorbing terminal state. Premature metrics.completed increments at :2209/:2506 replaced by Incoming::emit_finished (:465-492), which suppresses Finished after a prior worker failure and reserves the bounded channel slot via try_reserve() before record_generated(). Shares event_budget_exceeded (:493-501) between emit_finished and emit (:545-547), orders finish_error (:502-514) to record FAILED before notifying channels, folds record_cancelled() into finish_cancelled (:434-444), and adds ModelRuntime::generate_for_output (:1058-1064, defer_completion = true) while public generate/generate_many keep immediate worker completion. New unit and 2-thread Barrier concurrency tests at :4383-4561.
  • helios/src/server/http.rs: Switches HTTP submission to generate_for_output (:333), settles GenerationEvent::Finished via generations[index].take() with complete_output()/fail_output() (:561-566), and aborts the failing decoder plus calls fail_output() on active Generation handles across all Delivery::Failed exits (:402-410, :426-434, :582-589).
  • helios/src/server/protocol/decisions/mod.rs: score() (:830-893) now uses generate_for_output and settles every exit path with complete_output() (:871) or fail_output() (:845, :853, :865, :879, :883), preserving Drop -> on_reader_drop -> CANCELLED on client disconnect.
  • helios/src/server/metrics.rs & docs/api.md: Updates Snapshot::completed (metrics.rs:91), Prometheus # HELP strings for requests_completed_total and requests_cancelled_total (metrics.rs:1076-1090), and API metrics docs (docs/api.md:330,332,349-354) to cover validated output completion, unread/unvalidated disconnects, output-decoding/event-budget failures, and direct in-process ModelRuntime::generate* semantics.
  • helios/src/server/runtime/response_lifecycle_tests.rs & phase_tests.rs: Both terminal emission sites in response_lifecycle_tests.rs (:155, :372) route through emit_finished; adds four isolated HTTP-to-Worker integration tests (phase_tests.rs:8647-8989, shared wait_for_admitted helper at :8632-8645) covering ChatML duplicate-parameter rejections across Chat/Messages/Responses, post-worker-completion failures, client disconnects before and after worker completion, normal completions, and multi-choice (n = 2) sibling cancellation.
Merge Risk: Medium · up to 7f29869
  • All-request terminal accounting path: Replaces every completed, cancelled, and failed counter increment across helios/src/server/runtime.rs, helios/src/server/http.rs, and helios/src/server/protocol/decisions/mod.rs with the shared RequestOutcome state machine, changing when completed and cancelled settle for all served HTTP and Decisions traffic.
  • Active conflict surface: Textually overlaps open PRs #691 (same author, Incoming/Generation and http.rs), #548, and #560 (same counter and finish paths), requiring straightforward rebase coordination.
  • CI confirmation pending on head 7f298698: Author CPU test runs and check.py --mutations are self-reported (run locally at 512 MiB memlock vs CI's 64 MiB prlimit in .github/workflows/native-serving.yml:62-63), so GitHub CI checks should be verified green on 7f298698 before merge.
Pre-merge checks: ✅ 3 passed · ⚠️ 2 warnings
  • ✅ Security / malicious screen: No prompt injection, suspicious I/O, unsafe code, or trust-boundary weakening found in the diff or PR discussion.
  • ✅ Charter & value fit: Fixes operator-reported P2 bug #679 at the root cause in the right layer with no new config flags, wire changes, or per-model branches; PR description contains all four required sections.
  • ⚠️ Related / duplicate / conflict check: Genuinely additive (not superseded), but overlaps open PRs #691, #548, and #560 across runtime.rs, http.rs, metrics.rs, docs/api.md, phase_tests.rs, and response_lifecycle_tests.rs; rebase coordination needed.
  • ⚠️ Tests & verification evidence: Unit, 2-thread concurrency, and real-pipeline HTTP↔Worker integration tests are well isolated with no global-state hazards, and check.py --mutations is reported passing; verify GitHub CI (native-serving at 64 MiB memlock and helios-lifecycle) passes on 7f298698 before merge (note .github/workflows/helios-lifecycle.yml:34 runs check.py without --mutations).

Have your agent review the Full Review for complete verified findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

@jcartu
jcartu force-pushed the fix/output-stream-failure-accounting branch from 7f29869 to 2e9bfa5 Compare December 3, 2026 10:06
@jcartu

jcartu commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main (3d1614cc), resolving the helios/src/server/http.rs conflict with #689 (generate_for_output preserves the continuous-usage timestamp observation path). Local cargo test (2,409 passed across flare-helios, flare, and flare-cli, 0 failed) and touched-file clippy (zero new warnings, no unused_mut) are green on 2e9bfa59. Note: overlaps #691 in the chat first-token block; happy to rebase whichever lands second. Requesting re-review.

@jcartu
jcartu force-pushed the fix/output-stream-failure-accounting branch from 2e9bfa5 to 1419fcf Compare December 3, 2026 18:50
@jcartu

jcartu commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Rebased onto main (452c3686) at a04bfee3, resolving the append-only test conflict at the end of helios/src/server/runtime/phase_tests.rs (re-anchored below worker_admit_isolates_admission_and_stop_matcher_failures_without_killing_worker) with zero code/test diff drift. Local --locked cargo test passed (full suite on def91796: 1,941 flare-helios + 255 flare + 246 flare-cli; phase_tests on 452c3686: 148 passed, 0 failed).

Still overlaps #691/#705 at the http.rs / phase_tests.rs tails; will re-rebase in merge order.

Discord: jcartu

When the Helios HTTP output layer rejects a streamed or buffered response—for
example, when the ChatML tool parser rejects an empty or duplicate parameter
name or rejects an incomplete tool call at end-of-sequence—`http::generate`
encodes an error frame, returns `Delivery::Failed`, and drops its `Generation`
receiver. Previously, only `Incoming::finish_error` on the model worker
incremented `flare_requests_failed_total`, while worker completion eagerly
incremented `flare_requests_completed_total` before trailing stop flushes,
`GenerationEvent::Finished` channel delivery, or output decoding ran, and
worker cancellation incremented `flare_requests_cancelled_total` whenever
`cancelled` was set or the event channel closed. As a result, mid-stream output
rejections were miscounted as cancellations while `flare_requests_failed_total`
stayed zero, output rejections after worker completion or event-budget overflow
on terminal events were miscounted as completed requests, and event-budget
overflow could increment both failed and cancelled counters when `admit()`
subsequently observed `cancelled`.

This change introduces an atomic `RequestOutcome` state machine shared between
each worker `Incoming` and consumer `Generation` in
`helios/src/server/runtime.rs`:
- Each request transitions through monotonic atomic states (`PENDING`,
  `GENERATED`, `READER_DROPPED`, `COMPLETED`, `CANCELLED`, `FAILED`) via a
  single CAS helper (`RequestOutcome::transition`) and increments at most one
  of `completed`, `cancelled`, or `failed` without ever decrementing a counter.
- `Incoming::emit_finished` runs after scheduler lookup and trailing
  `stops.finish()` emission, suppresses `Finished` if a prior failure is
  already recorded, and uses `try_reserve()` to reserve the channel slot before
  calling `record_generated()` and sending `Finished`. Both `emit_finished` and
  `emit` share `Incoming::event_budget_exceeded()` on `TrySendError::Full` so
  terminal event-budget overflow records `FAILED` instead of
  `GENERATED`/`COMPLETED`.
- `ModelRuntime::generate_for_output` enables deferred completion for consumers
  that run output decoding and validation (`helios/src/server/http.rs` and
  `helios/src/server/protocol/decisions/mod.rs`), parking worker completion in
  `GENERATED` until the consumer calls `Generation::complete_output()`, calls
  `Generation::fail_output()`, or drops `Generation` (`on_reader_drop()`).
- When `defer_completion` is true, dropping `Generation` without confirming
  output validation settles `GENERATED -> CANCELLED` (in `on_reader_drop()`) or
  `READER_DROPPED -> CANCELLED` (in `record_generated()`), so unread client
  disconnects and aborted multi-choice sibling responses count as cancelled
  rather than completed. Direct `ModelRuntime::generate` and `generate_many`
  callers keep immediate worker completion (`defer_completion = false`,
  settling `PENDING | READER_DROPPED -> COMPLETED`) while still using
  `RequestOutcome` so event-budget overflow cannot double-count failure and
  cancellation.
- On every `Delivery::Failed` exit in `helios/src/server/http.rs`
  (`wait_for_first_token`, echo application, zero-token finish, and the event
  loop's single error handler covering both mid-stream and `Finished` errors),
  the failing decoder is aborted once with `Termination::ExecutionError` and
  any associated `Generation` calls `fail_output()`, which transitions the
  outcome to `FAILED` before setting `cancelled` so the worker releases
  scheduler resources without counting the request as cancelled.
- `Incoming::finish_cancelled` calls `record_cancelled()` before emitting
  `GenerationEvent::Finished`, pending-drop cancellation paths call
  `record_cancelled()` directly, and `Incoming::finish_error` calls
  `record_failed()` before notifying admission, first-token, and event
  channels.
- Updated Prometheus `# HELP` descriptions and `Snapshot::completed` docs in
  `helios/src/server/metrics.rs` and the metrics documentation in `docs/api.md`
  to describe validated output completion and unread/unvalidated disconnects
  for served HTTP and Decisions traffic while noting that direct in-process
  `ModelRuntime::generate*` callers retain model-generation completion
  semantics.
- Routed both terminal emission sites in
  `helios/src/server/runtime/response_lifecycle_tests.rs` through
  `Incoming::emit_finished` so the `ResponseLifecycle` conformance suite
  exercises the production terminal entry point.

As a result, output-layer failures across streaming and non-streaming Chat,
Completions, Messages, Responses, and Decisions endpoints increment
`flare_requests_failed_total` exactly once without incrementing
`flare_requests_cancelled_total` or `flare_requests_completed_total`, including
when worker generation finishes before output decoding rejects buffered events
or when terminal emission overflows the event budget. Genuine client
disconnects (before or after worker generation completes when output validation
has not run) increment `flare_requests_cancelled_total`, normal validated
completions increment `flare_requests_completed_total`, and multi-choice
(`n > 1`) failures count the failing choice as failed while cancelling
undelivered sibling choices.

Validation on Linux CPU (non-gated chat templates prepared by
`tests/frontend/prepare_templates.py` via `FLARE_TEST_TEMPLATE_DIR`, 512 MiB
locked-memory limit for parallel Engram staging tests):
- `cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server`:
  1,884 passed, 0 failed, 84 ignored (including unit, 2-thread barrier
  concurrency, and HTTP/Worker integration tests covering terminal event-budget
  overflow for direct and deferred streams, deferred vs direct reader-drop
  orderings, ChatML duplicate-parameter stream rejections across
  Chat/Messages/Responses, post-worker-completion and end-of-sequence output
  rejections, genuine client disconnects before and after worker completion,
  normal completions, and multi-choice `n = 2` output failures with both active
  and already-generated sibling choices).
- `cargo test --locked --release --manifest-path flare/Cargo.toml`:
  254 passed, 0 failed, 4 ignored.
- `cargo test --locked --release --manifest-path flare-cli/Cargo.toml`:
  245 passed, 0 failed, 3 ignored.
- `python3 verification/helios-lifecycle/check.py --tlc-jar <tla2tools.jar> --mutations`:
  passed all 8 TLA+ models and Rust trace-conformance checks (including 365,508
  observed Rust transitions against `ResponseLifecycle.tla` routed through
  `Incoming::emit_finished`), detected all 13 TLA+ mutations, 26 Rust guard
  mutations (including `unread response admission`,
  `unfinished producer admission`, `generation group admission`, and
  `undersized response queue`), and 1 observed-edge safety violation
  (`DispatchRing SlotReuseSafe`), restored sources, and re-verified all
  conformance suites cleanly.

Material limitations: checkpoint- and GPU-gated integration tests (84 ignored
in `helios`, 4 in `flare`, 3 in `flare-cli`), live GPU serving, and Kani
harnesses (no completion-vector or state-view validators were modified) were
not run.

Signed-off-by: Joshua Cartu <jcartu@users.noreply.github.com>
Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b
@jcartu
jcartu force-pushed the fix/output-stream-failure-accounting branch from 1419fcf to a04bfee Compare December 3, 2026 18:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:api Serving API, protocol encoding, tool parsing, and client-visible behavior. bug Something isn't working priority:P2 Normal bug priority: workflow failure or diagnosis with narrower impact or an available workaround. triage:review Proposed change needs code review; this does not imply merge readiness.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Output-layer stream failures (tool-call parse rejection) are counted as cancellations; requests_failed_total stays 0

2 participants