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

Raw Markdown for agents: https://autobot.eidonix.com/api/v1/cases/70410b34-0086-4ca8-8979-f65349ff5031

Opened by a workflow run, Dec 2, 2026 4:24 PM EST. decide malicious: all_clear (100%): No malicious content found

explore

Author: jcartu (CONTRIBUTOR; 3 merged, 10 open PRs in 180 days, mostly docs and helios/src; part of a seven-PR same-day batch #686–#693; Discord jcartu) Motivation: When Helios' output layer rejects a generated response (e.g. a ChatML tool-call parser rejection), the model worker only sees the reader dropping and counts the request as cancelled, so flare_requests_failed_total stays at zero and operators see failures as user aborts. Issue #679 reported exactly that, with journal evidence, and says only the accounting is wrong, not the rejection behaviour. Scale: +1068 / −32 lines in 4 files Proposal:

Full report · Notes

Value Proposition

Value Proposition — PR #692: count output-layer stream failures under requests_failed_total

Charter alignment — strong

The change fixes a metric-attribution defect reported by an operator (#679, priority:P2, with a journal timeline and a code trace at a3c80e19) and lands where the counters actually live. The documented contract already promised the fixed behaviour (docs/api.md:332, metrics.rs:1092-1095), so this closes a docs-vs-implementation gap rather than inventing a new contract. No per-model branch, no new flag, no default moved, no wire/schema change — so the "runtime stays small and model-agnostic" and "smallest footprint" rules are not engaged. Fixing the root cause (a single absorbing terminal outcome) instead of retrying or swallowing an error matches "bug fixes need to address the root cause (#397)." The description has all four required parts.

Novelty & status — additive

No commits on main since the branch point (c513e46) touch the four changed files, so this is not obsolete. #548/#560 (WynnD) rewrite the same counters for a different purpose (per-request histograms, vLLM-parity timing); neither addresses #679's attribution, so this is genuinely additive, not superseded. Notably, #548's review thread already flagged a "runtime says cancelled, HTTP returns success" divergence that #692 changes the machinery for while leaving docs/api.md:700-702 and the parallel_tool_calls: false path untouched.

Value vs maintenance cost — real, but expensive

Beneficiaries are /metrics and alerting consumers. Weakener: #541's shipped Grafana example plots only completed and failed, so both the bug and part of the fix are invisible on the documented dashboard; no performance claim is made either.

Cost is large for a metrics fix: +1068/−32, a new Arc<AtomicU8> state machine in the hot worker path, rewritten completion sites for all HTTP and Decisions traffic, and undocumented internal API changes (generate_many_observed deleted, generate_observed now #[cfg(test)]). No CI has run on 348c06c; all evidence is self-reported. The deferred half of the state machine — the half the PR exists for — has no conformance transition in ResponseLifecycle.tla/fixtures, which engages the blocking-design clause at docs/design-review.md:234-245. The Python counter assertions closest to this behaviour (tests/server/test_protocols.py:676, test_decisions.py:230-261) were neither run nor disclosed as skipped. Coordination risk is high: textual conflicts with #548, #560 and the author's own #691.

Verdict: Worth it with changes

Genuinely additive, correctly located and root-cause-driven. Before merge, require: CI green on head; the Python counter suites run (and updated if deferred completion shifts their expectations); an explicit statement on whether the new PENDING→GENERATED→{COMPLETED,CANCELLED,FAILED} transitions extend ResponseLifecycle or fall under the "no bound change" exemption; and a rebase plan against #548/#560/#691.

No prompt-injection attempt was found in the reviewed material.

Full report Decide Value: yes (100%): This change is worth reviewing: it provides value to the project in line with its charter.

Classify intake

Selected: triage:review, priority:P2, bug, area:api

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

Applied: +triage:review, +priority:P2, +bug, +area:api

Subtraction and simplicity

Subtraction/Simplicity review of PR #692 (helios outcome accounting). The diff is mostly principled and adds no config knob, env var, or compatibility shim, but it carries four clearly removable pieces of complexity.

S1 — six hand-rolled CAS loops differing only in constants (high). runtime.rs:138-295 repeats the same load/compare_exchange_weak loop; record_completed (:191-212), record_cancelled (:214-235), record_failed (:237-258) and the GENERATED arm of on_reader_drop (:275-291) differ only in the accepted from set, target state, and which AtomicU64 counter is bumped (metrics.rs:228-231). One settle(&self, from: &[u8], to: u8, counter: &AtomicU64) turns ~150 lines into ~40 with identical semantics.

S2 — delete defer_completion and the non-deferred half (high). The flag (runtime.rs:123-126) is threaded into enqueue_many (:1153-1158) and produces four branches in record_generated (:143-147, :155-157, :164-168, :176-180). Its only true callers are the two production entry points (http.rs:333, decisions/mod.rs:840); every false caller is a test (phase_tests.rs:3770/3784/3824/3857/3864/3869, response_lifecycle_tests.rs:122). Collapsing it also puts the TLA conformance harness on the deferred transitions docs/design-review.md:209-240 (not opened) cares about. This is the one AGENTS.md:188-193 hit (switch with one live value).

S3 — copied event-budget overflow arm (medium). runtime.rs:574-580 and :626-634 are byte-identical including the error literal at :577/:631; extract one event_budget_exceeded(). The duplicate is new code from this PR.

S4 — Incoming::record_cancelled forwarder (runtime.rs:550-552) with asymmetric call sites (low-medium). Three sites pair it with finish_cancelled (:1670-1671, :1683-1684, :1738-1740), the pending-retain site (:1650) does not; fold the recording into finish_cancelled (:523-532) and drop the forwarder.

Observation only: the new integration tests repeat for _ in 0..200 { admit(); sleep(2ms) } seven times (phase_tests.rs:8645, 8714, 8789, 8832, 8886, 8936, 8997) where existing fixtures use recv_timeout(5s) (:4487), and worker_for_http_state (:8467) duplicates Fixture::worker (:154). Also, the PR description omits that generate_observed became #[cfg(test)] and generate_many_observed was deleted.

Open: whether S2 is wanted given the author's stated intent to keep immediate completion for non-HTTP callers (no in-repo consumer found), and whether the polling loops should be replaced.

Full report · Notes

Correctness and contracts

PR #692's RequestOutcome state machine is mechanically sound — six absorbing states, exactly one counter increment per request, no decrements, no new locks on the hot path — and it genuinely fixes #679's failed/cancelled mis-attribution. The problems are contract and verification, not the CAS logic.

Findings, most important first:

  1. Major — metric contract drift: flare_requests_completed_total and _cancelled_total silently change meaning for HTTP and Decisions traffic, and now mean different things per entry point, while HELP text and docs still say "model generation completed" (metrics.rs:1077-1089, docs/api.md:330, runtime.rs:143-147, :260-295, :1136-1151).
  2. Major — formal gate: the PR adds six protocol states and changes cancellation/completion transitions but extends no TLA+ action or conformance fixture for the deferred half; the harness drives only generate_many (defer=false) and emits terminal events through emit rather than the new emit_finished, so it cannot observe the transition the PR exists for (response_lifecycle_tests.rs:122, :151-165; docs/design-review.md:234-246 calls this a blocking design failure).
  3. Minor — emit_finished's Closed arm records completion with no consumer ever receiving Finished (runtime.rs:570-573).
  4. Minor — a max_new_tokens = 0 choice is never submitted, so its output-layer rejection at http.rs:445-450 yields Delivery::Failed while no counter moves — the "failed exactly once" claim does not hold for that exit.
  5. Minor — the two in-repo Python counter assertions closest to this change were not run and are not disclosed as unrun.

Open questions: merge/rebase order against #548/#560/#691; whether the deferred entry point is used by every in-crate user-visible producer; whether docs/api.md:700-702 needs amending.

Full report · Notes

Final review

Recommendation: Changes Requested

The core fix for #679 is technically sound: the shared RequestOutcome atomic state machine cleanly eliminates mid-stream cancellation misattribution, post-generation output-rejection misattribution, and event-budget double-counting with zero lock contention and strong unit, 2-thread concurrency, and HTTP-to-Worker integration tests. No correctness or concurrency blockers were found. However, before merge the PR should (1) update the Prometheus # HELP strings and API docs for requests_completed_total and requests_cancelled_total so they match the new deferred end-to-end semantics, (2) route the ResponseLifecycle conformance harness's terminal emission through the new emit_finished entry point instead of raw emit, and (3) get CI green on head 348c06c (and simplify the ~160 lines of duplicated CAS loops in RequestOutcome).

Merge Risk

Level: Medium

Walkthrough

Pre-merge Checks

Blockers

None.

Should Fix

  1. Update metric # HELP strings and API docs for the shifted completed / cancelled contract (helios/src/server/metrics.rs:1076-1090, docs/api.md:330).
    • metrics.rs:1077-1079 still documents requests_completed_total as "Requests whose model generation completed successfully, including explicit token stops." and metrics.rs:1087-1089 documents requests_cancelled_total as "Queued or active model requests cancelled before completion." (docs/api.md:330 mirrors completed).
    • Under generate_for_output (defer_completion = true), HTTP and Decisions requests whose model generation completed successfully no longer increment completed until output decoding/validation succeeds, and requests whose reader drops after worker completion (no longer queued or active) now increment cancelled (explicitly tested at helios/src/server/runtime/phase_tests.rs:8983-9020).
    • Fix: Update the # HELP descriptions in helios/src/server/metrics.rs:1076-1090 and the table in docs/api.md:330 (and add a cancelled row if missing) to reflect validated output completion and unread/unvalidated disconnects for served HTTP/Decisions traffic (noting in-process ModelRuntime::generate* retains model-generation completion semantics).
  2. Exercise Incoming::emit_finished in the ResponseLifecycle conformance tests (helios/src/server/runtime/response_lifecycle_tests.rs:155, 372).
    • Production worker completion now goes through Incoming::emit_finished (helios/src/server/runtime.rs:2297, 2594), which uses try_reserve() and suppresses Finished after a prior failure. Both response_lifecycle_tests.rs:155 (action 3 in the TLA+ observed-edge harness) and response_lifecycle_tests.rs:372 (the HTTP terminal-frame retention test) still call raw emit(GenerationEvent::Finished { ... }), bypassing the new production entry point (docs/design-review.md:215-218).
    • Fix: Switch both call sites to .emit_finished(GenerationEvent::Finished { ... }). This preserves the exact ResponseLifecycle.tla projection without adding TLA+ state-space blowup while keeping the harness on the production terminal path.

Subtract / Simplify

  1. Collapse the five duplicated CAS loops in RequestOutcome into one transition helper (helios/src/server/runtime.rs:138-295).
    • record_generated, record_completed, record_cancelled, record_failed, and on_reader_drop repeat the same ~20-line load(Acquire) / compare_exchange_weak(AcqRel, Acquire) / fetch_add(Relaxed) loop across ~160 lines.
    • Replace with one monomorphized helper:
      fn transition(&self, next: impl Fn(u8) -> Option<(u8, Option<&AtomicU64>)>) {
          let mut current = self.state.load(Ordering::Acquire);
          while let Some((target, counter)) = next(current) {
              match self.state.compare_exchange_weak(
                  current,
                  target,
                  Ordering::AcqRel,
                  Ordering::Acquire,
              ) {
                  Ok(_) => {
                      if let Some(counter) = counter {
                          counter.fetch_add(1, Ordering::Relaxed);
                      }
                      return;
                  }
                  Err(actual) => current = actual,
              }
          }
      }
      
      Each of the five methods then becomes a 3–8 line transition table, cutting ~100 lines while keeping identical memory ordering and zero runtime overhead.
  2. Deduplicate the event-budget overflow arm (helios/src/server/runtime.rs:574-580 vs :626-634).
    • emit_finished and emit contain byte-identical TrySendError::Full handlers (same ExecutionError::Completion error string and cancelled.store(true, Ordering::Release)). Extract a single Incoming::event_budget_exceeded(&self) helper called by both.

Nits

Dropped on verification

Full report

Classify triage

Selected: triage:review

Threshold: 65%

Triage

Apply labels

No label changes Decision to Test: no (99%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with. decide malicious: all_clear (100%): No malicious content found

explore

Author: jcartu (CONTRIBUTOR; 3 merged / 10 open PRs in 180 days; Discord jcartu) Motivation: Helios counted responses that its own output layer rejected (e.g. a malformed ChatML tool call) as cancelled instead of failed, so flare_requests_failed_total stayed at zero while operators saw phantom cancellations. This PR makes the worker and the HTTP reader share one atomic outcome so exactly one of completed/cancelled/failed increments once per request. Scale: +968 / −46 lines in 7 files (was +1068 / −32 in 4 files at the previously reviewed head 348c06c) Proposal:

Full report · Notes

Classify intake

Selected: triage:review, priority:P2, bug, area:api

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

No label changes

Subtraction and simplicity

Subtraction/Simplicity review of PR #692 (head 7f298698). Three findings; everything else checked is lean.

  1. (High) RequestOutcome::defer_completion (runtime.rs:126) is a test-only mode switch. Its false callers are generate (:1040), #[cfg(test)] generate_observed (:1044) and generate_many (:1054), all reachable only from test harnesses; the sole true caller is generate_for_output (:1058), used by http.rs:333 and decisions/mod.rs:840. The flag forces two extra COMPLETED arms in record_generated (:158-168), the dual-settlement branch/comment at :482-487, an unused third parameter on enqueue_many (:1066-1071), and the "direct in-process caller" carve-outs in metrics.rs:91, :1078, :1088 and docs/api.md:330, :349-352. Delete the flag and the three wrappers; convert the ~7 test call sites to generate_for_output + explicit complete_output()/drop. Backed by AGENTS.md:188-193 ("configuration switches without a concrete requirement"). Caveat: generate/generate_many are pub (re-exported server.rs:34 (not opened)), so the fallback is to make deferral unconditional and keep them as wrappers that settle immediately.

  2. (Medium-high) http.rs repeats abort + fail_output() + encoder.failure() + yield Delivery::Failed at :402-410, :426-434, :445-450 (correctly no fail_output(), zero-token choices hold no Generation) and :582-589. One helper taking explicit mutable slices removes ~10 lines and makes the PR's central invariant auditable in one place.

  3. (Medium) The new tests copy a 7-line drain loop three times (phase_tests.rs:8744-8750, :8828-8834, :8973-8979) and re-implement the image-input strip loop a third time (:8441-8453 vs :59-67, :4784-4792). Extract drain_to_retirement beside the existing emit_worker_tokens/wait_for_admitted helpers, and Fixture::strip_image_inputs.

Explicitly lean: transition() CAS helper (:138-156), event_budget_exceeded (:493-501), emit_finished (:465-492), finish_cancelled (:434-443), the metrics/docs prose, and the 2-line emit_finished test switch.

Open: whether the pub generate* API may be removed; whether the flag has a planned non-test consumer (none visible).

Full report · Notes

Correctness and contracts

Correctness/contracts review of PR #692 (head 7f298698). No blockers: the CAS state machine, orderings, settlement coverage and hot-path cost are sound. Two Majors and four Minors follow.

  1. Major — the new contract "each request increments at most one of completed/cancelled/failed" (docs/api.md:349-354, metrics.rs:1086-1090) is contradicted by the PR's own tests: an n=2 output failure asserts failed==1 AND cancelled==1 (phase_tests.rs:8894-8898, :8950-8954). The invariant is per-choice, and the PR description's "leaves cancelled unchanged" is false for n>1.
  2. Major — the deferred half has no formal coverage: the ResponseLifecycle harness admits via generate_many (response_lifecycle_tests.rs:120-122, defer_completion=false), so GENERATED/READER_DROPPED and complete_output/fail_output/on_reader_drop (runtime.rs:158-206, :259-268, :289-294) are unreachable in ResponseLifecycle.tla. The 365,508-transition and mutation claims cover only pre-existing behaviour.
  3. Minor — zero-token choices hold no Generation (http.rs:311-316, :344-348), so a fully served all-zero request increments nothing, contradicting docs/api.md:330's new promise.
  4. Minor — completed is recorded at output validation (http.rs:561-566), not delivery, so a post-validation disconnect still counts completed; the doc should say so.
  5. Minor — emit_finished's suppression consults only Incoming.failure (runtime.rs:465-473); consumer-side fail_output leaves that None, so Finished is still sent. Counters stay correct.
  6. Minor — evidence is self-reported: figures byte-identical to the pre-fix run, no CI on head, and --mutations is never invoked by .github/workflows/helios-lifecycle.yml:33-34 (not opened).

Verified sound: transition() CAS with Relaxed fetch_add only on success (runtime.rs:138-156); all terminal states absorbing; fail_output records FAILED before cancel() (:263-268); finish_error records before notifying (:502-513); emit_finished try_reserves before record_generated (:465-492); event_budget_exceeded shared with emit (:493-501, :545-547); no double settle in http.rs (take() at :561 precedes the Err arm at :584); Decisions settles every exit (decisions/mod.rs:838-888). No new locks, allocations, buffering or platform-conditional code; the parallel_tool_calls:false note at docs/api.md:704-709 still matches the code and I am not flagging it.

Open: whether head actually re-ran the suites; whether the TLA+ model is meant to cover the deferred half; and confirmation that the counter invariant is per-choice.

Full report · Notes

Re-review

Recommendation: Ready To Merge

Commit 7f298698 cleanly addresses every Round 1 review item (metric # HELP and API docs updates, routing ResponseLifecycle terminal emission through emit_finished, collapsing the five CAS loops into RequestOutcome::transition, extracting Incoming::event_budget_exceeded, folding record_cancelled() into finish_cancelled, and consolidating test admission polling via wait_for_admitted) without introducing any 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. Once GitHub CI (native-serving and helios-lifecycle) passes on 7f298698, this PR is ready to merge.

Merge Risk

Level: Medium

Walkthrough

Pre-merge Checks

Blockers

None.

Should Fix

None.

Subtract / Simplify

  1. Centralize HTTP Delivery::Failed settlement (helios/src/server/http.rs:402-410, :426-434, :445-450, :582-589) (optional): The four Delivery::Failed exits repeat decoders[idx].abort(Termination::ExecutionError), optional generation.fail_output(), and encoder.failure(&err) (with generations[i] already None for zero-token choices at :445-450). Extracting a small helper (e.g., fail_choice(&mut decoders[idx], generations[idx].as_ref(), &mut encoder, &err) -> Frame) puts the "every Delivery::Failed exit settles its Generation" invariant in one place.
  2. Deduplicate new test helpers (helios/src/server/runtime/phase_tests.rs:8744-8750, :8828-8834, :8973-8979, :8441-8453) (optional): The 7-line for _ in 0..16 terminal-drain loop is copied three times in the new tests and could become a small drain_to_retirement(&mut worker, &mut seq) helper next to wait_for_admitted (:8632-8645). Similarly, text_http_fixture (:8443-8451) repeats the image-input retain loop already present at :59-67 and :4784-4792.

Nits

  1. Clarify per-choice / per-model-request granularity (docs/api.md:349-354, helios/src/server/metrics.rs:1078,1088): docs/api.md:353-354 states "Each request increments at most one of flare_requests_completed_total, flare_requests_cancelled_total, or flare_requests_failed_total." Because Helios runtime counters are per model request (one per choice for n > 1 HTTP requests, or per question prompt in Decisions), a multi-choice output failure increments failed for the failing choice and cancelled for dropped undelivered siblings (as verified in phase_tests.rs:8896-8898 and :8952-8954). Clarifying "Each model request (each choice in a multi-choice request or scored question in Decisions)..." removes any ambiguity for dashboard/alert authors.

Dropped on verification

Full report Decision to Test: no (56%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with.

Classify triage

Selected: triage:review

Threshold: 65%

Triage

Apply labels

No label changes