Subtraction, Simplicity & Conventions review — PR #692
PR: https://github.com/NVIDIA/hyperflare-inference/pull/692 · head 348c06c · 4 files, +1068/−32
Key findings
- ~150 lines of hand-rolled CAS loops that differ only in three constants.
helios/src/server/runtime.rs:138-295contains six near-identicalload→compare_exchange_weakloops.record_completed(:191-212),record_cancelled(:214-235),record_failed(:237-258) and theGENERATEDarm ofon_reader_drop(:275-291) differ only in the acceptedfromset, the target state, and whichAtomicU64counter they bump. Onesettle(&self, from: &[u8], to: u8, counter: &AtomicU64) -> boolhelper preserves identical semantics and shrinks the block to ~40 lines. High value. - The
defer_completionflag and the whole non-deferred half of the state machine are now dead production code. After this PR the only production callers arehttp.rs:333anddecisions/mod.rs:840, bothgenerate_for_output(defer_completion = true). Thefalsehalf is reachable only from three test files. Deleting the flag removes the struct field (runtime.rs:123-126), the extraenqueue_manyparameter (:1153-1158) and fourdefer_completionbranches inrecord_generated(:143-147, 155-157, 164-168, 176-180). High value. - The event-budget overflow arm is copy-pasted verbatim, including the error literal string:
emit_finishedruntime.rs:574-580vsemit:626-634. Extract oneevent_budget_exceeded(). Medium value. Incoming::record_cancelled(runtime.rs:550-552) is a one-line forwarder with inconsistent call sites — three sites pair it withfinish_cancelled, one does not. Fold the recording intofinish_cancelled(:523-532). Low-medium value.- Seven copies of the same
for _ in 0..200 { admit(); sleep(2ms) }admission-poll loop inphase_tests.rs(:8645, 8714, 8789, 8832, 8886, 8936, 8997), plus a localworker_for_http_state(:8467) that duplicatesFixture::worker(:154). Observation, not a blocker.
Everything else is lean: the settlement sites in http.rs:561-566 and :582-590 are as small as they can be, decisions/mod.rs:843-889 is an unavoidable per-exit fail_output() without a guard type, and no new config knob, env var, or speculative extension point was introduced.
S1 — Collapse six CAS loops into one settle helper (runtime.rs:138-295)
runtime.rs:214-235, verbatim:
fn record_cancelled(&self) {
let mut current = self.state.load(Ordering::Acquire);
loop {
match current {
OUTCOME_PENDING | OUTCOME_READER_DROPPED => {
match self.state.compare_exchange_weak(
current,
OUTCOME_CANCELLED,
Ordering::AcqRel,
Ordering::Acquire,
) {
Ok(_) => {
self.metrics.cancelled.fetch_add(1, Ordering::Relaxed);
return;
}
Err(actual) => current = actual,
}
}
_ => return,
}
}
}
runtime.rs:191-212, verbatim (identical shape; only the from-set, target and counter change):
fn record_completed(&self) {
let mut current = self.state.load(Ordering::Acquire);
loop {
match current {
OUTCOME_PENDING | OUTCOME_GENERATED => {
match self.state.compare_exchange_weak(
current,
OUTCOME_COMPLETED,
Ordering::AcqRel,
Ordering::Acquire,
) {
Ok(_) => {
self.metrics.completed.fetch_add(1, Ordering::Relaxed);
record_failed (:237-258) and the OUTCOME_GENERATED arm of on_reader_drop (:275-291) are the same loop with PENDING | GENERATED | READER_DROPPED → FAILED → metrics.failed and GENERATED → CANCELLED → metrics.cancelled respectively. All three counters are AtomicU64 (helios/src/server/metrics.rs:228-231).
Replace with:
fn settle(&self, from: &[u8], to: u8, counter: &AtomicU64) -> bool {
let mut current = self.state.load(Ordering::Acquire);
loop {
if !from.contains(¤t) {
return false;
}
match self.state.compare_exchange_weak(
current, to, Ordering::AcqRel, Ordering::Acquire,
) {
Ok(_) => {
counter.fetch_add(1, Ordering::Relaxed);
return true;
}
Err(actual) => current = actual,
}
}
}
then record_completed/record_cancelled/record_failed become one-line calls, and on_reader_drop becomes:
fn on_reader_drop(&self) {
if self.settle(&[OUTCOME_PENDING], OUTCOME_READER_DROPPED, ...) { ... }
(the PENDING → READER_DROPPED arm increments no counter, so it keeps its own two-line CAS or takes an Option<&AtomicU64>). Semantics are unchanged: same from-sets, same absorbing terminal states, same one-increment guarantee. Only record_generated (:138-189) genuinely needs bespoke handling because its target depends on defer_completion — and see S2, which deletes that flag anyway.
S2 — Delete defer_completion and the non-deferred half of the machine
runtime.rs:119-127, verbatim:
#[derive(Clone)]
struct RequestOutcome {
state: Arc<AtomicU8>,
metrics: Arc<super::metrics::Metrics>,
/// When true, normal worker completion parks in `OUTCOME_GENERATED` until
/// the response consumer confirms output processing succeeded, rejects
/// output as failed, or drops the reader.
defer_completion: bool,
}
runtime.rs:138-149, verbatim (one of four defer_completion branches):
fn record_generated(&self) {
let mut current = self.state.load(Ordering::Acquire);
loop {
match current {
OUTCOME_PENDING => {
let target = if self.defer_completion {
OUTCOME_GENERATED
} else {
OUTCOME_COMPLETED
};
match self.state.compare_exchange_weak(
Further branches at :155-157, :164-168, :176-180. The parameter is threaded through enqueue_many (runtime.rs:1153-1158):
fn enqueue_many(
&self,
prompts: Vec<Prompt>,
observation: Option<bool>,
defer_completion: bool,
) -> Result<Vec<Generation>> {
Caller census after this PR (verified against the head):
| entry point | line | defer_completion |
callers |
|---|---|---|---|
generate_for_output |
runtime.rs:1145-1151 |
true |
http.rs:333, decisions/mod.rs:840 — the only production callers |
generate |
runtime.rs:1127 |
false |
phase_tests.rs:3784 only |
generate_many |
runtime.rs:1141 |
false |
phase_tests.rs:3857, 3864, 3869 and response_lifecycle_tests.rs:122 |
#[cfg(test)] generate_observed |
runtime.rs:1131-1134 |
false |
phase_tests.rs:3770, 3824 |
No consumer outside helios/ (no helios:: references in flare/; ModelRuntime is re-exported at helios/src/server.rs:34 (not opened)).
Concrete simplification: drop the defer_completion field and the enqueue_many parameter, make record_generated unconditionally PENDING → GENERATED, and have generate/generate_many/generate_observed call complete_output() when they want immediate settlement (the settlement they already get today through the flag). That deletes ~40 lines, an entire flag dimension, and makes the state machine exactly the deferred machine the PR exists for. It has a second benefit worth naming: helios/src/server/runtime/response_lifecycle_tests.rs:100-195 drives generate_many/emit/cancel/fail directly, so it today exercises only the defer_completion = false half — the half the PR does not care about. Collapsing the flag puts the TLA+ conformance harness on the transitions that matter.
This is also the strongest convention argument in the diff: AGENTS.md:188-193 — "Do not add frameworks, extension points, speculative compatibility, fallback layers, or configuration switches without a concrete requirement." A true-only boolean threaded into the worker's hot outcome path is exactly a two-valued switch with one live value.
S3 — De-duplicate the event-budget overflow arm (runtime.rs:574-580 vs :626-634)
runtime.rs:574-580, verbatim:
Err(async_mpsc::error::TrySendError::Full(())) => {
self.fail(Error::execution(
ExecutionError::Completion,
"generation exceeded its output event budget",
));
self.cancelled.store(true, Ordering::Release);
}
runtime.rs:626-634, verbatim:
Err(async_mpsc::error::TrySendError::Full(_)) => {
// Admission budgets the complete response, so a full queue is a
// producer invariant violation, not a slow or disconnected reader.
self.fail(Error::execution(
ExecutionError::Completion,
"generation exceeded its output event budget",
));
self.cancelled.store(true, Ordering::Release);
}
Both bodies are identical bar the channel payload type and the comment; the error literal is byte-identical at :577 and :631.
Replace both bodies with a single method on Incoming:
fn event_budget_exceeded(&self) {
self.fail(Error::execution(
ExecutionError::Completion,
"generation exceeded its output event budget",
));
self.cancelled.store(true, Ordering::Release);
}
and call self.event_budget_exceeded() from both arms. The Full arm in emit_finished is new code from this PR (:574-580), so this is duplicated logic the PR itself introduced.
S4 — Remove the Incoming::record_cancelled forwarder and the paired-call asymmetry
runtime.rs:550-552, verbatim:
fn record_cancelled(&self) {
self.outcome.record_cancelled();
}
runtime.rs:523-532 (finish_cancelled), verbatim:
fn finish_cancelled(&self, carried: Carried) {
self.emit(GenerationEvent::Finished {
prompt_tokens: carried.prompt_tokens.unwrap_or(self.prompt.tokens.len()),
generated_tokens: carried.generated_tokens,
reused_prompt_tokens: carried.reused_prompt_tokens.unwrap_or(0),
reason: "stop",
termination: crate::output::Termination::Cancelled,
stop_sequence: None,
});
}
Call sites are inconsistent. runtime.rs:1667-1675, verbatim — the recording and the terminal event are always adjacent:
self.parked.retain(|(incoming, parked)| {
let cancelled = incoming.cancelled.load(Ordering::Acquire);
if cancelled {
incoming.record_cancelled();
incoming.finish_cancelled(parked.carried);
progress = true;
}
!cancelled
});
The same pairing appears at :1683-1684 and :1738-1740, whereas the pending-retain site (:1647-1654) calls request.record_cancelled(); alone with no terminal event:
self.pending.retain(|request| {
let cancelled = request.cancelled.load(Ordering::Acquire);
if cancelled {
request.record_cancelled();
progress = true;
}
!cancelled
});
Concrete simplification: have finish_cancelled call self.outcome.record_cancelled() as its first statement (the argument, finish_cancelled cannot be reached on a live request, is already carried by the audit claim), delete the Incoming::record_cancelled forwarder, and keep a direct self.outcome.record_cancelled() only in the pending-retain arm that emits no terminal event. Net: one fewer method, one fewer line at three call sites, and the invariant "a cancelled request records the outcome exactly once, either when it is finished or when it is dropped while pending" sits in one place instead of being reasserted by every caller. The forwarder exists for no reason: Incoming already holds outcome directly and calls self.outcome.record_generated() / self.outcome.record_failed() inline elsewhere (:567, :572, :589).
Note for the correctness lens, not duplicated here: if the reviewer prefers, deleting the forwarder wholesale — including the pending-retain call — is not safe, because that arm settles no other way. This suggestion is strictly about removing the middleman and the pairing.
Observation (not a demand): duplicated admission polling in the new tests
The seven new/checked test bodies at helios/src/server/runtime/phase_tests.rs:8645, 8714, 8789, 8832, 8886, 8936, 8997 each contain the same loop; phase_tests.rs:8645-8651, verbatim:
for _ in 0..200 {
let _ = worker.admit().unwrap();
if worker.active[0].is_some() {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(2)).await;
}
This is a 400 ms wall-clock budget with a silent failure mode (the loop ends and the next assert! reports "request was not admitted"), while the existing fixture family in the same file synchronizes on the actual channel instead — phase_tests.rs:4487-4491 uses .recv_timeout(std::time::Duration::from_secs(5)), as do :4640, :4875, :5116, :5510. Neither in-repo convention docs mandate one over the other; the suggestion is only that seven copies of a polling loop should be one helper (or the recipient-based wait), especially since the same tests already sit next to a helper that could own it. Similarly, the local worker_for_http_state (phase_tests.rs:8467-8496) re-derives graph durations and Worker::new construction that Fixture::worker (phase_tests.rs:154) already provides. Both are test-side and do not block.
Conventions check
AGENTS.md:188-193("Reject unsupported abstractions and churn… no configuration switches without a concrete requirement; refactoring must directly support the requested behavior") — S2 is the one real hit: a boolean mode switch with a single live value in the worker's outcome path.AGENTS.md:72-112(four-part PR description) — satisfied; the description has Why / What Changed / Claimed Result / Supporting Evidence. It does not mention thatgenerate_observedbecame#[cfg(test)](runtime.rs:1131-1134) and thatgenerate_many_observedwas deleted, nor thehttp.rs:331-333observation rewrite; underAGENTS.md:93("a file list or a label does not explain what was done") the internal API reduction deserves one sentence. Not a code change, but it is the one prose gap.docs/design-review.md:209-240(not opened) — the lifecycle gate applies; the PR reportscheck.py (not opened) --mutationsbut adds no model action or conformance fixture for the newPENDING → GENERATED → COMPLETED/CANCELLED/FAILEDtransitions, and the existing harness only reaches the non-deferred half (see S2).- Configuration rule (
AGENTS.md:450-472) — no env var or config file key added; clean. - No dead code flags, no
#[allow(dead_code)]suppressions, no compatibility shims, no duplicated metric helpers introduced beyond S3.
Open questions / not found
- Whether S2's deletion of
defer_completionis acceptable to the author's intent — the PR deliberately keepsgenerate/generate_manyat immediate completion for "SDK-style and test callers" (description, What Changed). No in-repo SDK consumer exists; I found no Rust caller ofgenerate/generate_manyoutsidephase_tests.rsandresponse_lifecycle_tests.rs, and nohelios::references inflare/, but I did not searchflare-cli/,flare-winui/, orheliopause/exhaustively. - Whether
on_reader_drop'sPENDING → READER_DROPPEDarm (runtime.rs:260-274, the only CAS that increments nobody) has a natural place in the proposedsettlehelper or should stay bespoke — either answer is fine, it is one branch. - Whether the seven polling loops should be replaced or left as-is; I did not determine which existing helper in
phase_tests.rsis the canonical one for an HTTP-drives-worker fixture.