Skip to content

fix(mux-h2): defer graceful_goaway's GOAWAY during header-block reassembly - #1401

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
fix/h2-graceful-goaway-clobber
Sep 21, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
fix/h2-graceful-goaway-clobber

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Closes #1398. Third and last known instance of the zero.storage double-duty bug class, after #1396 and #1397 — and the only one that fires unconditionally.

The defect

ConnectionH2::zero is simultaneously the read-side accumulation buffer for a HEADERS+CONTINUATION field block — header_block_fragment is a (start, len) window into it that must stay valid across however many readable() passes the block takes — and a write scratch space.

graceful_goaway took let kawa = &mut self.zero; kawa.storage.clear(); unconditionally, to serialize the initial advisory GOAWAY. Three lines above sat its own comment:

Keep expect_read as-is: existing streams should continue reading data during the drain window opened by the initial GOAWAY.

That intent is exactly what the clear broke. A stream whose HEADERS had arrived and whose CONTINUATION had not lost its accumulated fragment. Unlike #1397, nothing had to coincide: every graceful shutdown and every hot reload landing mid-reassembly corrupted that stream.

The fix: defer, not a second buffer

Mirrors #1397 rather than giving the GOAWAY its own buffer — a second buffer relocates the double-duty problem instead of removing it.

graceful_goaway's body splits into send_initial_goaway(), called either immediately or, when header_block_reassembly_in_progress() is true, from a new deferred stage in flush_pending_control_frames gated on H2DrainState::initial_goaway_pending.

The asymmetry with #1397 had to be handled explicitly: WINDOW_UPDATE and RST_STREAM already had a pending queue, so skipping a drain was free. The GOAWAY had none, so deferring it without a flag would have traded a corruption bug for a lost-GOAWAY bug. The test drives writable() until the deferred frame flushes, then reads the 17 bytes off the peer socket and compares them against an independently generated serializer::gen_goaway encoding.

The forced-close deadline does not move. drain.draining and drain.started_at are still set unconditionally, before the reassembly check, because Mux::shutting_down samples started_at against graceful_shutdown_deadline regardless of whether the wire GOAWAY was deferred. Pinned by its own assertion.

Two further sites needed the flag once it existed:

  • goaway() (the final GOAWAY) clears initial_goaway_pending — it drops expect_read and moves to a terminal state, so a deferred advisory would otherwise fire stale afterwards.
  • flush_zero_buffer() is now also a no-op while reassembly is in progress. Mux::shutting_down_inner calls it directly after graceful_goaway, bypassing writable(), and it would have flushed-and-cleared zero.storage in precisely the deferred-but-unqueued state this fix introduces — reintroducing the clobber one level up. This is lossless because expect_write == Some(Zero), the only case with a legitimate pending zero write, cannot coexist with reassembly in progress: READABLE is disabled for the duration of a stalled zero-buffer write.

Verification

Re-run independently rather than taken from the implementation report.

cargo +1.93.1 build -p sozu-lib                                   exit 0
cargo +1.93.1 clippy -p sozu-lib --all-targets -- -D warnings     exit 0
cargo +1.93.1 test -p sozu-lib --lib protocol::mux::h2            exit 0
   test result: ok. 117 passed; 0 failed
python3 .github/scripts/check_doc_citations.py                    exit 0
python3 .github/scripts/check_doc_citations.py --base origin/main  exit 0

Seen red. Replacing the guard with if false && self.header_block_reassembly_in_progress() fails the new test; with the guard restored it passes, and the tree is byte-identical to the commit afterwards.

One correction to the record, because it matters for this bug class. The implementation report stated the red failure was a wrong header pair — a silent, decodable corruption. I could not reproduce that against the committed fixture, with either the single guard or both disabled. It fails as:

the connection decoder must still resolve the peer's dynamic table after a
graceful_goaway during header-block reassembly, got Err(HeaderIndexOutOfBounds)

a decode error. The test carries both assertions — status.is_ok() and then a byte-for-byte assert_eq! on the decoded pair — so it pins the field block surviving intact either way. But the silent wrong-pair variant is what #1397 exhibited; which of the two a fixture lands on depends on where the CONTINUATION's bytes fall relative to the stale window, not on the bug being different. Recorded so nobody cites this PR for the silent-corruption symptom.

Doc citations

h2.rs moves by ~300 lines, so 58 citations across mux/LIFECYCLE.md, doc/testing.md and doc/h2_mux_internals.md were re-anchored. Passing check_doc_citations.py --base origin/main does not prove those are right — the drift rule excludes any citation whose (path, spans) pair changed, which is exactly the blind spot #1399 documented this morning. So I verified them directly: for each re-anchored citation, the text at the old line under origin/main must equal the text at the new line under HEAD.

re-anchored citations compared: 58  identical: 58  MISMATCH: 0  unresolved: 0

zero.storage audit

The issue asked whether any other site clears it without consulting header_block_reassembly_in_progress(). All seven were classified and no fourth unguarded site was found. handle_header_state's header clear and the final goaway() are state-exclusive; the Discard arm is #1396; the WINDOW_UPDATE/RST_STREAM drains are #1397; frontend_hung_up_while_draining only fires on HUP/ERROR, when no future readable() can supply the awaited CONTINUATION.

On centralising the invariant

Three instances found by three separate investigations in one afternoon is a pattern, not a coincidence, and the per-site grep-and-guard discipline has no structural backstop against a fourth. A wrapper around zero.storage that tracks reassembly internally and refuses to hand out a mutable write view while it is set would make this a type-level invariant rather than one every future call site must remember.

Not done here — it is a refactor across the module and wants a maintainer's approval, not a drive-by in a fix PR.

Beyond the fix this is documentation only: CHANGELOG.md gains a Security entry in the same format as #1396/#1397, and doc/h2_mux_internals.md plus mux/LIFECYCLE.md document the new deferred stage. No Cargo.toml touched; no async fn added to lib/.

…embly

graceful_goaway's first GOAWAY(NO_ERROR, last_stream_id=MAX) unconditionally
cleared and reused self.zero.storage to serialize itself, directly
contradicting its own comment's promise that in-flight streams keep reading
during the drain window: zero.storage is also the read-side accumulation
buffer for a HEADERS+CONTINUATION field block in progress, and
headers.header_block_fragment stays a (start, len) window into it across
however many readable() passes the block takes. Clearing the buffer mid-block
destroyed that window's contents while the recorded length kept growing,
so the eventual HPACK decode read past the genuinely-filled region into
zero-initialized stale bytes and produced a wrong, but still decodable,
header pair -- CAUSE: h2.rs graceful_goaway's unconditional
self.zero.storage.clear() -> corrupts the field-block bytes
header_block_fragment still points at -> SYMPTOM: the peer's CONTINUATION
decodes into the wrong name/value pair with no visible error. This is the
third instance of the same zero.storage double-duty bug class (#1396, #1397)
and the only one that fires unconditionally: no refusal and no coincident
control frame is required, every graceful shutdown or hot reload landing
mid-reassembly hit it.

The fix defers, mirroring flush_pending_control_frames's existing
WINDOW_UPDATE/RST_STREAM defer pattern rather than giving the GOAWAY its own
buffer: reusing header_block_reassembly_in_progress() and the same
event-loop invariant (frontend readable() then writable() in the same sweep)
needs no new state machine, and a second scratch buffer would only move the
double-duty problem rather than removing it. The one asymmetry against the
precedent: WINDOW_UPDATE/RST_STREAM already had a pending queue to fall back
on, so skipping their drain was free. A deferred GOAWAY has no such queue, so
send_initial_goaway() (split out of graceful_goaway's original body) is now
also invoked from a new stage in flush_pending_control_frames, gated on the
new H2DrainState::initial_goaway_pending flag, which drains it as soon as
reassembly completes -- guaranteeing the advisory GOAWAY is still emitted
rather than traded for a lost-GOAWAY bug. self.drain.draining and
self.drain.started_at are still set unconditionally before the deferral
check, so Mux::shutting_down's forced-close budget still arms at the moment
the proxy decides to drain, not once the wire GOAWAY eventually goes out.

Two more sites needed a look once the flag existed. goaway() (the final
GOAWAY) now also clears initial_goaway_pending: it drops expect_read and
moves to a terminal state, so no further readable() will ever complete the
reassembly the advisory GOAWAY was waiting on, and sending it afterward
would only be a redundant, less informative GOAWAY. flush_zero_buffer() --
called directly by Mux::shutting_down right after graceful_goaway, bypassing
writable() because edge-triggered epoll will not deliver a fresh WRITABLE
event for an already-writable socket -- is now also a no-op while reassembly
is in progress: without that guard it would unconditionally flush (and
clear) zero.storage in exactly the deferred-but-unflushed state
graceful_goaway's own defer exists to protect, reintroducing the same
clobber one level up. That guard is provably lossless: expect_write ==
Some(H2StreamId::Zero) is the only state with a legitimate pending write
here, and it already cannot coexist with reassembly in progress -- READABLE
is disabled for the whole time a zero-buffer write is stalled, so a fresh
frame read can never start mid-write.

Audited every other self.zero.storage clear/reuse site for the same class:
- handle_header_state's unconditional clear (generic 9-byte frame-header
  consume): not-a-clobber -- self.state == H2State::Header is mutually
  exclusive with ContinuationHeader/ContinuationFrame, so it can never run
  while a block is mid-reassembly.
- The H2State::Discard arm's clear: guarded by #1396 (decodes the discarded
  field block first); also not-a-clobber by the same state-exclusivity
  argument as above.
- flush_pending_control_frames's frontend_hung_up_while_draining() clear:
  unguarded by header_block_reassembly_in_progress(), but not-a-clobber --
  it only fires on a HUP/ERROR readiness event, meaning the peer is already
  gone and no further readable() will ever supply the CONTINUATION this
  buffer might be awaiting.
- The WINDOW_UPDATE and RST_STREAM drain stages: guarded by #1397.
- graceful_goaway's clear: the bug this commit fixes.
- flush_zero_to_socket's post-drain clear: guarded transitively -- every
  caller either already checked header_block_reassembly_in_progress()
  (WINDOW_UPDATE/RST_STREAM/deferred-GOAWAY stages) or is the "resume"
  stage, which only runs when expect_write == Some(Zero), itself mutually
  exclusive with reassembly in progress per the argument above.
- goaway() (the final GOAWAY)'s clear: not-a-clobber -- it sets
  state = H2State::Error and expect_read = None in the same call, so no
  further readable() will ever try to complete the reassembly it clobbers.

No fourth unguarded site found. Three independent investigations finding the
same bug class at three different call sites is a real signal that the
invariant wants enforcing structurally (e.g. a newtype wrapping zero.storage
that refuses to hand out a mutable write view while reassembly is recorded
in progress) rather than by a grep-and-add-a-check discipline at each new
call site -- flagged for the maintainer, not attempted here.

Regression test a_legitimate_continuation_survives_a_graceful_goaway, in the
shape of a_legitimate_continuation_survives_an_unrelated_window_update_flush:
sends HEADERS without END_HEADERS, calls graceful_goaway (and, matching
Mux::shutting_down's exact call sequence, flush_zero_buffer right after),
sends the CONTINUATION, and asserts the peer's next HPACK reference decodes
byte-for-byte. Confirmed red against the unfixed behaviour with the
production guards disabled: the assertion fails with a wrong pair --
left: [("from", "\rx-sozu-marker\x10legitimate-value" + 34 zero bytes)],
right: [("x-sozu-marker", "legitimate-value")] -- decode success on the
wrong bytes, not a decode error, matching this bug class's defining silent
symptom. Restoring the guards turns it green. The production diff shares no
literal with the test's header names, values, or path, so the fix is a
general structural guard, not shaped to this test's specific bytes.

LIFECYCLE.md and doc/h2_mux_internals.md gain the new invariant and stage;
64 h2.rs:NNN citations in LIFECYCLE.md and 1 in doc/testing.md are
re-anchored for this changeset's own line shift (verified against the
pre-change file: all 64 mapped citations resolve to byte-identical content).
check_doc_citations.py --base origin/main reports 0 unresolved and 0 drifted.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 42df3fd into main Sep 21, 2026
24 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/h2-graceful-goaway-clobber branch September 21, 2026 14:14
FlorentinDUBOIS added a commit that referenced this pull request Sep 22, 2026
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 added a commit that referenced this pull request Sep 22, 2026
…ol-frame scratch

ConnectionH2::zero served two incompatible roles: the read-side accumulator
a HEADERS/CONTINUATION field block was reassembled into across however many
readable() passes a block took (headers.header_block_fragment, a window
over zero.storage), and the write-side scratch buffer every control-frame
flush (WINDOW_UPDATE, RST_STREAM, GOAWAY) clears and reuses. Three bugs
(#1396, #1397, #1401) shipped from the two roles sharing one buffer, each
patched with its own header_block_reassembly_in_progress() guard, and a
fourth site (#1423) was found unguarded while landing the third.

Add h2_header_reassembly.rs: HeaderBlockAccumulator owns its bytes (Vec<u8>,
no new dependency) instead of borrowing a window into zero.storage. The
initiating HEADERS frame's fragment is copied out and zero.storage cleared
in the same step that enters ContinuationHeader; each CONTINUATION frame's
payload is folded in and zero.storage cleared again in the same step that
leaves ContinuationFrame; the block is retired (decoded, or handed unread
to the CVE-2024-27316 refusal path) through the single exit point matching
the single entry point. The old zero.storage.end -= 9 trick that kept a
CONTINUATION frame's incoming header from disturbing the accumulated
fragment's physical position is gone; every zero-stream frame now frees
zero.storage the same way every other frame type already did.

No write-side code holds a field named header_reassembly, so a
control-frame flush cannot reach the accumulated bytes of a reassembly in
progress on its own: that write-side half of the collision is
unrepresentable by construction, in every build profile. It is not the
whole story. Review of the first version of this change found two hazards
the type does not close by itself:

- A same-module, read-side misuse can still leak the accumulator across
  streams: handle_headers_frame's RFC 9113 5.3.1 self-dependency early
  return retired the stream without retiring the accumulator, so the next
  HEADERS frame on an unrelated stream decoded against the previous
  stream's stale bytes. Fixed by retiring the accumulator on that return
  before the reset_stream/remove_dead_stream/return, and adding a
  debug_assert on the fast path confirming it never observes in-progress
  state there. debug_assert compiles out in release, so the type does not
  make this class of bug impossible by itself - it is caught here only
  because a human reviewed the code path. "Unrepresentable by construction"
  is therefore true for the write side only; the module doc, LIFECYCLE.md
  and CHANGELOG.md now say exactly that instead of overclaiming it for the
  whole type, and no longer claim a release build panics loudly on misuse
  (debug_assert compiles out there; a release build silently starts a
  fresh block instead, the #1396/#1397 shape).
- Closes #1423 was justified on a false premise: that Ready::HUP means "the
  peer will send no more bytes," so the frontend-hung-up-while-draining
  stage could discard zero.storage unconditionally without ever touching a
  reassembly in progress. mio's is_read_closed() (which Ready::HUP is
  defined from) is true on a TCP half-close with data still queued in the
  kernel receive buffer, not only on a fully drained close, so a
  CONTINUATION frame split across TCP segments can still have its second
  segment readable after HUP fires. The stage now carries the same
  header_block_reassembly_in_progress() guard its five sibling call sites
  already had (the WINDOW_UPDATE-drain and RST_STREAM-drain stages in the
  same function, the deferred-initial-GOAWAY stage beside them,
  graceful_goaway's drain-defer decision, and flush_zero_buffer),
  restoring the guard the first version of this change removed. #1423 is
  closed by this changeset, but not by the mechanism the first version
  claimed.

The property test (reassembly_property) is extended: it now actually
composes a graceful_goaway deferral into the same interleave set as the
WINDOW_UPDATE/RST_STREAM/HUP-while-draining triggers - the first version
claimed this in four places without doing it, and generated a dead
zeroth interleave that was never read - and generates each interleave
point at either a frame boundary or mid-frame, splitting a CONTINUATION
fragment's own bytes across two simulated TCP segments so the accumulator
actually holds unretired bytes when the interleave fires; generating
whole-frame writes only, as the first version did, always found
zero.storage empty at interleave time and could not reach the B2 shape at
all. Composing the deferral surfaced its own bug during development: the
HUP-while-draining interleave's test-only drain-flag setter also flips
draining() to true, so a plan combining both would silently take the
already-draining branch of graceful_goaway instead of deferring - fixed by
checking connection.drain.draining() directly instead of a separately
tracked "did we already send GOAWAY" flag.

Tests: a_legitimate_continuation_survives_a_hup_while_draining still pins
the frame-boundary shape of #1423; a new
a_continuation_frame_split_by_tcp_segmentation_survives_a_hup_while_draining
pins the mid-frame shape B2 found, red on the unguarded stage (reproducing
the predicted StringDecodingError(NotEnoughOctets) desync) and green with
the guard restored; a new
a_priority_self_dependency_reset_does_not_leak_the_reassembly_accumulator
pins the accumulator leak, red on the un-retired early return and green
after; the three existing pinning tests for #1396/#1397/#1401 still pass;
the extended quickcheck property passes at both its default iteration
count and at QUICKCHECK_TESTS=2000; the e2e test
(try_h2_continuation_survives_a_graceful_drain_mid_reassembly) now asserts
a GOAWAY witness so it cannot pass on a run where the race it targets never
fired.

LIFECYCLE.md invariant 24, doc/h2_mux_internals.md, doc/testing.md and
CHANGELOG.md updated for both the original design and these findings, and
softened where the first version overclaimed. Citation drift re-anchored
throughout LIFECYCLE.md, including drift this changeset's own edits
introduced after an earlier re-anchoring pass missed a later hunk; a small
number of pre-existing wrong citations unrelated to this change (three in
LIFECYCLE.md, one in doc/testing.md, and a handful in CHANGELOG.md's
timer-accuracy entry that predate this branch and are outside the citation
checker's doc/ + LIFECYCLE.md scope) are left as found. CHANGELOG.md also
now documents the copy-cost trade-off of the multi-frame path (one memcpy
per CONTINUATION frame, offset by the CVE-2024-27316 refusal path's old
eager copy going away) and a behaviour change: payload_len >
available_space() no longer implicitly caps a block's total size at the
zero buffer's capacity now that zero.storage is cleared every frame
instead of held for the whole block - only max_header_list_size (default
65536) still does.

Round 2 (independent re-review of `bf407254`): CI runs `check_doc_citations.py
--base "${{ github.event.pull_request.base.sha }}"` (`.github/workflows/ci.yml`), which for this
branch is `f76c8eb3` — a check this changeset had never actually run. Against that exact base it
exited 1 on a citation this changeset re-anchored to `h2.rs:6058` (the "close" backend-stream
teardown line): a DIFFERENT LIFECYCLE.md citation happened to read that same number at `f76c8eb3`,
and the checker's own drift rule keys identity on the (path, number) pair, not on which paragraph
carries it. Re-anchored to the range `h2.rs:6057-6059`, which cannot collide, per the checker's
own advice ("or better, cite a symbol"): `check_doc_citations.py --base f76c8eb` now exits 0.

The round-1 report of "15 citations found and fixed, all verified" undercounted: it missed the
`end_stream` Client/Server range pair (`LIFECYCLE.md:1030`/`:1033`, off by the same +17 as the rest
but never actually corrected despite being investigated), and left two disclosed-as-pre-existing
citations (`LIFECYCLE.md:303`, `:323`) that were in fact fixable now that their exact-source targets
were re-derived directly (`grep -n` for the construct each sentence names, not an offset formula) —
`:303`'s three-site illustration list now reads `h2.rs:6097/6194/6219` (`reset_stream`'s reset,
`end_stream`'s Client-arm and Server-arm `ForwardTerminated` retirements — all independently
grep-verified `StreamState::Unlinked` assignment sites), and `:323`'s `unlink_stream` call-site pair
now reads `h2.rs:6145/6089` (keeping `6089`, which was already correct). `doc/testing.md`'s own
`emit_pending_size_update_if_new_block` arm site drifted the same way, `h2.rs:5424` (now itself a
different-but-real `handle_rst_stream_frame` citation) corrected to `h2.rs:5476`
(`self.pending_table_size_update = Some(capped);`). This round independently re-enumerated every
citation whose value differs from `f76c8eb3` (91 across `LIFECYCLE.md` and `doc/testing.md` by this
round's own count — broader than a narrower "re-anchored only" count, since it also covers freshly
authored citations, not just re-anchored ones) and verified each by reading the cited source line(s)
against the sentence's own claim, not by re-deriving from the same shift formula that produced these
errors. All checked out except the ones named above, now fixed, and the one citation
(`LIFECYCLE.md:371`) this changeset's own text already discloses as pre-existing and intentionally
left. `check_doc_citations.py --base f76c8eb` exits 0.

Two more items from this round. First, a residual this changeset's B2 guard opens: with
`h2_graceful_shutdown_deadline_seconds` explicitly set to `0` (`None`, "indefinite wait explicitly
opted in" per `h2_drain.rs`'s own doc comment), `Mux::shutting_down_inner`'s forced-close branch
never fires, and a peer dying mid-CONTINUATION during a drain leaves `zero.storage` non-empty
forever — `ConnectionH2::has_pending_write` (`h2.rs:4400-4407`) never flips to `false`, and shutdown
waits indefinitely. Traced through source rather than assumed; documented in CHANGELOG.md as a real,
narrow (opt-out-of-the-default-deadline-only) hole the fix opens, not fixed in this changeset. Second,
`check_doc_citations.py`'s `doc_files()` never covers `CHANGELOG.md` (108 `file.rs:NNN` matches,
105 unique, by this script's own `CITATION` regex, none of them checked by anything) — recorded
in that function's own docstring.

Round 3 (final): two one-line corrections from a second independent pass. `LIFECYCLE.md:303`'s
"Transitions:" enumeration cited three of the four real `StreamState::Unlinked` assignment sites
(`h2.rs:6097/6194/6219`) and silently dropped the fourth: `6237` is `EndStreamAction::CloseDelimited`'s
sibling arm to `6219`'s `ForwardTerminated`, in the same `match end_stream_decision(stream)` — now
`h2.rs:6097/6194/6219/6237`. And this changeset's own prior claim of "102 citations, measured" in
`check_doc_citations.py`'s docstring was itself unverified: counted with the script's own `CITATION`
regex (`PATH = r"[A-Za-z0-9_][A-Za-z0-9_./-]*\.rs"`, `SPAN = r"[0-9]+(?:-[0-9]+)?"`) rather than an
ad hoc backtick-anchored grep, CHANGELOG.md carries 108 matches (105 unique `(path, spans)` pairs) —
the backtick requirement in the earlier grep silently excluded citations not wrapped in backticks.
Docstring corrected to state both numbers and the regex used to produce them.
`check_doc_citations.py --base f76c8eb` and `--self-test` both
exit 0.

Round 4 (final, PR #1440 CI fix): CI's `Doc citations` job gates on the pull request's base sha
(`github.event.pull_request.base.sha`), which for a branch stacked on another branch but opened
against `main` is `main`'s sha, not the parent branch's — for #1440 that is `595920e91c45`, not
`f76c8eb3`. Both prior rounds verified only against `f76c8eb3` (the direct parent), which was
insufficient: `mod.rs:1339` at `LIFECYCLE.md:681` and `:696` (both citing `counter`'s declaration in
`Mux::ready_inner`) were already correct relative to `f76c8eb3` — unchanged, unmoved, genuinely
accurate — but wrong relative to `595920e91c45`, because unrelated commits between that main sha and
`f76c8eb3` shifted `mod.rs` and coincidentally left `mod.rs:1339` holding different, also-plausible
content (`if self.frontend.readiness().event.is_hup()`) at the older base. Re-derived from the
construct each sentence names (`grep -n 'let mut counter = 0;' mod.rs` -> `1339`, inside
`fn ready_inner`, confirmed `1338` is that function's closing `) -> SessionResult {` and `1339` is
the declaration itself — both non-blank, so a tight range is valid) and re-anchored both citations
to `mod.rs:1338-1339`, breaking the collision with the stale base-era content the same way as the
earlier `6058`/`2706` collisions. `check_doc_citations.py --base 595920e` and `--base f76c8eb`
both exit 0. `cargo +nightly fmt --all -- --check` exits 0; nothing else re-run since only
`LIFECYCLE.md` changed.

Closes #1423

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 22, 2026
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 added a commit that referenced this pull request Sep 22, 2026
…ol-frame scratch

ConnectionH2::zero served two incompatible roles: the read-side accumulator
a HEADERS/CONTINUATION field block was reassembled into across however many
readable() passes a block took (headers.header_block_fragment, a window
over zero.storage), and the write-side scratch buffer every control-frame
flush (WINDOW_UPDATE, RST_STREAM, GOAWAY) clears and reuses. Three bugs
(#1396, #1397, #1401) shipped from the two roles sharing one buffer, each
patched with its own header_block_reassembly_in_progress() guard, and a
fourth site (#1423) was found unguarded while landing the third.

Add h2_header_reassembly.rs: HeaderBlockAccumulator owns its bytes (Vec<u8>,
no new dependency) instead of borrowing a window into zero.storage. The
initiating HEADERS frame's fragment is copied out and zero.storage cleared
in the same step that enters ContinuationHeader; each CONTINUATION frame's
payload is folded in and zero.storage cleared again in the same step that
leaves ContinuationFrame; the block is retired (decoded, or handed unread
to the CVE-2024-27316 refusal path) through the single exit point matching
the single entry point. The old zero.storage.end -= 9 trick that kept a
CONTINUATION frame's incoming header from disturbing the accumulated
fragment's physical position is gone; every zero-stream frame now frees
zero.storage the same way every other frame type already did.

No write-side code holds a field named header_reassembly, so a
control-frame flush cannot reach the accumulated bytes of a reassembly in
progress on its own: that write-side half of the collision is
unrepresentable by construction, in every build profile. It is not the
whole story. Review of the first version of this change found two hazards
the type does not close by itself:

- A same-module, read-side misuse can still leak the accumulator across
  streams: handle_headers_frame's RFC 9113 5.3.1 self-dependency early
  return retired the stream without retiring the accumulator, so the next
  HEADERS frame on an unrelated stream decoded against the previous
  stream's stale bytes. Fixed by retiring the accumulator on that return
  before the reset_stream/remove_dead_stream/return, and adding a
  debug_assert on the fast path confirming it never observes in-progress
  state there. debug_assert compiles out in release, so the type does not
  make this class of bug impossible by itself - it is caught here only
  because a human reviewed the code path. "Unrepresentable by construction"
  is therefore true for the write side only; the module doc, LIFECYCLE.md
  and CHANGELOG.md now say exactly that instead of overclaiming it for the
  whole type, and no longer claim a release build panics loudly on misuse
  (debug_assert compiles out there; a release build silently starts a
  fresh block instead, the #1396/#1397 shape).
- Closes #1423 was justified on a false premise: that Ready::HUP means "the
  peer will send no more bytes," so the frontend-hung-up-while-draining
  stage could discard zero.storage unconditionally without ever touching a
  reassembly in progress. mio's is_read_closed() (which Ready::HUP is
  defined from) is true on a TCP half-close with data still queued in the
  kernel receive buffer, not only on a fully drained close, so a
  CONTINUATION frame split across TCP segments can still have its second
  segment readable after HUP fires. The stage now carries the same
  header_block_reassembly_in_progress() guard its five sibling call sites
  already had (the WINDOW_UPDATE-drain and RST_STREAM-drain stages in the
  same function, the deferred-initial-GOAWAY stage beside them,
  graceful_goaway's drain-defer decision, and flush_zero_buffer),
  restoring the guard the first version of this change removed. #1423 is
  closed by this changeset, but not by the mechanism the first version
  claimed.

The property test (reassembly_property) is extended: it now actually
composes a graceful_goaway deferral into the same interleave set as the
WINDOW_UPDATE/RST_STREAM/HUP-while-draining triggers - the first version
claimed this in four places without doing it, and generated a dead
zeroth interleave that was never read - and generates each interleave
point at either a frame boundary or mid-frame, splitting a CONTINUATION
fragment's own bytes across two simulated TCP segments so the accumulator
actually holds unretired bytes when the interleave fires; generating
whole-frame writes only, as the first version did, always found
zero.storage empty at interleave time and could not reach the B2 shape at
all. Composing the deferral surfaced its own bug during development: the
HUP-while-draining interleave's test-only drain-flag setter also flips
draining() to true, so a plan combining both would silently take the
already-draining branch of graceful_goaway instead of deferring - fixed by
checking connection.drain.draining() directly instead of a separately
tracked "did we already send GOAWAY" flag.

Tests: a_legitimate_continuation_survives_a_hup_while_draining still pins
the frame-boundary shape of #1423; a new
a_continuation_frame_split_by_tcp_segmentation_survives_a_hup_while_draining
pins the mid-frame shape B2 found, red on the unguarded stage (reproducing
the predicted StringDecodingError(NotEnoughOctets) desync) and green with
the guard restored; a new
a_priority_self_dependency_reset_does_not_leak_the_reassembly_accumulator
pins the accumulator leak, red on the un-retired early return and green
after; the three existing pinning tests for #1396/#1397/#1401 still pass;
the extended quickcheck property passes at both its default iteration
count and at QUICKCHECK_TESTS=2000; the e2e test
(try_h2_continuation_survives_a_graceful_drain_mid_reassembly) now asserts
a GOAWAY witness so it cannot pass on a run where the race it targets never
fired.

LIFECYCLE.md invariant 24, doc/h2_mux_internals.md, doc/testing.md and
CHANGELOG.md updated for both the original design and these findings, and
softened where the first version overclaimed. Citation drift re-anchored
throughout LIFECYCLE.md, including drift this changeset's own edits
introduced after an earlier re-anchoring pass missed a later hunk; a small
number of pre-existing wrong citations unrelated to this change (three in
LIFECYCLE.md, one in doc/testing.md, and a handful in CHANGELOG.md's
timer-accuracy entry that predate this branch and are outside the citation
checker's doc/ + LIFECYCLE.md scope) are left as found. CHANGELOG.md also
now documents the copy-cost trade-off of the multi-frame path (one memcpy
per CONTINUATION frame, offset by the CVE-2024-27316 refusal path's old
eager copy going away) and a behaviour change: payload_len >
available_space() no longer implicitly caps a block's total size at the
zero buffer's capacity now that zero.storage is cleared every frame
instead of held for the whole block - only max_header_list_size (default
65536) still does.

Round 2 (independent re-review of `bf407254`): CI runs `check_doc_citations.py
--base "${{ github.event.pull_request.base.sha }}"` (`.github/workflows/ci.yml`), which for this
branch is `f76c8eb3` — a check this changeset had never actually run. Against that exact base it
exited 1 on a citation this changeset re-anchored to `h2.rs:6058` (the "close" backend-stream
teardown line): a DIFFERENT LIFECYCLE.md citation happened to read that same number at `f76c8eb3`,
and the checker's own drift rule keys identity on the (path, number) pair, not on which paragraph
carries it. Re-anchored to the range `h2.rs:6057-6059`, which cannot collide, per the checker's
own advice ("or better, cite a symbol"): `check_doc_citations.py --base f76c8eb` now exits 0.

The round-1 report of "15 citations found and fixed, all verified" undercounted: it missed the
`end_stream` Client/Server range pair (`LIFECYCLE.md:1030`/`:1033`, off by the same +17 as the rest
but never actually corrected despite being investigated), and left two disclosed-as-pre-existing
citations (`LIFECYCLE.md:303`, `:323`) that were in fact fixable now that their exact-source targets
were re-derived directly (`grep -n` for the construct each sentence names, not an offset formula) —
`:303`'s three-site illustration list now reads `h2.rs:6097/6194/6219` (`reset_stream`'s reset,
`end_stream`'s Client-arm and Server-arm `ForwardTerminated` retirements — all independently
grep-verified `StreamState::Unlinked` assignment sites), and `:323`'s `unlink_stream` call-site pair
now reads `h2.rs:6145/6089` (keeping `6089`, which was already correct). `doc/testing.md`'s own
`emit_pending_size_update_if_new_block` arm site drifted the same way, `h2.rs:5424` (now itself a
different-but-real `handle_rst_stream_frame` citation) corrected to `h2.rs:5476`
(`self.pending_table_size_update = Some(capped);`). This round independently re-enumerated every
citation whose value differs from `f76c8eb3` (91 across `LIFECYCLE.md` and `doc/testing.md` by this
round's own count — broader than a narrower "re-anchored only" count, since it also covers freshly
authored citations, not just re-anchored ones) and verified each by reading the cited source line(s)
against the sentence's own claim, not by re-deriving from the same shift formula that produced these
errors. All checked out except the ones named above, now fixed, and the one citation
(`LIFECYCLE.md:371`) this changeset's own text already discloses as pre-existing and intentionally
left. `check_doc_citations.py --base f76c8eb` exits 0.

Two more items from this round. First, a residual this changeset's B2 guard opens: with
`h2_graceful_shutdown_deadline_seconds` explicitly set to `0` (`None`, "indefinite wait explicitly
opted in" per `h2_drain.rs`'s own doc comment), `Mux::shutting_down_inner`'s forced-close branch
never fires, and a peer dying mid-CONTINUATION during a drain leaves `zero.storage` non-empty
forever — `ConnectionH2::has_pending_write` (`h2.rs:4400-4407`) never flips to `false`, and shutdown
waits indefinitely. Traced through source rather than assumed; documented in CHANGELOG.md as a real,
narrow (opt-out-of-the-default-deadline-only) hole the fix opens, not fixed in this changeset. Second,
`check_doc_citations.py`'s `doc_files()` never covers `CHANGELOG.md` (108 `file.rs:NNN` matches,
105 unique, by this script's own `CITATION` regex, none of them checked by anything) — recorded
in that function's own docstring.

Round 3 (final): two one-line corrections from a second independent pass. `LIFECYCLE.md:303`'s
"Transitions:" enumeration cited three of the four real `StreamState::Unlinked` assignment sites
(`h2.rs:6097/6194/6219`) and silently dropped the fourth: `6237` is `EndStreamAction::CloseDelimited`'s
sibling arm to `6219`'s `ForwardTerminated`, in the same `match end_stream_decision(stream)` — now
`h2.rs:6097/6194/6219/6237`. And this changeset's own prior claim of "102 citations, measured" in
`check_doc_citations.py`'s docstring was itself unverified: counted with the script's own `CITATION`
regex (`PATH = r"[A-Za-z0-9_][A-Za-z0-9_./-]*\.rs"`, `SPAN = r"[0-9]+(?:-[0-9]+)?"`) rather than an
ad hoc backtick-anchored grep, CHANGELOG.md carries 108 matches (105 unique `(path, spans)` pairs) —
the backtick requirement in the earlier grep silently excluded citations not wrapped in backticks.
Docstring corrected to state both numbers and the regex used to produce them.
`check_doc_citations.py --base f76c8eb` and `--self-test` both
exit 0.

Round 4 (final, PR #1440 CI fix): CI's `Doc citations` job gates on the pull request's base sha
(`github.event.pull_request.base.sha`), which for a branch stacked on another branch but opened
against `main` is `main`'s sha, not the parent branch's — for #1440 that is `595920e91c45`, not
`f76c8eb3`. Both prior rounds verified only against `f76c8eb3` (the direct parent), which was
insufficient: `mod.rs:1339` at `LIFECYCLE.md:681` and `:696` (both citing `counter`'s declaration in
`Mux::ready_inner`) were already correct relative to `f76c8eb3` — unchanged, unmoved, genuinely
accurate — but wrong relative to `595920e91c45`, because unrelated commits between that main sha and
`f76c8eb3` shifted `mod.rs` and coincidentally left `mod.rs:1339` holding different, also-plausible
content (`if self.frontend.readiness().event.is_hup()`) at the older base. Re-derived from the
construct each sentence names (`grep -n 'let mut counter = 0;' mod.rs` -> `1339`, inside
`fn ready_inner`, confirmed `1338` is that function's closing `) -> SessionResult {` and `1339` is
the declaration itself — both non-blank, so a tight range is valid) and re-anchored both citations
to `mod.rs:1338-1339`, breaking the collision with the stale base-era content the same way as the
earlier `6058`/`2706` collisions. `check_doc_citations.py --base 595920e` and `--base f76c8eb`
both exit 0. `cargo +nightly fmt --all -- --check` exits 0; nothing else re-run since only
`LIFECYCLE.md` changed.

Closes #1423

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 22, 2026
…lush cannot clobber header reassembly (#1440)

* refactor(mux-h2): separate HEADERS+CONTINUATION reassembly from control-frame scratch

ConnectionH2::zero served two incompatible roles: the read-side accumulator
a HEADERS/CONTINUATION field block was reassembled into across however many
readable() passes a block took (headers.header_block_fragment, a window
over zero.storage), and the write-side scratch buffer every control-frame
flush (WINDOW_UPDATE, RST_STREAM, GOAWAY) clears and reuses. Three bugs
(#1396, #1397, #1401) shipped from the two roles sharing one buffer, each
patched with its own header_block_reassembly_in_progress() guard, and a
fourth site (#1423) was found unguarded while landing the third.

Add h2_header_reassembly.rs: HeaderBlockAccumulator owns its bytes (Vec<u8>,
no new dependency) instead of borrowing a window into zero.storage. The
initiating HEADERS frame's fragment is copied out and zero.storage cleared
in the same step that enters ContinuationHeader; each CONTINUATION frame's
payload is folded in and zero.storage cleared again in the same step that
leaves ContinuationFrame; the block is retired (decoded, or handed unread
to the CVE-2024-27316 refusal path) through the single exit point matching
the single entry point. The old zero.storage.end -= 9 trick that kept a
CONTINUATION frame's incoming header from disturbing the accumulated
fragment's physical position is gone; every zero-stream frame now frees
zero.storage the same way every other frame type already did.

No write-side code holds a field named header_reassembly, so a
control-frame flush cannot reach the accumulated bytes of a reassembly in
progress on its own: that write-side half of the collision is
unrepresentable by construction, in every build profile. It is not the
whole story. Review of the first version of this change found two hazards
the type does not close by itself:

- A same-module, read-side misuse can still leak the accumulator across
  streams: handle_headers_frame's RFC 9113 5.3.1 self-dependency early
  return retired the stream without retiring the accumulator, so the next
  HEADERS frame on an unrelated stream decoded against the previous
  stream's stale bytes. Fixed by retiring the accumulator on that return
  before the reset_stream/remove_dead_stream/return, and adding a
  debug_assert on the fast path confirming it never observes in-progress
  state there. debug_assert compiles out in release, so the type does not
  make this class of bug impossible by itself - it is caught here only
  because a human reviewed the code path. "Unrepresentable by construction"
  is therefore true for the write side only; the module doc, LIFECYCLE.md
  and CHANGELOG.md now say exactly that instead of overclaiming it for the
  whole type, and no longer claim a release build panics loudly on misuse
  (debug_assert compiles out there; a release build silently starts a
  fresh block instead, the #1396/#1397 shape).
- Closes #1423 was justified on a false premise: that Ready::HUP means "the
  peer will send no more bytes," so the frontend-hung-up-while-draining
  stage could discard zero.storage unconditionally without ever touching a
  reassembly in progress. mio's is_read_closed() (which Ready::HUP is
  defined from) is true on a TCP half-close with data still queued in the
  kernel receive buffer, not only on a fully drained close, so a
  CONTINUATION frame split across TCP segments can still have its second
  segment readable after HUP fires. The stage now carries the same
  header_block_reassembly_in_progress() guard its five sibling call sites
  already had (the WINDOW_UPDATE-drain and RST_STREAM-drain stages in the
  same function, the deferred-initial-GOAWAY stage beside them,
  graceful_goaway's drain-defer decision, and flush_zero_buffer),
  restoring the guard the first version of this change removed. #1423 is
  closed by this changeset, but not by the mechanism the first version
  claimed.

The property test (reassembly_property) is extended: it now actually
composes a graceful_goaway deferral into the same interleave set as the
WINDOW_UPDATE/RST_STREAM/HUP-while-draining triggers - the first version
claimed this in four places without doing it, and generated a dead
zeroth interleave that was never read - and generates each interleave
point at either a frame boundary or mid-frame, splitting a CONTINUATION
fragment's own bytes across two simulated TCP segments so the accumulator
actually holds unretired bytes when the interleave fires; generating
whole-frame writes only, as the first version did, always found
zero.storage empty at interleave time and could not reach the B2 shape at
all. Composing the deferral surfaced its own bug during development: the
HUP-while-draining interleave's test-only drain-flag setter also flips
draining() to true, so a plan combining both would silently take the
already-draining branch of graceful_goaway instead of deferring - fixed by
checking connection.drain.draining() directly instead of a separately
tracked "did we already send GOAWAY" flag.

Tests: a_legitimate_continuation_survives_a_hup_while_draining still pins
the frame-boundary shape of #1423; a new
a_continuation_frame_split_by_tcp_segmentation_survives_a_hup_while_draining
pins the mid-frame shape B2 found, red on the unguarded stage (reproducing
the predicted StringDecodingError(NotEnoughOctets) desync) and green with
the guard restored; a new
a_priority_self_dependency_reset_does_not_leak_the_reassembly_accumulator
pins the accumulator leak, red on the un-retired early return and green
after; the three existing pinning tests for #1396/#1397/#1401 still pass;
the extended quickcheck property passes at both its default iteration
count and at QUICKCHECK_TESTS=2000; the e2e test
(try_h2_continuation_survives_a_graceful_drain_mid_reassembly) now asserts
a GOAWAY witness so it cannot pass on a run where the race it targets never
fired.

LIFECYCLE.md invariant 24, doc/h2_mux_internals.md, doc/testing.md and
CHANGELOG.md updated for both the original design and these findings, and
softened where the first version overclaimed. Citation drift re-anchored
throughout LIFECYCLE.md, including drift this changeset's own edits
introduced after an earlier re-anchoring pass missed a later hunk; a small
number of pre-existing wrong citations unrelated to this change (three in
LIFECYCLE.md, one in doc/testing.md, and a handful in CHANGELOG.md's
timer-accuracy entry that predate this branch and are outside the citation
checker's doc/ + LIFECYCLE.md scope) are left as found. CHANGELOG.md also
now documents the copy-cost trade-off of the multi-frame path (one memcpy
per CONTINUATION frame, offset by the CVE-2024-27316 refusal path's old
eager copy going away) and a behaviour change: payload_len >
available_space() no longer implicitly caps a block's total size at the
zero buffer's capacity now that zero.storage is cleared every frame
instead of held for the whole block - only max_header_list_size (default
65536) still does.

Round 2 (independent re-review of `bf407254`): CI runs `check_doc_citations.py
--base "${{ github.event.pull_request.base.sha }}"` (`.github/workflows/ci.yml`), which for this
branch is `f76c8eb3` — a check this changeset had never actually run. Against that exact base it
exited 1 on a citation this changeset re-anchored to `h2.rs:6058` (the "close" backend-stream
teardown line): a DIFFERENT LIFECYCLE.md citation happened to read that same number at `f76c8eb3`,
and the checker's own drift rule keys identity on the (path, number) pair, not on which paragraph
carries it. Re-anchored to the range `h2.rs:6057-6059`, which cannot collide, per the checker's
own advice ("or better, cite a symbol"): `check_doc_citations.py --base f76c8eb` now exits 0.

The round-1 report of "15 citations found and fixed, all verified" undercounted: it missed the
`end_stream` Client/Server range pair (`LIFECYCLE.md:1030`/`:1033`, off by the same +17 as the rest
but never actually corrected despite being investigated), and left two disclosed-as-pre-existing
citations (`LIFECYCLE.md:303`, `:323`) that were in fact fixable now that their exact-source targets
were re-derived directly (`grep -n` for the construct each sentence names, not an offset formula) —
`:303`'s three-site illustration list now reads `h2.rs:6097/6194/6219` (`reset_stream`'s reset,
`end_stream`'s Client-arm and Server-arm `ForwardTerminated` retirements — all independently
grep-verified `StreamState::Unlinked` assignment sites), and `:323`'s `unlink_stream` call-site pair
now reads `h2.rs:6145/6089` (keeping `6089`, which was already correct). `doc/testing.md`'s own
`emit_pending_size_update_if_new_block` arm site drifted the same way, `h2.rs:5424` (now itself a
different-but-real `handle_rst_stream_frame` citation) corrected to `h2.rs:5476`
(`self.pending_table_size_update = Some(capped);`). This round independently re-enumerated every
citation whose value differs from `f76c8eb3` (91 across `LIFECYCLE.md` and `doc/testing.md` by this
round's own count — broader than a narrower "re-anchored only" count, since it also covers freshly
authored citations, not just re-anchored ones) and verified each by reading the cited source line(s)
against the sentence's own claim, not by re-deriving from the same shift formula that produced these
errors. All checked out except the ones named above, now fixed, and the one citation
(`LIFECYCLE.md:371`) this changeset's own text already discloses as pre-existing and intentionally
left. `check_doc_citations.py --base f76c8eb` exits 0.

Two more items from this round. First, a residual this changeset's B2 guard opens: with
`h2_graceful_shutdown_deadline_seconds` explicitly set to `0` (`None`, "indefinite wait explicitly
opted in" per `h2_drain.rs`'s own doc comment), `Mux::shutting_down_inner`'s forced-close branch
never fires, and a peer dying mid-CONTINUATION during a drain leaves `zero.storage` non-empty
forever — `ConnectionH2::has_pending_write` (`h2.rs:4400-4407`) never flips to `false`, and shutdown
waits indefinitely. Traced through source rather than assumed; documented in CHANGELOG.md as a real,
narrow (opt-out-of-the-default-deadline-only) hole the fix opens, not fixed in this changeset. Second,
`check_doc_citations.py`'s `doc_files()` never covers `CHANGELOG.md` (108 `file.rs:NNN` matches,
105 unique, by this script's own `CITATION` regex, none of them checked by anything) — recorded
in that function's own docstring.

Round 3 (final): two one-line corrections from a second independent pass. `LIFECYCLE.md:303`'s
"Transitions:" enumeration cited three of the four real `StreamState::Unlinked` assignment sites
(`h2.rs:6097/6194/6219`) and silently dropped the fourth: `6237` is `EndStreamAction::CloseDelimited`'s
sibling arm to `6219`'s `ForwardTerminated`, in the same `match end_stream_decision(stream)` — now
`h2.rs:6097/6194/6219/6237`. And this changeset's own prior claim of "102 citations, measured" in
`check_doc_citations.py`'s docstring was itself unverified: counted with the script's own `CITATION`
regex (`PATH = r"[A-Za-z0-9_][A-Za-z0-9_./-]*\.rs"`, `SPAN = r"[0-9]+(?:-[0-9]+)?"`) rather than an
ad hoc backtick-anchored grep, CHANGELOG.md carries 108 matches (105 unique `(path, spans)` pairs) —
the backtick requirement in the earlier grep silently excluded citations not wrapped in backticks.
Docstring corrected to state both numbers and the regex used to produce them.
`check_doc_citations.py --base f76c8eb` and `--self-test` both
exit 0.

Round 4 (final, PR #1440 CI fix): CI's `Doc citations` job gates on the pull request's base sha
(`github.event.pull_request.base.sha`), which for a branch stacked on another branch but opened
against `main` is `main`'s sha, not the parent branch's — for #1440 that is `595920e91c45`, not
`f76c8eb3`. Both prior rounds verified only against `f76c8eb3` (the direct parent), which was
insufficient: `mod.rs:1339` at `LIFECYCLE.md:681` and `:696` (both citing `counter`'s declaration in
`Mux::ready_inner`) were already correct relative to `f76c8eb3` — unchanged, unmoved, genuinely
accurate — but wrong relative to `595920e91c45`, because unrelated commits between that main sha and
`f76c8eb3` shifted `mod.rs` and coincidentally left `mod.rs:1339` holding different, also-plausible
content (`if self.frontend.readiness().event.is_hup()`) at the older base. Re-derived from the
construct each sentence names (`grep -n 'let mut counter = 0;' mod.rs` -> `1339`, inside
`fn ready_inner`, confirmed `1338` is that function's closing `) -> SessionResult {` and `1339` is
the declaration itself — both non-blank, so a tight range is valid) and re-anchored both citations
to `mod.rs:1338-1339`, breaking the collision with the stale base-era content the same way as the
earlier `6058`/`2706` collisions. `check_doc_citations.py --base 595920e` and `--base f76c8eb`
both exit 0. `cargo +nightly fmt --all -- --check` exits 0; nothing else re-run since only
`LIFECYCLE.md` changed.

Closes #1423

Signed-off-by: Florentin Dubois <[email protected]>

* test(e2e): replace the H2 CONTINUATION+drain sleeps with observable gates

test_h2_continuation_survives_a_graceful_drain_mid_reassembly sequenced
three events with two fixed thread::sleep(150ms) windows: sozu reading
stream 3's partial HEADERS, the soft_stop drain landing on that
connection, and the CONTINUATION completing the block. Neither window is
guaranteed under load. Measured on a 20-core box at load average 219, the
test failed 3 runs out of 3 with anchor_ok=true stream3_ok=false
drain_witnessed=true - the intended interleaving simply never happened,
so the run proved nothing and the assertions failed anyway.

No in-band probe can establish either ordering. RFC 9113 6.2/6.10 forbid
interleaving any frame into an open header block and
handle_continuation_header_state answers GOAWAY(PROTOCOL_ERROR) for a
non-CONTINUATION frame header, so a PING round-trip would destroy the
connection it was meant to measure. The drain is equally invisible:
graceful_goaway takes GracefulDrainDecision::DeferInitial while
reassembly is in progress, precisely so serializing a GOAWAY cannot
clobber the block, so in the interleaving under test no GOAWAY is emitted
until the CONTINUATION completes - gating on one would wait for a frame
that correct behaviour guarantees will not come, and would proceed only
in the runs where the premise had already been missed.

The control plane can see both. Both gates are bounded polls with a
5-second deadline, matching the anchor-reached-backend poll already in
this test:

  - h2.frames.rx.headers ticking once proves handle_frame dispatched the
    partial HEADERS to handle_headers_frame, which with END_HEADERS clear
    is what assigns H2State::ContinuationHeader. Counter and transition
    are one synchronous pass, so a later command round-trip observing the
    increment proves the state is live.
  - server.live dropping to 0 proves Server::run completed an iteration
    with shutting_down set. shut_down_sessions() runs immediately after
    that gauge write in the same iteration and is what reaches
    Mux::shutting_down -> ConnectionH2::graceful_goaway; command
    responses are produced earlier in the loop body, so a query returning
    0 was answered no earlier than the next iteration.
  - A second tick of the same counter proves the CONTINUATION was
    consumed, via the (H2State::ContinuationFrame(_), _) arm's re-entry
    into handle_frame(Frame::Headers(..)).

The anchor stream is now held rather than merely slow. Its 600ms delay
was an ordering requirement expressed as a duration, and the gates above
cost control-plane round-trips whose cost is set by machine load: with
the drain gate measured at 352ms on one attempt and 642ms on the next,
the anchor resolved first, the drain concluded the connection had nothing
left to wait for, and the CONTINUATION was never read - stream 1 served,
stream 3 dropped. DelayedH2Backend::start_held holds every response until
release(), called once the CONTINUATION is confirmed consumed, so the
ordering holds by construction at any load. start() is unchanged for its
two existing callers: the release flag starts set, so that loop never
runs.

query_proxy_metric returns None instead of panicking when the worker has
already exited, so a worker that dies mid-poll surfaces as the caller's
own timeout and diagnostic rather than a panic thrown from inside a query
helper.

Verified: 3 isolated runs green where the previous shape failed 3 of 3,
and 6 concurrent invocations under 60 CPU burners all green where the
previous shape failed 5 of 6 at comparable load.

Inverting the guarantee turns it red: corrupting the accumulated block in
graceful_goaway fails with "sozu never completed stream 3's header block"
and left: Fail / right: Success. Inverting only graceful_goaway's
reassembly_in_progress decision does NOT turn it red - after this
branch's extraction the block lives in HeaderBlockAccumulator rather than
zero.storage, so that decision no longer protects this shape on its own.
The previous test shape did not detect that inversion either; its colour
tracked machine load, not behaviour.

CHANGELOG folds into the existing entry rather than adding its own: the
test does not exist on main, git log -S naming it returns only 3be8c88,
so a separate Fixed entry would announce repairing a defect that never
shipped.

Signed-off-by: Florentin Dubois <[email protected]>

---------

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 23, 2026
…e protects

test_h2_continuation_survives_a_graceful_drain_mid_reassembly wrote stream 3's
CONTINUATION in a single TLS write, so the soft-stop drain always landed on a
frame BOUNDARY: reassembly in progress, but zero.storage empty and the
accumulated block already copied into ConnectionH2::header_reassembly, where no
write-side site names it. graceful_goaway's GracefulDrainDecision::DeferInitial
therefore protected nothing the test could observe - forcing its
reassembly_in_progress argument to false left the test green, measured 3/3 at
04fade6, so the production guarantee could have been deleted outright without
this test noticing (#1453).

The window that decision still guards is the one h2_header_reassembly.rs names:
one CONTINUATION frame mid-socket_read(), its already-read bytes parked in
zero.storage while expect_read still owes the rest, which send_initial_goaway's
zero.storage.clear() destroys on its way to serializing the GOAWAY. Split the
CONTINUATION across two TLS writes with the drain triggered between them - the
wire-level twin of the mid-frame interleave reassembly_property already
generates at the unit level. No production code changed.

The ordering holds by construction, not by timing; no sleep sequences the two
writes. The new gate is bytes_in, which ConnectionH2::handle_read advances on
every frontend socket read, PARTIAL ones included - precisely what
h2.frames.rx.headers cannot do, since handle_frame ticks it only on a frame
completed and it can therefore never witness a frame still arriving. read_space
caps each read at exactly the bytes the current frame stage expects, so the
first chunk costs exactly two reads (the 9-byte frame header, then the partial
payload) and the counter settles at exactly baseline + first_chunk.len().
Reaching that total is what proves the half-read frame is parked; an overshoot
fails the run loudly rather than being rounded away by the poll's <, since it
would mean something other than this test's own writes feeds the counter.

Discrimination re-measured, because this test's colour has been observed to
track machine load rather than behaviour and one red on a quiet box settles
nothing: inverting reassembly_in_progress to false now reds it 63 invocations
out of 63 with no green at all - 15/15 sequentially at 1-minute load 2.2-6.4,
and 48/48 under a 6-concurrent harness at load 4.5-31 - every one through the
same StringDecodingError(NotEnoughOctets) HPACK decoder desync #1397/#1401
already showed, and none through any other mechanism. The unmodified guarantee
is green 25/25 sequentially and 36/36 under 6-way concurrency. Under artificial
2x-CPU-oversubscription (peak 1-minute load 47.6) the changed test fails 4/48
and the UNCHANGED test measured the same way (peak 49.1) fails 11/48, both with
the identical anchor_ok=true stream3_ok=false drain_witnessed=true shape:
collect_response_frames's fixed 30x50ms collection window, a pre-existing
property this changeset deliberately does not widen - a deadline raised to make
a run land is the defect #1453 exists to remove.

doc/testing.md gains the convention this defect class distils: a test for a
guarantee that protects a mid-frame window has to reach that window, a
whole-frame write never does, and the only thing that settles it is inverting
the production decision and confirming the test turns red.

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 23, 2026
…e protects (#1481)

test_h2_continuation_survives_a_graceful_drain_mid_reassembly wrote stream 3's
CONTINUATION in a single TLS write, so the soft-stop drain always landed on a
frame BOUNDARY: reassembly in progress, but zero.storage empty and the
accumulated block already copied into ConnectionH2::header_reassembly, where no
write-side site names it. graceful_goaway's GracefulDrainDecision::DeferInitial
therefore protected nothing the test could observe - forcing its
reassembly_in_progress argument to false left the test green, measured 3/3 at
04fade6, so the production guarantee could have been deleted outright without
this test noticing (#1453).

The window that decision still guards is the one h2_header_reassembly.rs names:
one CONTINUATION frame mid-socket_read(), its already-read bytes parked in
zero.storage while expect_read still owes the rest, which send_initial_goaway's
zero.storage.clear() destroys on its way to serializing the GOAWAY. Split the
CONTINUATION across two TLS writes with the drain triggered between them - the
wire-level twin of the mid-frame interleave reassembly_property already
generates at the unit level. No production code changed.

The ordering holds by construction, not by timing; no sleep sequences the two
writes. The new gate is bytes_in, which ConnectionH2::handle_read advances on
every frontend socket read, PARTIAL ones included - precisely what
h2.frames.rx.headers cannot do, since handle_frame ticks it only on a frame
completed and it can therefore never witness a frame still arriving. read_space
caps each read at exactly the bytes the current frame stage expects, so the
first chunk costs exactly two reads (the 9-byte frame header, then the partial
payload) and the counter settles at exactly baseline + first_chunk.len().
Reaching that total is what proves the half-read frame is parked; an overshoot
fails the run loudly rather than being rounded away by the poll's <, since it
would mean something other than this test's own writes feeds the counter.

Discrimination re-measured, because this test's colour has been observed to
track machine load rather than behaviour and one red on a quiet box settles
nothing: inverting reassembly_in_progress to false now reds it 63 invocations
out of 63 with no green at all - 15/15 sequentially at 1-minute load 2.2-6.4,
and 48/48 under a 6-concurrent harness at load 4.5-31 - every one through the
same StringDecodingError(NotEnoughOctets) HPACK decoder desync #1397/#1401
already showed, and none through any other mechanism. The unmodified guarantee
is green 25/25 sequentially and 36/36 under 6-way concurrency. Under artificial
2x-CPU-oversubscription (peak 1-minute load 47.6) the changed test fails 4/48
and the UNCHANGED test measured the same way (peak 49.1) fails 11/48, both with
the identical anchor_ok=true stream3_ok=false drain_witnessed=true shape:
collect_response_frames's fixed 30x50ms collection window, a pre-existing
property this changeset deliberately does not widen - a deadline raised to make
a run land is the defect #1453 exists to remove.

doc/testing.md gains the convention this defect class distils: a test for a
guarantee that protects a mid-frame window has to reach that window, a
whole-frame write never does, and the only thing that settles it is inverting
the production decision and confirming the test turns red.

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 28, 2026
…is incomplete

A graceful drain deferred its initial GOAWAY(NO_ERROR, 2^31-1) while a
HEADERS/CONTINUATION block was being reassembled. The deferral was added
for #1401, when the GOAWAY was serialised into zero.storage, the buffer
that also held the block. Since #1625 control frames go to the separate
output queue and the block lives in ConnectionH2::header_reassembly, so
the deferral protected no buffer.

It still had an effect on the wire: when a soft-stop landed while a
connection's only stream was mid-block, that stream was still Idle,
Mux::shutting_down_inner did not wait for it, nothing was queued, and the
session closed with no GOAWAY at all, against RFC 9113 §6.8. RFC 9113
§4.3/§6.10 constrain the sender of a field block, not a GOAWAY travelling
the other way; hyperium/h2 (Connection::go_away_gracefully) and HAProxy
(h2_process) send it unconditionally too.

Remove the deferral: H2DrainState::initial_goaway_pending,
GracefulDrainDecision::DeferInitial, take_deferred_initial_goaway and its
test accessor, the reassembly_in_progress parameter of
begin_graceful_drain, the deferred-GOAWAY stage of
flush_pending_control_frames, the DeferInitial arm of graceful_goaway,
and header_block_reassembly_in_progress, which has no caller left.

test_h2_graceful_drain_mid_header_block_sends_goaway_before_closing
pins the wire behaviour: red before (0 bytes, no GOAWAY before the close),
green after. a_legitimate_continuation_survives_a_graceful_goaway now
reads the advisory GOAWAY on the peer socket before the CONTINUATION is
sent, then checks the block still decodes. The h2_drain unit tests that
asserted the flag are replaced by tests of the remaining decisions.

Docs: h2_drain.rs module doc, LIFECYCLE.md §2.2 and invariant 24,
doc/h2_mux_internals.md, the sozu#1453 paragraph of doc/testing.md, the
e2e test's doc comment and CHANGELOG. Line citations shifted by the
removal are re-pointed.

Closes #1637

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 28, 2026
…is incomplete

A graceful drain deferred its initial GOAWAY(NO_ERROR, 2^31-1) while a
HEADERS/CONTINUATION block was being reassembled. The deferral was added
for #1401, when the GOAWAY was serialised into zero.storage, the buffer
that also held the block. Since #1625 control frames go to the separate
output queue and the block lives in ConnectionH2::header_reassembly, so
the deferral protected no buffer.

It still had an effect on the wire: when a soft-stop landed while a
connection's only stream was mid-block, that stream was still Idle,
Mux::shutting_down_inner did not wait for it, nothing was queued, and the
session closed with no GOAWAY at all, against RFC 9113 §6.8. RFC 9113
§4.3/§6.10 constrain the sender of a field block, not a GOAWAY travelling
the other way; hyperium/h2 (Connection::go_away_gracefully) and HAProxy
(h2_process) send it unconditionally too.

Remove the deferral: H2DrainState::initial_goaway_pending,
GracefulDrainDecision::DeferInitial, take_deferred_initial_goaway and its
test accessor, the reassembly_in_progress parameter of
begin_graceful_drain, the deferred-GOAWAY stage of
flush_pending_control_frames, the DeferInitial arm of graceful_goaway,
and header_block_reassembly_in_progress, which has no caller left.

test_h2_graceful_drain_mid_header_block_sends_goaway_before_closing
pins the wire behaviour: red before (0 bytes, no GOAWAY before the close),
green after. a_legitimate_continuation_survives_a_graceful_goaway now
reads the advisory GOAWAY on the peer socket before the CONTINUATION is
sent, then checks the block still decodes. The h2_drain unit tests that
asserted the flag are replaced by tests of the remaining decisions.

Docs: h2_drain.rs module doc, LIFECYCLE.md §2.2 and invariant 24,
doc/h2_mux_internals.md, the sozu#1453 paragraph of doc/testing.md, the
e2e test's doc comment and CHANGELOG. Line citations shifted by the
removal are re-pointed.

Closes #1637

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 28, 2026
…is incomplete

A graceful drain deferred its initial GOAWAY(NO_ERROR, 2^31-1) while a
HEADERS/CONTINUATION block was being reassembled. The deferral was added
for #1401, when the GOAWAY was serialised into zero.storage, the buffer
that also held the block. Since #1625 control frames go to the separate
output queue and the block lives in ConnectionH2::header_reassembly, so
the deferral protected no buffer.

It still had an effect on the wire: when a soft-stop landed while a
connection's only stream was mid-block, that stream was still Idle,
Mux::shutting_down_inner did not wait for it, nothing was queued, and the
session closed with no GOAWAY at all, against RFC 9113 §6.8. RFC 9113
§4.3/§6.10 constrain the sender of a field block, not a GOAWAY travelling
the other way; hyperium/h2 (Connection::go_away_gracefully) and HAProxy
(h2_process) send it unconditionally too.

Remove the deferral: H2DrainState::initial_goaway_pending,
GracefulDrainDecision::DeferInitial, take_deferred_initial_goaway and its
test accessor, the reassembly_in_progress parameter of
begin_graceful_drain, the deferred-GOAWAY stage of
flush_pending_control_frames, the DeferInitial arm of graceful_goaway,
and header_block_reassembly_in_progress, which has no caller left.

test_h2_graceful_drain_mid_header_block_sends_goaway_before_closing
pins the wire behaviour: red before (0 bytes, no GOAWAY before the close),
green after. a_legitimate_continuation_survives_a_graceful_goaway now
reads the advisory GOAWAY on the peer socket before the CONTINUATION is
sent, then checks the block still decodes. The h2_drain unit tests that
asserted the flag are replaced by tests of the remaining decisions.

Docs: h2_drain.rs module doc, LIFECYCLE.md §2.2 and invariant 24,
doc/h2_mux_internals.md, the sozu#1453 paragraph of doc/testing.md, the
e2e test's doc comment and CHANGELOG. Prose citations the removal
shifted now name a symbol; pinned code-block annotations, which quote
their lines verbatim, are re-pointed.

Closes #1637

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 28, 2026
…is incomplete

A graceful drain deferred its initial GOAWAY(NO_ERROR, 2^31-1) while a
HEADERS/CONTINUATION block was being reassembled. The deferral was added
for #1401, when the GOAWAY was serialised into zero.storage, the buffer
that also held the block. Since #1625 control frames go to the separate
output queue and the block lives in ConnectionH2::header_reassembly, so
the deferral protected no buffer.

It still had an effect on the wire: when a soft-stop landed while a
connection's only stream was mid-block, that stream was still Idle,
Mux::shutting_down_inner did not wait for it, nothing was queued, and the
session closed with no GOAWAY at all, against RFC 9113 §6.8. RFC 9113
§4.3/§6.10 constrain the sender of a field block, not a GOAWAY travelling
the other way; hyperium/h2 (Connection::go_away_gracefully) and HAProxy
(h2_process) send it unconditionally too.

Remove the deferral: H2DrainState::initial_goaway_pending,
GracefulDrainDecision::DeferInitial, take_deferred_initial_goaway and its
test accessor, the reassembly_in_progress parameter of
begin_graceful_drain, the deferred-GOAWAY stage of
flush_pending_control_frames, the DeferInitial arm of graceful_goaway,
and header_block_reassembly_in_progress, which has no caller left.

test_h2_graceful_drain_mid_header_block_sends_goaway_before_closing
pins the wire behaviour: red before (0 bytes, no GOAWAY before the close),
green after. a_legitimate_continuation_survives_a_graceful_goaway now
reads the advisory GOAWAY on the peer socket before the CONTINUATION is
sent, then checks the block still decodes. The h2_drain unit tests that
asserted the flag are replaced by tests of the remaining decisions.

Docs: h2_drain.rs module doc, LIFECYCLE.md §2.2 and invariant 24,
doc/h2_mux_internals.md, the sozu#1453 paragraph of doc/testing.md, the
e2e test's doc comment and CHANGELOG. Prose citations the removal
shifted now name a symbol; pinned code-block annotations, which quote
their lines verbatim, are re-pointed.

Closes #1637

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 28, 2026
…is incomplete (#1649)

## Summary

A graceful drain deferred its advisory `GOAWAY(NO_ERROR, 2^31-1)` while a peer HEADERS/CONTINUATION block was being reassembled (`GracefulDrainDecision::DeferInitial`, added for #1401 when the GOAWAY was serialised into `zero.storage`, the buffer that also held the block). Since #1625 control frames go to the separate output queue and the block lives in `ConnectionH2::header_reassembly`, so the deferral protected no buffer. #1637 found that the e2e test built for it (sozu#1453) no longer notices the mutation `DeferInitial → SendInitial`.

Re-running that mutation against the wire showed the deferral still had one effect, and a harmful one: a soft-stop landing while a connection's only stream is mid-block closes the session with **no GOAWAY at all**. That stream is still `StreamState::Idle`, `Mux::shutting_down_inner` (`lib/src/protocol/mux/mod.rs`) does not wait for it, and with the GOAWAY deferred nothing is queued. This violates RFC 9113 §6.8: "Endpoints SHOULD always send a GOAWAY frame before closing a connection".

The deferral has no protocol basis:
- RFC 9113 §4.3 ("Field blocks MUST be transmitted as a contiguous sequence of frames") and §6.10 constrain the **sender** of a field block, here the client. A GOAWAY travelling the other way interleaves nothing.
- §6.8's "SHOULD send an initial GOAWAY frame with the last stream identifier set to 2^31-1" is not conditioned on the peer's state.
- hyperium/h2 0.4.19: `Connection::go_away_gracefully` (`src/proto/connection.rs`) sends it at once, never consulting `FramedRead::partial`.
- HAProxy `h2_process` (`src/mux_h2.c` @ `0ceb8c65f`) sends it on `PR_FL_STOPPED` without looking at the demux state.

This PR removes the deferral. Behaviour change: the advisory GOAWAY now leaves in the drain pass itself, possibly before the rest of a peer's header block, and a session no longer closes mid-block without one.

Closes #1637

## Removed

- `H2DrainState::initial_goaway_pending`, `GracefulDrainDecision::DeferInitial`, `H2DrainState::take_deferred_initial_goaway`, `H2DrainState::__test_initial_goaway_pending` (`lib/src/protocol/mux/h2_drain.rs`)
- the `reassembly_in_progress` parameter of `H2DrainState::begin_graceful_drain`
- the deferred-GOAWAY stage of `ConnectionH2::flush_pending_control_frames` and the `DeferInitial` arm of `ConnectionH2::graceful_goaway` (`lib/src/protocol/mux/h2.rs`)
- `ConnectionH2::header_block_reassembly_in_progress`, which has no caller left

## Red → green

New e2e test `test_h2_graceful_drain_mid_header_block_sends_goaway_before_closing` (`e2e/src/tests/h2_tests.rs`). It sends half a HEADERS block (no END_HEADERS) and waits on `h2.frames.rx.headers` (no timer) before calling `soft_stop()`. After `wait_for_server_stop()` it reads everything that reached the client and requires a `GOAWAY(NO_ERROR)`.

On `a3cb11ae` (before the change), `unshare -rn`, `--exact`:
```
H2 drain mid-block - received 0 frames
H2 drain mid-block - the session closed without a GOAWAY(NO_ERROR) (0 bytes received, stopped=true)
stability check FAILED: iteration 1 of 1 did not succeed (a single clean run is required)
test result: FAILED. 0 passed; 1 failed
```
The same shape measured with a scratch test before this change: 4/4 runs `bytes=0 goaway=false` on `main`, and 3/3 runs `GOAWAY error_code=0x0, bytes=17` with the `DeferInitial → SendInitial` mutation.

After this change: `test result: ok. 1 passed`.

## Tests modified

- `h2::tests::a_legitimate_continuation_survives_a_graceful_goaway` (`h2.rs`): it asserted the internal flag (`__test_initial_goaway_pending()` true, then false after `writable()`). It now reads the 17-byte `GOAWAY(NO_ERROR, STREAM_ID_MAX)` on the peer socket **before** sending the CONTINUATION, and keeps every decode assertion (block decodes byte-for-byte, peer dynamic table still resolves). It also asserts that `graceful_goaway` leaves `H2State::ContinuationHeader` untouched, and that completing the block queues no second GOAWAY. Seen red with the deferral reintroduced in `graceful_goaway`: `the peer must receive the advisory GOAWAY before it completes the block: WouldBlock`.
- `h2_drain::tests::initial_state`: dropped the flag assertion (the field no longer exists).
- `h2_drain::tests::begin_graceful_drain_sends_initial_when_no_reassembly` → `begin_graceful_drain_sends_the_initial_goaway_on_the_first_call`: same assertions minus the flag; the decision no longer takes a reassembly input.
- `h2_drain::tests::begin_graceful_drain_defers_initial_during_reassembly`: removed. It asserted the removed decision; the wire behaviour it stood for is now asserted by the two tests above.
- `h2_drain::tests::take_deferred_initial_goaway_only_fires_when_ready`: removed together with the method it tested.
- `h2_drain::tests::enter_final_goaway_supersedes_a_deferred_initial_goaway` → `enter_final_goaway_after_a_graceful_drain_keeps_the_budget_armed`: there is no deferred GOAWAY left to supersede. It now pins that the final GOAWAY neither arms nor moves the forced-close budget, which `enter_final_goaway` also asserts as a new `debug_assert_eq!`.
- `h2_drain::tests::enter_final_goaway_marks_draining_even_without_a_prior_graceful_drain`: added the `started_at == None` assertion.
- `h2_drain::tests::begin_graceful_drain_is_idempotent_and_does_not_rearm_the_budget`, `deadline_elapsed_respects_configured_budget`, `deadline_elapsed_never_fires_when_deadline_is_none`: call sites only (one argument fewer).
- `reassembly_property` (`h2.rs`): interleave variant `GracefulGoawayDefer` renamed `GracefulGoaway`, because it no longer defers. Behaviour unchanged, property green.
- `test_h2_continuation_survives_a_graceful_drain_mid_reassembly` (e2e): doc comment and inline comments only. They described the GOAWAY as deliberately deferred. The corruption and `drain_witnessed` assertions are unchanged.

## Docs

- `h2_drain.rs` module doc: the dual-role-hazard section is replaced by the history and the reason for removal.
- LIFECYCLE.md §2.2 and invariant 24.
- `doc/h2_mux_internals.md`: the `flush_pending_control_frames` stage list, and the field list of `H2DrainState`.
- `doc/testing.md`: the sozu#1453 paragraph is now also the example of a guard made inert by a refactor and revealed by re-running its mutation.
- `h2_header_reassembly.rs` module doc.
- CHANGELOG (Fixed).

Removing ~80 lines from `h2.rs` shifted 31 `file:NNN` citations in `doc/` and `LIFECYCLE.md`. They are re-pointed through a diff-based line mapping, and one that had already drifted on `main` (`h2.rs:5294`) now cites a symbol.

A distinct defect found here, out of scope: #1647. A stream still in reassembly does not hold the drain open, so its request is lost and no final GOAWAY with the real `last_stream_id` is sent.

## Commands run (after rebase on `96b4bca9`)

- `cargo +nightly fmt --all -- --check` → 0
- `cargo build --locked` → 0; `cargo build --all-features --locked` → 0
- `cargo clippy --all-targets --locked -- -D warnings` → 0
- `cargo clippy --all-targets --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -- -D warnings` → 0
- `cargo test --workspace --locked -- --skip tests::fuzz_tests:: --test-threads=8` → 2198 passed, 0 failed, 14 ignored
- `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked` → 0
- `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` → 0
- `check_doc_citations.py`: `--self-test` 0, broken fixture 1 (expected), `--base origin/main` 0, plain 0
- Stability, 10 sequential runs each, `unshare -rn` with `lo` up, one e2e process, `--exact`:
  - `test_h2_graceful_drain_mid_header_block_sends_goaway_before_closing` 10/10
  - `test_h2_continuation_survives_a_graceful_drain_mid_reassembly` 10/10
- `git merge-tree --write-tree origin/main HEAD` clean

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.

mux-h2: graceful_goaway clears zero.storage unconditionally, corrupting an in-flight header-block reassembly on every graceful shutdown

1 participant