Repository navigation
refactor(mux-h2): extract the GOAWAY/drain state machine, and write the invariant its bug class never had - #1425
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 22, 2026 07:04
FlorentinDUBOIS
changed the base branch from
refactor/h2-flood-detector
to
main
September 22, 2026 07:25
H2DrainState (draining, peer_last_stream_id, started_at, graceful_shutdown_deadline, initial_goaway_pending) was already socket-free. What was not is the six ConnectionH2 functions that read and wrote it: graceful_goaway, goaway, send_initial_goaway, handle_goaway_frame, peer_gone_after_final_goaway, and the GOAWAY stage of flush_pending_control_frames. Move the decision - draining or not, defer-or-send, budget-elapsed - into h2_drain.rs behind the same closed-API shape hpack_state.rs, h2_flow_control.rs, h2_stream_table.rs and h2_flood_detector.rs established in the four prior extraction steps: - H2DrainState::begin_graceful_drain replaces graceful_goaway's state-mutating half, returning a GracefulDrainDecision (AlreadyDraining / DeferInitial / SendInitial). - H2DrainState::take_deferred_initial_goaway replaces the check-and-clear at the top of flush_pending_control_frames' GOAWAY stage. - H2DrainState::enter_final_goaway replaces the two-field mutation in goaway(); H2DrainState::observe_peer_goaway replaces it in handle_goaway_frame, which now reads back its own recorded peer_last_stream_id() for the retry-loop comparison. - H2DrainState::deadline_elapsed replaces graceful_shutdown_deadline_elapsed's body, taking now: Instant as an explicit parameter instead of reading a clock. Every decision method that needs the header-block-reassembly guard takes it as a caller-computed bool rather than reaching for self.zero/self.state itself - h2_drain.rs has neither - which keeps the module structurally unable to reintroduce the zero.storage dual-role clobber (#1396, #1397, #1401) that LIFECYCLE.md's new invariant 24 documents. peer_gone_after_final_goaway and force_disconnect stay on ConnectionH2 untouched. Pure relocation, no behaviour change: proved by the compiler and the existing suite, including the #1397/#1401 regression tests passing unmodified. Reported but not fixed here: flush_pending_control_frames' frontend_hung_up_while_draining() stage clears zero.storage without checking header_block_reassembly_in_progress(), unlike every stage below it in the same function - a live gap of the same bug class. Also fixes 73 LIFECYCLE.md/doc/testing.md line citations that drifted from this changeset's line-number shifts in h2.rs (mechanically relocated via exact-text diff mapping against the branch base, each spot-verified), and the one pre-existing rule-1 failure that drift caused. Also fixes LIFECYCLE.md prose that quoted pre-refactor private-field access syntax on this and the three prior extractions' closed-API types (self.drain.draining, self.drain.started_at, self.streams, self.rst_sent, and a struct snippet showing expect_read/expect_write as pub when they are private) - code that no longer compiles now that those fields are private. The narrative paragraph in section 2.2 is rewritten to describe the actual API (begin_graceful_drain, enter_final_goaway, take_deferred_initial_goaway) instead of raw field assignment. The citation gate does not catch this class of drift: a line citation can resolve to a real, unchanged, on-topic line while the code fragment quoted in the surrounding prose no longer compiles. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
refactor/h2-goaway-drain
branch
from
September 22, 2026 10:31
f76c8eb to
39813f2
Compare
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 22, 2026
#1425 moved the RFC 9113 §6.8 GOAWAY/drain state machine into h2_drain.rs and made all five H2DrainState fields private. Five sentences outside that module still described them as reachable from h2.rs; two were false rather than merely loose. mux/LIFECYCLE.md §8.3 attributed `drain.started_at = Some(now)` to ConnectionH2::graceful_goaway, which reads and writes none of the five and delegates to H2DrainState::begin_graceful_drain. The passage now names that method and PINS the debug_assert guarding the assignment as a fenced quote of h2_drain.rs:234-237, so the invariant it encodes — the budget arms exactly once, on the first call — is carried verbatim by the source instead of paraphrased beside it. #1432 added that mechanism for exactly this case; quoted unpinned, the sentence drifts silently the moment the message is reworded. Seen red: rewording the message to "on the very first call" exits 1 naming the block, and restoring it exits 0. The same attribution sat in production source: the RFC 9113 §6.8 comment guarding new peer-initiated streams said graceful_goaway sets `drain.draining = true`. Only that mechanism clause changed; the argument around it is correct and is kept. The comment keeps its exact line count so the 88 h2.rs citations below it and the pinned code blocks do not drift. doc/h2_mux_internals.md's priority-cleanup list cited close_all_streams, which has never existed under lib/ at any revision. ConnectionH2::goaway is the nearest-sounding real function and is the wrong target: it touches neither the prioriser nor the stream map. GOAWAY-time removal is handle_goaway_frame plus prune_inactive_streams_while_closing, both reaching remove_dead_stream once per retired stream, and neither clears the map wholesale. Two further hits from the same sweep: doc/lifetime_of_a_session.md placed H2DrainState::draining in h2.rs, and doc/architecture.md credited H2DrainState with "pending RST streams", which are H2StreamTable's pending_rst_streams. That bullet names the struct's role and its module and enumerates nothing: replacing a wrong five-field list with a right one keeps the restated copy that drifted in the first place. Sweep, read against c359eaf: git grep -En 'drain\.|draining|started_at|graceful_shutdown_deadline|peer_last_stream_id|initial_goaway_pending' \ c359eaf -- lib/ doc/ | grep -v h2_drain.rs 338 hits across 36 files read. 3 of those hit lines changed, across 2 files: LIFECYCLE.md twice and h2.rs once. A 4th hit had the module path beside it corrected (lifetime_of_a_session.md), and 2 further sites carry no pattern token and so sit outside the hit set altogether — h2_mux_internals.md's close_all_streams and architecture.md's sub-struct bullet. Five sites in all. The trailing `.` above is escaped and means a literal field access; as an unescaped regex any-char the same sweep returns 933 hits across 52 files. doc/h2_mux_internals.md:617 and :621 are among the hits read and deliberately left: they narrate module-internal state in the register h2_drain.rs's own doc comments use and claim nothing about reachability. No rule in check_doc_citations.py reached any of these when written: the drift rule compares a cited line at two revisions and these documents do not modify h2.rs; the dead-name rule resolves test names only; a code comment is in no rule. The pinned debug_assert is the one that need not stay that way. Refs: #1446 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 23, 2026
#1425 moved the RFC 9113 §6.8 GOAWAY/drain state machine into h2_drain.rs and made all five H2DrainState fields private. Five sentences outside that module still described them as reachable from h2.rs; two were false rather than merely loose. mux/LIFECYCLE.md §8.3 attributed `drain.started_at = Some(now)` to ConnectionH2::graceful_goaway, which reads and writes none of the five and delegates to H2DrainState::begin_graceful_drain. The passage now names that method and PINS the debug_assert guarding the assignment as a fenced quote of h2_drain.rs:234-237, so the invariant it encodes — the budget arms exactly once, on the first call — is carried verbatim by the source instead of paraphrased beside it. #1432 added that mechanism for exactly this case; quoted unpinned, the sentence drifts silently the moment the message is reworded. Seen red: rewording the message to "on the very first call" exits 1 naming the block, and restoring it exits 0. The same attribution sat in production source: the RFC 9113 §6.8 comment guarding new peer-initiated streams said graceful_goaway sets `drain.draining = true`. Only that mechanism clause changed; the argument around it is correct and is kept. The comment keeps its exact line count so the 88 h2.rs citations below it and the pinned code blocks do not drift. doc/h2_mux_internals.md's priority-cleanup list cited close_all_streams, which has never existed under lib/ at any revision. ConnectionH2::goaway is the nearest-sounding real function and is the wrong target: it touches neither the prioriser nor the stream map. GOAWAY-time removal is handle_goaway_frame plus prune_inactive_streams_while_closing, both reaching remove_dead_stream once per retired stream, and neither clears the map wholesale. Two further hits from the same sweep: doc/lifetime_of_a_session.md placed H2DrainState::draining in h2.rs, and doc/architecture.md credited H2DrainState with "pending RST streams", which are H2StreamTable's pending_rst_streams. That bullet names the struct's role and its module and enumerates nothing: replacing a wrong five-field list with a right one keeps the restated copy that drifted in the first place. Sweep, read against c359eaf: git grep -En 'drain\.|draining|started_at|graceful_shutdown_deadline|peer_last_stream_id|initial_goaway_pending' \ c359eaf -- lib/ doc/ | grep -v h2_drain.rs 338 hits across 36 files read. 3 of those hit lines changed, across 2 files: LIFECYCLE.md twice and h2.rs once. A 4th hit had the module path beside it corrected (lifetime_of_a_session.md), and 2 further sites carry no pattern token and so sit outside the hit set altogether — h2_mux_internals.md's close_all_streams and architecture.md's sub-struct bullet. Five sites in all. The trailing `.` above is escaped and means a literal field access; as an unescaped regex any-char the same sweep returns 933 hits across 52 files. doc/h2_mux_internals.md:617 and :621 are among the hits read and deliberately left: they narrate module-internal state in the register h2_drain.rs's own doc comments use and claim nothing about reachability. No rule in check_doc_citations.py reached any of these when written: the drift rule compares a cited line at two revisions and these documents do not modify h2.rs; the dead-name rule resolves test names only; a code comment is in no rule. The pinned debug_assert is the one that need not stay that way. Refs: #1446 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 23, 2026
) #1425 moved the RFC 9113 §6.8 GOAWAY/drain state machine into h2_drain.rs and made all five H2DrainState fields private. Five sentences outside that module still described them as reachable from h2.rs; two were false rather than merely loose. mux/LIFECYCLE.md §8.3 attributed `drain.started_at = Some(now)` to ConnectionH2::graceful_goaway, which reads and writes none of the five and delegates to H2DrainState::begin_graceful_drain. The passage now names that method and PINS the debug_assert guarding the assignment as a fenced quote of h2_drain.rs:234-237, so the invariant it encodes — the budget arms exactly once, on the first call — is carried verbatim by the source instead of paraphrased beside it. #1432 added that mechanism for exactly this case; quoted unpinned, the sentence drifts silently the moment the message is reworded. Seen red: rewording the message to "on the very first call" exits 1 naming the block, and restoring it exits 0. The same attribution sat in production source: the RFC 9113 §6.8 comment guarding new peer-initiated streams said graceful_goaway sets `drain.draining = true`. Only that mechanism clause changed; the argument around it is correct and is kept. The comment keeps its exact line count so the 88 h2.rs citations below it and the pinned code blocks do not drift. doc/h2_mux_internals.md's priority-cleanup list cited close_all_streams, which has never existed under lib/ at any revision. ConnectionH2::goaway is the nearest-sounding real function and is the wrong target: it touches neither the prioriser nor the stream map. GOAWAY-time removal is handle_goaway_frame plus prune_inactive_streams_while_closing, both reaching remove_dead_stream once per retired stream, and neither clears the map wholesale. Two further hits from the same sweep: doc/lifetime_of_a_session.md placed H2DrainState::draining in h2.rs, and doc/architecture.md credited H2DrainState with "pending RST streams", which are H2StreamTable's pending_rst_streams. That bullet names the struct's role and its module and enumerates nothing: replacing a wrong five-field list with a right one keeps the restated copy that drifted in the first place. Sweep, read against c359eaf: git grep -En 'drain\.|draining|started_at|graceful_shutdown_deadline|peer_last_stream_id|initial_goaway_pending' \ c359eaf -- lib/ doc/ | grep -v h2_drain.rs 338 hits across 36 files read. 3 of those hit lines changed, across 2 files: LIFECYCLE.md twice and h2.rs once. A 4th hit had the module path beside it corrected (lifetime_of_a_session.md), and 2 further sites carry no pattern token and so sit outside the hit set altogether — h2_mux_internals.md's close_all_streams and architecture.md's sub-struct bullet. Five sites in all. The trailing `.` above is escaped and means a literal field access; as an unescaped regex any-char the same sweep returns 933 hits across 52 files. doc/h2_mux_internals.md:617 and :621 are among the hits read and deliberately left: they narrate module-internal state in the register h2_drain.rs's own doc comments use and claim nothing about reachability. No rule in check_doc_citations.py reached any of these when written: the drift rule compares a cited line at two revisions and these documents do not modify h2.rs; the dead-name rule resolves test names only; a code comment is in no rule. The pinned debug_assert is the one that need not stay that way. Refs: #1446 Signed-off-by: Florentin Dubois <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Step 5 of the H2 sans-io extraction. Stacked on #1419 (step 4); steps 1-3 landed as #1403, #1406,
#1415. This PR will need retargeting to
mainonce #1419 merges — squash-merging a base branchauto-closes its stacked PRs, which happened once already in this series.
H2DrainState—draining,peer_last_stream_id,started_at,graceful_shutdown_deadline,initial_goaway_pending— moves intolib/src/protocol/mux/h2_drain.rswith the closedpub(super)API the four previous steps established. Decision methods return outcome enums
(
GracefulDrainDecision::{AlreadyDraining, DeferInitial, SendInitial}) so the module stays free oflogging, metrics and I/O;
ConnectionH2keeps everything that needs a socket,Contextor readiness.A pure move. No behaviour change, proven by the compiler and the unmodified suite — 380 tests,
including both regression tests that pin this area's history:
a_legitimate_continuation_survives_an_unrelated_window_update_flush(#1397) anda_legitimate_continuation_survives_a_graceful_goaway(#1401). No assertion was touched and no red wasmanufactured.
The reassembly guard is passed in, not reached for
Every decision method that needs to know whether a header block is mid-reassembly takes it as a
caller-computed
bool.h2_drain.rsimports onlystd::timeandsuper::StreamId— it has nopath to
self.zero,H2StateorConnectionH2at all.That is the point. This module's whole reason to exist carefully is that
graceful_goawayclearingzero.storagemid-reassembly was #1401, andinitial_goaway_pendingexists because of it. A modulethat cannot reach the buffer cannot reintroduce the clobber — by construction rather than by review.
A review verified both halves: the absent imports, and that both call sites compute the bool on the
line immediately preceding the call, so no staleness window exists.
Invariant 24, written before the step that needs it
None of
LIFECYCLE.md's 23 invariants named thezero.storagedual-role hazard, though it has nowproduced four bugs. This changeset writes it:
with #1396, #1397 and #1401 as provenance, the guard that enforces it today, and the tests that pin it.
It is written now, deliberately, so the reassembly step has a citable rule rather than three scattered
bug fixes.
Writing it is what found the fourth instance.
A live gap found while writing the invariant — filed, not fixed
flush_pending_control_frameshas four stages touchingzero.storage. The three lower ones each carry&& !self.header_block_reassembly_in_progress(), added one at a time by #1397 and #1401. The first— the
frontend_hung_up_while_draining()clear — carries none.frontend_hung_up_while_draining()checks onlyPosition::Server,draining, and HUP/ERRORreadiness. Nothing excludes a connection parked in
ContinuationHeader/ContinuationFrame, and twoordinary paths reach it: a peer sending FIN together with a last incomplete CONTINUATION in one
edge-triggered read, or a
graceful_goawaysettingdrainingmid-reassembly — which #1401 establishedhappens — followed by a HUP.
Each previous fix added the guard to the stage it was fixing. None looked at the stage above.
Filed as #1423, verified byte-identical to this changeset's base, and deliberately untouched here.
What step 9 will need from the shell
The
writable()H2State::GoAwayarm — the one whose comment calls it the primary truncationvector — is untouched by this changeset and belongs to step 9. But the extraction had to establish
what shape it will need, so it is recorded rather than rediscovered:
A boolean is not enough. The arm's inner re-check after attempting a flush distinguishes three
states — nothing was queued, a flush was attempted and fully drained, a flush was attempted and the
kernel is still backpressured. A single "is anything pending" flag collapses the last two, and a stale
pre-attempt read cannot tell you whether this attempt succeeded. The recommendation is a three-state
outcome reported by the shell, consumed by a decision method returning
{CloseSession, WaitForWritable, ForceDisconnect}— the same shape asGracefulDrainDecision.A documentation defect this changeset fixes beyond its own scope
Review found that
LIFECYCLE.mditem 8 and the narrative above invariant 24 still described drainstate with pre-refactor field syntax —
self.drain.draining— which no longer compiles, since thischangeset made those fields private. The line citations beside them were correct and resolved cleanly,
which is exactly why CI passed: rule 1 proves a line is non-blank and in range, and the drift rule
compares text at unchanged pairs. Neither inspects whether code quoted in the prose still compiles.
That is a different failure from a drifted citation — there the number is wrong and the prose right;
here the number is right and the prose wrong — and both are invisible to the gate.
Sweeping for the same shape found six more sites, all pre-existing from #1415's
H2StreamTableextraction, all fixed here. The sweep also correctly left alone the passages that look identical and
are right: prose deliberately showing unreachable syntax to prove a field is private, code blocks
reproducing a method from inside its own module's
impl, andContext.streams, which is a differentfield on a different type.
doc/h2_mux_internals.mdcarries the same class and is outside this changeset's files; filed as#1424.
Validation, both feature shapes
Refs #1336, #1339, #1423, #1424.