Skip to content

fix(mux-h2): decode a refused stream's HPACK field block instead of dropping it - #1396

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
fix/h2-refused-stream-hpack-desync
Sep 21, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
fix/h2-refused-stream-hpack-desync

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Found while instructing #1336 (Q1/Q14, buffers and HPACK state). It is standalone and shippable
independently of whatever the sans-io decision turns out to be.

The defect

HPACK field-compression state is scoped to the connection, not to the stream (RFC 9113 §4.3).

H2State::Discard has exactly one entry point, refuse_stream_and_discard, reached when a peer
opens a stream we will not serve: during a graceful drain, over MAX_CONCURRENT_STREAMS, on buffer
pool exhaustion, or on a CONTINUATION refusal after flood detection. Its arm in
ConnectionH2::readable threw the buffered payload away:

let _i = kawa.storage.data();
trace!("{} DISCARDING: {:?}", log_context!(self), _i);
kawa.storage.clear();

Those bytes are a field block the peer's encoder has already applied to its own dynamic table.
Dropping them undecoded leaves our decoder permanently behind the peer's encoder, and every later
header block on the surviving connection resolves the wrong dynamic entry or fails outright. The
connection is deliberately kept alive by every one of those refusal paths, so the desync persists.

Any peer that can trigger a refusal can trigger it.

The fix

The Discard arm now decodes the refused field block into self.decoder (callback no-op, result
discarded) before clearing storage. Three things make that correct rather than merely plausible:

A HEADERS payload is not a field block. RFC 9113 §6.2 puts an optional Pad Length byte and an
optional 5-byte PRIORITY prefix ahead of the fragment, and the three new-stream call sites pass the
whole payload_len. Feeding that raw to the decoder turns every refused PADDED or PRIORITY HEADERS
from a legitimate peer into a spurious COMPRESSION_ERROR GOAWAY. DiscardedFieldBlock::New { flags }
re-parses through parser::headers_frame to strip them first.

Without END_HEADERS the decode is skipped, not errored. A refused multi-frame block cannot
legally continue: after the discard, handle_header_state already treats the following standalone
CONTINUATION as PROTOCOL_ERROR. Decoding a fragment that ends mid-integer would only swap one
connection error for another.

The CONTINUATION refusal site needed its own handling. refuse_stream_and_discard's enqueue_rst
arms WRITABLE, and the inner event loop dispatches readable() then writable() in the same sweep
(mod.rs:1387 vs :1714), so flush_pending_control_frames — which reuses zero.storage as
RST_STREAM scratch — is guaranteed to clobber that buffer before the next readable(). A byte offset
into zero.storage would therefore be unsafe. The accumulated earlier fragments are copied to an
owned Vec<u8> synchronously at refusal time, then concatenated with the final frame's payload and
decoded once.

On a genuine decode failure of a complete block: GOAWAY(COMPRESSION_ERROR) per RFC 9113 §4.3.
A malformed Pad Length on a new-stream refusal is PROTOCOL_ERROR per §6.1 — distinct paths.

Red-then-green

Two tests, both driven through the real mux state machine over a loopback socket.

a_refused_stream_keeps_the_hpack_decoder_in_sync — the peer encodes a request whose last field
lands in its dynamic table, we refuse the stream, then the peer sends a one-byte indexed reference
to that entry. Unfixed:

the connection decoder must still resolve the peer's dynamic table after a refused stream,
got Err(HeaderIndexOutOfBounds)

a_refused_padded_prioritized_stream_keeps_the_hpack_decoder_in_sync — the same, with PADDED and
PRIORITY set. Against a naive fix that decodes the raw payload:

refusing a PADDED|PRIORITY HEADERS frame must leave the connection usable: GoAway
(cause: discarded stream's HPACK field block failed to decode: CompressionError)

Both green after the fix. 919 passed; 0 failed on sozu-lib --lib.

Dependencies and docs

No Cargo.toml change — loona-hpack was already a normal sozu-lib dependency. Production
dependencies do not grow.

Inserting code mid-file shifts every citation below it, so LIFECYCLE.md has its Discard section
rewritten and 43 h2.rs:NNN citations re-anchored, plus one drifted citation in doc/testing.md.
.github/scripts/check_doc_citations.py --base origin/main reports 0 unresolved and 0 drifted.

Flagged, not fixed

zero.storage is reused as write scratch by flush_pending_control_frames for any queued
RST_STREAM or WINDOW_UPDATE, so a legitimate multi-frame HEADERS+CONTINUATION reassembly could in
principle be corrupted by an unrelated stream's pending control frame. That is pre-existing,
independent of Discard, and untouched here — it wants its own investigation.

…ropping it

H2State::Discard's only entry point, refuse_stream_and_discard, is reached
when a stream is refused during graceful drain, over
MAX_CONCURRENT_STREAMS, on buffer-pool exhaustion, or when a CONTINUATION
flood refusal fires mid-block (CVE-2024-27316 mitigation). Its readable()
arm dropped the frame's payload unconditionally via kawa.storage.clear().

RFC 9113 §4.3 scopes HPACK field-compression state to the whole
connection, not to a stream: the dropped bytes are a field block the
peer's encoder has already applied to its own dynamic table. Dropping it
undecoded left the connection decoder permanently behind the peer's
encoder, so every later header block on the surviving connection then
resolved the wrong dynamic entry or failed outright with
HeaderIndexOutOfBounds.

The Discard arm now decodes the field block into ConnectionH2::decoder
(the header pairs are discarded — the stream was already refused) before
clearing zero.storage, via the new decode_discarded_field_block free
function and the DiscardedFieldBlock value refuse_stream_and_discard
stashes for it:

- A HEADERS payload is not itself a field block (RFC 9113 §6.2):
  [Pad Length?][Stream Dependency+Weight?][field block][padding?]. A
  new-stream refusal re-parses the whole payload with
  parser::headers_frame to strip any PADDED/PRIORITY prefix before
  decoding, matching how an accepted HEADERS frame is parsed. A naive
  decode of the raw payload turns a legitimate padded or prioritized
  refusal into a spurious GOAWAY(COMPRESSION_ERROR) — covered by a second
  regression test, since the first (recovered) test's unpadded,
  unprioritized probe cannot exercise this path.
- When the refused frame did not carry END_HEADERS, decoding is skipped
  rather than attempted: a refused multi-frame block cannot legally
  continue (handle_header_state already treats a standalone CONTINUATION
  as a connection error of type PROTOCOL_ERROR), so there is nothing
  complete to decode, and decoding a fragment that ends mid-integer would
  only misreport COMPRESSION_ERROR in place of that PROTOCOL_ERROR.
- A CONTINUATION frame refused mid-block copies out every prior frame's
  accumulated field-block bytes eagerly, at refusal time: queuing the
  RST_STREAM arms WRITABLE, and the same event-loop pass's writable()
  preamble (flush_pending_control_frames) reuses zero.storage as
  RST_STREAM/WINDOW_UPDATE scratch before the next readable() pass would
  otherwise read this frame's own payload, which would otherwise silently
  corrupt the reassembly this decode depends on.
- A genuine HPACK decode failure of a complete block is reported as
  GOAWAY(COMPRESSION_ERROR) per RFC 9113 §4.3, distinct from the
  PROTOCOL_ERROR a malformed Pad Length now correctly produces.

Both regression tests were run against the unfixed tree and confirmed red
(HeaderIndexOutOfBounds for the first, GOAWAY(CompressionError) for the
PADDED|PRIORITY variant) before the fix was applied; both pass against the
fixed tree. loona-hpack was already a normal (non-dev, non-optional)
sozu-lib dependency, so no dependency was added.

Updates LIFECYCLE.md's Discard section and CHANGELOG.md in the same
changeset, and repairs every h2.rs:NNN citation the new code shifted
(doc/testing.md, LIFECYCLE.md), verified with
.github/scripts/check_doc_citations.py --base origin/main.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 42ac35b into main Sep 21, 2026
24 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/h2-refused-stream-hpack-desync branch September 21, 2026 09:21
pull Bot pushed a commit to jrcribb/sozu that referenced this pull request Sep 21, 2026
…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 (sozu-proxy#1396, sozu-proxy#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 sozu-proxy#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 sozu-proxy#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 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant