Skip to content

refactor(mux-h2): split zero.storage's dual role so a control-frame flush cannot clobber header reassembly - #1440

Merged
FlorentinDUBOIS merged 2 commits into
mainfrom
refactor/h2-header-reassembly
Sep 22, 2026
Merged

FlorentinDUBOIS merged 2 commits into
mainfrom
refactor/h2-header-reassembly

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

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,
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 fix(mux-h2): decode a refused stream's HPACK field block instead of dropping it #1396/fix(mux-h2): defer control-frame flush during header-block reassembly #1397 shape).
  • Closes mux-h2: flush_pending_control_frames' hung-up-while-draining stage clears zero.storage without the reassembly guard its three sibling stages carry #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. mux-h2: flush_pending_control_frames' hung-up-while-draining stage clears zero.storage without the reassembly guard its three sibling stages carry #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 f76c8eb3 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 f76c8eb3753b70291f47d0395430b3c9c36a26dd 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 f76c8eb3753b70291f47d0395430b3c9c36a26dd and --self-test both
exit 0.

Closes #1423

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
FlorentinDUBOIS force-pushed the refactor/h2-header-reassembly branch from 130306e to 3be8c88 Compare September 22, 2026 11:59
…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]>
…ates

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]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the refactor/h2-header-reassembly branch from 5f3da7d to c464e0d Compare September 22, 2026 20:47
@FlorentinDUBOIS
FlorentinDUBOIS merged commit fbe6912 into main Sep 22, 2026
24 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the refactor/h2-header-reassembly branch September 22, 2026 22:43
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: flush_pending_control_frames' hung-up-while-draining stage clears zero.storage without the reassembly guard its three sibling stages carry

1 participant