Skip to content

refactor(mux-h2): extract the GOAWAY/drain state machine, and write the invariant its bug class never had - #1425

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-goaway-drain
Sep 22, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-goaway-drain

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

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 main once #1419 merges — squash-merging a base branch
auto-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 into lib/src/protocol/mux/h2_drain.rs with the closed pub(super)
API the four previous steps established. Decision methods return outcome enums
(GracefulDrainDecision::{AlreadyDraining, DeferInitial, SendInitial}) so the module stays free of
logging, metrics and I/O; ConnectionH2 keeps everything that needs a socket, Context or 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) and
a_legitimate_continuation_survives_a_graceful_goaway (#1401). No assertion was touched and no red was
manufactured.

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.rs imports only std::time and super::StreamId — it has no
path to self.zero, H2State or ConnectionH2 at all.

That is the point. This module's whole reason to exist carefully is that graceful_goaway clearing
zero.storage mid-reassembly was #1401, and initial_goaway_pending exists because of it. A module
that 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 the zero.storage dual-role hazard, though it has now
produced four bugs. This changeset writes it:

  1. ConnectionH2::zero's dual role: HEADERS+CONTINUATION reassembly accumulator vs. control-frame
    write scratch — no path may clobber the former while it is in progress.
    self.zero is BOTH the
    read-side accumulator a HEADERS/CONTINUATION field block is reassembled into —
    headers.header_block_fragment is a (start, len) window over self.zero.storage that must survive
    multiple readable() passes until END_HEADERS — AND the write-side scratch buffer every
    control-frame flush (WINDOW_UPDATE, RST_STREAM, GOAWAY) clears and reuses. No code path may clear or
    reuse self.zero.storage while ConnectionH2::header_block_reassembly_in_progress() is true.

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_frames has four stages touching zero.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 only Position::Server, draining, and HUP/ERROR
readiness. Nothing excludes a connection parked in ContinuationHeader/ContinuationFrame, and two
ordinary paths reach it: a peer sending FIN together with a last incomplete CONTINUATION in one
edge-triggered read, or a graceful_goaway setting draining mid-reassembly — which #1401 established
happens — 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::GoAway arm — the one whose comment calls it the primary truncation
vector
— 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 as GracefulDrainDecision.

A documentation defect this changeset fixes beyond its own scope

Review found that LIFECYCLE.md item 8 and the narrative above invariant 24 still described drain
state with pre-refactor field syntax — self.drain.draining — which no longer compiles, since this
changeset 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 H2StreamTable
extraction, 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, and Context.streams, which is a different
field on a different type.

doc/h2_mux_internals.md carries the same class and is outside this changeset's files; filed as
#1424.

Validation, both feature shapes

cargo +1.93.1 build --all-features --locked                       -> exit 0
cargo +1.93.1 build --locked                                      -> exit 0
cargo +1.93.1 clippy --all-targets --all-features -- -D warnings  -> exit 0
cargo +1.93.1 clippy --all-targets --locked -- -D warnings        -> exit 0
cargo +nightly fmt --all -- --check                               -> exit 0
cargo +1.93.1 test -p sozu-lib --locked protocol::mux             -> 380 passed, 0 failed
python3 .github/scripts/check_doc_citations.py --base origin/refactor/h2-flood-detector -> exit 0

Refs #1336, #1339, #1423, #1424.

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
FlorentinDUBOIS merged commit 95dee16 into main Sep 22, 2026
24 checks passed
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant