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
- 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, andhelios/src/server/protocol/decisions/mod.rswith a sharedArc<AtomicU8>state machine (RequestOutcome), changing whencompletedandcancelledincrement 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::Finishedsites, andwait_for_first_tokenpath as open PRs#691(same author),#548, and#560.
Walkthrough
helios/src/server/runtime.rs: AddsRequestOutcome(runtime.rs:109-296), a six-state monotonicAtomicU8(PENDING,GENERATED,READER_DROPPED,COMPLETED,CANCELLED,FAILED) where each Prometheus counter increments only inside a successful CAS into an absorbing terminal state. Replaces eagermetrics.completedincrements atruntime.rs:2295-2314and:2592-2616withIncoming::emit_finished(:553-582), which suppressesFinishedafter a prior worker failure and reserves the channel slot viatry_reserve()before recording generation (failing onFullinstead of completing). AddsModelRuntime::generate_for_output(:1145-1151,defer_completion = true) while keepinggenerate/generate_manyon immediate worker completion (defer_completion = false). Ordersfinish_error(:583-595) to recordFAILEDbefore waking consumers and routes all four worker cancellation sites inWorker::admit(:1650,:1670,:1683,:1738) throughrecord_cancelled(). Adds unit tests for overflow/drop orderings and a 2-threadBarrierconcurrency test (:4471-4649).helios/src/server/http.rs: Switches submission togenerate_for_output(:328-334), settlesGenerationEvent::Finishedwithcomplete_output()orfail_output()(:561-566), and aborts the decoder withTermination::ExecutionError(verified idempotent athelios/src/server/output.rs:384-396) plus callsgeneration.fail_output()on everyDelivery::Failedexit holding an activeGeneration(:402-410,:426-434,:582-590).helios/src/server/protocol/decisions/mod.rs: Switchesscore()(:830-893) togenerate_for_outputand explicitly settles every exit withcomplete_output()orfail_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.
Pre-merge Checks
- [PASS] Security / malicious screen: No prompt injection, suspicious I/O, unsafe code, or trust-boundary weakening found in the diff or PR conversation.
- [PASS] Charter & value fit: Fixes operator-reported P2 bug #679 at the root cause with no new config flags, wire changes, or per-model branches; PR description includes all four required sections.
- [WARN] Related / duplicate / conflict check: Genuinely additive (not superseded), but textually overlaps open PRs
#691(same author,Incoming/Generationandwait_for_first_token),#548, and#560(same counter/finish sites); needs rebase coordination. - [WARN] Tests & verification evidence: Substantial, well-isolated CPU unit/concurrency/integration tests exist and exercise real production
http::generate/Worker/Decoder/Encoderpaths, andcheck.py (not opened) --mutationsis reported passing, but no GitHub CI checks have run on head348c06cyet.
Blockers
None.
Should Fix
- Update metric
# HELPstrings and API docs for the shiftedcompleted/cancelledcontract (helios/src/server/metrics.rs:1076-1090,docs/api.md:330).metrics.rs:1077-1079still documentsrequests_completed_totalas"Requests whose model generation completed successfully, including explicit token stops."andmetrics.rs:1087-1089documentsrequests_cancelled_totalas"Queued or active model requests cancelled before completion."(docs/api.md:330mirrorscompleted).- Under
generate_for_output(defer_completion = true), HTTP and Decisions requests whose model generation completed successfully no longer incrementcompleteduntil output decoding/validation succeeds, and requests whose reader drops after worker completion (no longer queued or active) now incrementcancelled(explicitly tested athelios/src/server/runtime/phase_tests.rs:8983-9020). - Fix: Update the
# HELPdescriptions inhelios/src/server/metrics.rs:1076-1090and the table indocs/api.md:330(and add acancelledrow if missing) to reflect validated output completion and unread/unvalidated disconnects for served HTTP/Decisions traffic (noting in-processModelRuntime::generate*retains model-generation completion semantics).
- Exercise
Incoming::emit_finishedin theResponseLifecycleconformance 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 usestry_reserve()and suppressesFinishedafter a prior failure. Bothresponse_lifecycle_tests.rs:155(action3in the TLA+ observed-edge harness) andresponse_lifecycle_tests.rs:372(the HTTP terminal-frame retention test) still call rawemit(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 exactResponseLifecycle.tlaprojection without adding TLA+ state-space blowup while keeping the harness on the production terminal path.
- Production worker completion now goes through
Subtract / Simplify
- Collapse the five duplicated CAS loops in
RequestOutcomeinto onetransitionhelper (helios/src/server/runtime.rs:138-295).record_generated,record_completed,record_cancelled,record_failed, andon_reader_droprepeat the same ~20-lineload(Acquire)/compare_exchange_weak(AcqRel, Acquire)/fetch_add(Relaxed)loop across ~160 lines.- Replace with one monomorphized helper:
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.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, } } }
- Deduplicate the event-budget overflow arm (
helios/src/server/runtime.rs:574-580vs:626-634).emit_finishedandemitcontain byte-identicalTrySendError::Fullhandlers (sameExecutionError::Completionerror string andcancelled.store(true, Ordering::Release)). Extract a singleIncoming::event_budget_exceeded(&self)helper called by both.
Nits
- Test admission-polling helper (
helios/src/server/runtime/phase_tests.rs:8645, 8714, 8789, 8832, 8886, 8936, 8997): Seven copies of thefor _ in 0..200 { let _ = worker.admit().unwrap(); ... sleep(2ms); }loop (400 ms budget) can be collapsed into onewait_for_admitted(&mut worker, count)helper (with a slightly more generous timeout under loaded CI). - Clarifying comment on
emit_finished'sClosedarm (helios/src/server/runtime.rs:570-573): Worth a one-line comment noting thatrecord_generated()settlesREADER_DROPPED -> CANCELLEDwhendefer_completionis true and preservesREADER_DROPPED -> COMPLETEDfor directgenerate/generate_manycallers. - Pair
record_cancelledinsidefinish_cancelled(helios/src/server/runtime.rs:523-532, 1670-1690): Movingself.outcome.record_cancelled()intoIncoming::finish_cancelledmakes it impossible for a future caller to emit a cancelledFinishedevent without settling the outcome (withrecord_cancelled()still called directly on the pending-drop path at:1650and:1738).
Dropped on verification
- Upstream claim (Correctness 3.2 / Value Prop / Dossier): "Blocking design failure because
ResponseLifecycle.tlawas not extended with the 6RequestOutcomestates." Dropped as a blocker: verified inverification/helios-lifecycle/ResponseLifecycle.tla:1-193andverification/helios-lifecycle/README.md:98-145thatResponseLifecycle.tlamodels host admission permit retention, bounded response queues, and producer/reader ownership — explicitly excluding HTTP/output encoder state (README.md:137) and not tracking Prometheus counters. Adding 6 per-cell outcome states to a 3-cell model already at 65,989 states / 365,508 edges would risk TLC state-space blowup with little value over the unit + 2-threadBarrierconcurrency tests (runtime.rs:4574-4649). Downgraded to the targetedShould Fix#2 (callingemit_finishedfromresponse_lifecycle_tests.rs). - Upstream claim (Subtraction S2): "Delete
defer_completionand the non-deferred half ofRequestOutcomeas dead production code; havegenerate/generate_manycallcomplete_output()instead." Dropped as incorrect/unsafe: verifiedModelRuntime::generate(runtime.rs:1127) andgenerate_many(runtime.rs:1141) arepubAPIs re-exported athelios/src/server.rs:34(not opened) (aligned with the charter's in-process Rust SDK roadmap) whileGeneration::complete_outputispub(super)(runtime.rs:348). Callingcomplete_output()insidegenerate/generate_manyat enqueue time is broken (it would settle requests asCOMPLETEDbefore execution, breaking worker failure and cancellation accounting), and forcing deferred semantics onto publicgenerate/generate_manycallers without a public settlement API would miscount every direct completion asCANCELLEDonDropand break existing tests (phase_tests.rs:571, 2003, 3770, 3784, 3824, 3864). - Upstream claim (Correctness / Dossier / Value Prop): "Python counter suites
tests/server/test_protocols.py:676andtests/server/test_decisions.py:230-261were skipped without disclosure." Dropped as false: verified attests/server/test_protocols.py:22-24andtests/server/test_decisions.py:16-18that both suites are gated byFLARE_API_TEST_URL(reason="requires a native Flare service"), which requires live GPU serving throughflare run— explicitly disclosed as unrun in the PR's Limitations section. Static inspection of both tests confirms theirflare_requests_cancelled_total > beforeassertions remain valid under PR #692. - Upstream claim (Dossier / Value Prop / Subtraction): "Silently breaks internal API by deleting
generate_many_observedand makinggenerate_observed#[cfg(test)]." Dropped as false/low-signal: verified onmain(helios/src/server/runtime.rs:895, 908) that both methods were already crate-internalpub(super)helpers, and both changes are explicitly noted in the PR's What Changed section. - Upstream claim (Correctness 1.2): "Zero-token output failure (
http.rs:445-450) is an uncovered hole because it does not incrementrequests_failed_total." Dropped as by-design / pre-existing: verified athttp.rs:311-315that zero-token choices bypassModelRuntimecompletely (never admitted, never incrementadmittedorcompletedeither), matching all other non-admitted HTTP rejections. - Upstream claim (Dossier / Correctness Open Question): "
emit_finished'stry_reserve()permit could be dropped without sending, leaving a request stuck inGENERATED." Dropped as speculative: verified atruntime.rs:562-569thatpermit.send(event)executes unconditionally on the line immediately afterself.outcome.record_generated()with no fallible call or branch in between.