Repository navigation
fix(mux-h2): defer control-frame flush during header-block reassembly - #1397
Merged
Merged
Conversation
ConnectionH2::zero is both the read-side accumulation buffer for an in-progress, non-refused HEADERS+CONTINUATION field block and the write scratch space flush_pending_control_frames reuses for any queued WINDOW_UPDATE or RST_STREAM, on any stream. Because the event loop dispatches frontend readable() then writable() in the same sweep, ordinary connection-level flow-control housekeeping could run between a HEADERS frame and its CONTINUATION and clear zero.storage out from under the accumulating fragment - no adversarial peer required. The clobbered bytes still HPACK-decoded, producing wrong header names and values instead of an obvious failure. Gate the WINDOW_UPDATE-drain and RST_STREAM-drain stages of flush_pending_control_frames on the new header_block_reassembly_in_progress() (true while self.state is ContinuationHeader or ContinuationFrame) so they defer instead of flushing. Nothing is lost: queuing either frame kind already arms WRITABLE, so the next writable() call after the block completes drains it normally. This mirrors the write side's own existing protection of the same buffer, where a stalled zero-buffer write disables READABLE so a fresh frame read cannot clobber it. Red-then-green: a_legitimate_continuation_survives_an_unrelated_window_update_flush drives a real HEADERS(no END_HEADERS)+CONTINUATION(END_HEADERS) sequence over a loopback socket, queues an unrelated connection-level WINDOW_UPDATE between the two frames, and asserts the field block still decodes byte-for-byte. Before the fix it fails with the decoded header name/value pair corrupted to unrelated bytes; after the fix it passes. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 21, 2026 09:46
This was referenced Sep 21, 2026
pull Bot
pushed a commit
to jrcribb/sozu
that referenced
this pull request
Sep 21, 2026
check_doc_citations.py --base b51d9f9 (PR sozu-proxy#1372's merge base, a Dependabot actions bump that touches no doc file) reported 9 of 56 compared citations drifted. Sweeping every remaining `file.rs:NNN` citation in both files against origin/main at 610eaa0 found roughly 60 more that the base comparison structurally cannot see, because the checker only compares a citation whose (path, line) pair is unchanged since the base -- and a prior PR (sozu-proxy#1397, merged after this fix started) mechanically renumbered many h2.rs citations to track a 200+-line insertion without checking whether they pointed at the right place first. A renumbered-but-still-wrong citation drops out of every future --base comparison forever. STALE LINE NUMBERS (the large majority): each of these named a real construct correctly but the number had drifted, usually because later commits shifted the target file. Renumbered to the current line. Symbol form was not substituted because in every case the prose already names the symbol separately (e.g. "MAX_LOOP_ITERATIONS (mod.rs)") and the line number pins a *specific statement* among several uses of that same symbol (e.g. two separate MAX_LOOP_ITERATIONS comparisons, four separate self.context.now writes, many remove_dead_stream call sites) -- exactly the case doc/README.md's citation-form rule reserves for line citations, since no symbol names "this one occurrence" more precisely than a line does. Representative fixes: the MAX_LOOP_ITERATIONS backstop check (mod.rs:1216 -> 1762), the `counter` declaration above both ready_inner loops (mod.rs:793 -> 1335), the once-per-outer-pass and top-of-Mux::timeout clock samples (mod.rs:841 -> 1383, mod.rs:1430 -> 1965), the top-of-shutting_down sample (mod.rs:1929 -> 2338), frontend-HUP detection and the two MuxResult::CloseSession sites (mod.rs:795/860/1183 -> 1337/1402/1729), every StreamState::Link/Unlinked/Recycle transition site in h1.rs/h2.rs/answers.rs, the backend attach/detach citations (Router::connect, Context::link_stream, Context::unlink_stream), the Recycle-slot pool-clear/metrics-reset/search citations in Context::create_stream, the ConnectionH2.now mirror-assignment sites in readable/writable/cancel_timed_out_streams/start_stream, the outbound-byte and fc-stall-arm liveness refreshes in write_streams, the SETTINGS-ACK-timeout checks in readable and flush_pending_control_frames, the graceful-GOAWAY call chain (Mux::shutting_down -> graceful_goaway -> goaway), the backend-timeout action arm in Mux::timeout, and the flood-window / back-pressure-window fail-closed citations. udp/LIFECYCLE.md needed exactly the one CI-reported fix: armed_deadline's clear-before-reschedule statement (manager.rs:534 -> 535); the file was otherwise untouched by any PR since the merge base and every other citation in it still resolves correctly. A GENUINE PROSE ERROR, not a stale line number: section 4.1 and section 5.4 of mux/LIFECYCLE.md asserted that `handle_continuation_header_state`, `cancel_timed_out_streams`, `handle_rst_stream_frame`, `handle_goaway_frame` and `end_stream` perform `self.streams.remove(...)` inline instead of routing through the canonical `ConnectionH2::remove_dead_stream` helper, and told reviewers to apply its two invalidation checks (`expect_write`, `expect_read`) by hand at each one. That claim is now false: `self.streams.remove(` occurs exactly once in the whole of h2.rs, inside `remove_dead_stream` itself, and all five sites this section named as unsafe now call the helper -- several with a comment explicitly citing this LIFECYCLE.md section by name as the reason. Renumbering any of the five citations would have re-anchored them onto correct-looking but misleading targets, since the code they used to point at no longer exists as a distinct inline removal. Rewrote both sections instead: the "inline" call-site list is gone (there is nothing left to list), the five sites moved into the "goes through remove_dead_stream" list with fresh citations, and the prose now states plainly that the helper is the only removal path and performs both invalidation checks internally. The `close` backend-stream-teardown exception (which never removed at all) is kept and renumbered, since that half of the claim is still true. One citation the sweep missed, found by a separate check: section 8's frontend timeout handling cited `mod.rs:1473` for "`Mux::timeout` inspects each stream's state". That line is a `push_event(EventKind::BackendUp)` inside `ready_inner`, unrelated to timeouts. The state inspection the sentence describes is the `match self.context.streams[stream_id].state` at mod.rs:2018, whose arms are exactly the 408/503/504, forcefully-terminate and keep-draining outcomes the prose lists. Corrected to mod.rs:2018. It escaped both the --base comparison and the symbol sweep because the doc line names `Mux::timeout` while the citation must point inside `timeout_inner`, so a naive "is the cited line inside the named function" test cannot distinguish a correct delegation citation from a wrong one. Verified locally against origin/main at 610eaa0 (this task's second base; PR sozu-proxy#1397 landed mid-task and required a full rebase and re-verification of every previously-computed line number): python3 .github/scripts/check_doc_citations.py --self-test # exit 0 python3 .github/scripts/check_doc_citations.py # exit 0 python3 .github/scripts/check_doc_citations.py --base b51d9f9 # red before this commit (matching the 9 CI-reported citations, minus the # 2 that PR sozu-proxy#1397's mechanical renumbering had already dropped out of # comparison -- 7/54 reported at 610eaa0), green after (0/47 drifted) Signed-off-by: Florentin Dubois <[email protected]>
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]>
This was referenced Sep 21, 2026
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 22, 2026
H2DrainState (draining, peer_last_stream_id, started_at, graceful_shutdown_deadline, initial_goaway_pending) was already socket-free. What was not is the six ConnectionH2 functions that read and wrote it: graceful_goaway, goaway, send_initial_goaway, handle_goaway_frame, peer_gone_after_final_goaway, and the GOAWAY stage of flush_pending_control_frames. Move the decision - draining or not, defer-or-send, budget-elapsed - into h2_drain.rs behind the same closed-API shape hpack_state.rs, h2_flow_control.rs, h2_stream_table.rs and h2_flood_detector.rs established in the four prior extraction steps: - H2DrainState::begin_graceful_drain replaces graceful_goaway's state-mutating half, returning a GracefulDrainDecision (AlreadyDraining / DeferInitial / SendInitial). - H2DrainState::take_deferred_initial_goaway replaces the check-and-clear at the top of flush_pending_control_frames' GOAWAY stage. - H2DrainState::enter_final_goaway replaces the two-field mutation in goaway(); H2DrainState::observe_peer_goaway replaces it in handle_goaway_frame, which now reads back its own recorded peer_last_stream_id() for the retry-loop comparison. - H2DrainState::deadline_elapsed replaces graceful_shutdown_deadline_elapsed's body, taking now: Instant as an explicit parameter instead of reading a clock. Every decision method that needs the header-block-reassembly guard takes it as a caller-computed bool rather than reaching for self.zero/self.state itself - h2_drain.rs has neither - which keeps the module structurally unable to reintroduce the zero.storage dual-role clobber (#1396, #1397, #1401) that LIFECYCLE.md's new invariant 24 documents. peer_gone_after_final_goaway and force_disconnect stay on ConnectionH2 untouched. Pure relocation, no behaviour change: proved by the compiler and the existing suite, including the #1397/#1401 regression tests passing unmodified. Reported but not fixed here: flush_pending_control_frames' frontend_hung_up_while_draining() stage clears zero.storage without checking header_block_reassembly_in_progress(), unlike every stage below it in the same function - a live gap of the same bug class. Also fixes 73 LIFECYCLE.md/doc/testing.md line citations that drifted from this changeset's line-number shifts in h2.rs (mechanically relocated via exact-text diff mapping against the branch base, each spot-verified), and the one pre-existing rule-1 failure that drift caused. Also fixes LIFECYCLE.md prose that quoted pre-refactor private-field access syntax on this and the three prior extractions' closed-API types (self.drain.draining, self.drain.started_at, self.streams, self.rst_sent, and a struct snippet showing expect_read/expect_write as pub when they are private) - code that no longer compiles now that those fields are private. The narrative paragraph in section 2.2 is rewritten to describe the actual API (begin_graceful_drain, enter_final_goaway, take_deferred_initial_goaway) instead of raw field assignment. The citation gate does not catch this class of drift: a line citation can resolve to a real, unchanged, on-topic line while the code fragment quoted in the surrounding prose no longer compiles. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 22, 2026
…ol-frame scratch ConnectionH2::zero served two incompatible roles: the read-side accumulator a HEADERS/CONTINUATION field block was reassembled into across however many readable() passes a block took (headers.header_block_fragment, a window over zero.storage), and the write-side scratch buffer every control-frame flush (WINDOW_UPDATE, RST_STREAM, GOAWAY) clears and reuses. Three bugs (#1396, #1397, #1401) shipped from the two roles sharing one buffer, each patched with its own header_block_reassembly_in_progress() guard, and a fourth site (#1423) was found unguarded while landing the third. Add h2_header_reassembly.rs: HeaderBlockAccumulator owns its bytes (Vec<u8>, no new dependency) instead of borrowing a window into zero.storage. The initiating HEADERS frame's fragment is copied out and zero.storage cleared in the same step that enters ContinuationHeader; each CONTINUATION frame's payload is folded in and zero.storage cleared again in the same step that leaves ContinuationFrame; the block is retired (decoded, or handed unread to the CVE-2024-27316 refusal path) through the single exit point matching the single entry point. The old zero.storage.end -= 9 trick that kept a CONTINUATION frame's incoming header from disturbing the accumulated fragment's physical position is gone; every zero-stream frame now frees zero.storage the same way every other frame type already did. No write-side code holds a field named header_reassembly, so a control-frame flush cannot reach the accumulated bytes of a reassembly in progress on its own: that write-side half of the collision is unrepresentable by construction, in every build profile. It is not the whole story. Review of the first version of this change found two hazards the type does not close by itself: - A same-module, read-side misuse can still leak the accumulator across streams: handle_headers_frame's RFC 9113 5.3.1 self-dependency early return retired the stream without retiring the accumulator, so the next HEADERS frame on an unrelated stream decoded against the previous stream's stale bytes. Fixed by retiring the accumulator on that return before the reset_stream/remove_dead_stream/return, and adding a debug_assert on the fast path confirming it never observes in-progress state there. debug_assert compiles out in release, so the type does not make this class of bug impossible by itself - it is caught here only because a human reviewed the code path. "Unrepresentable by construction" is therefore true for the write side only; the module doc, LIFECYCLE.md and CHANGELOG.md now say exactly that instead of overclaiming it for the whole type, and no longer claim a release build panics loudly on misuse (debug_assert compiles out there; a release build silently starts a fresh block instead, the #1396/#1397 shape). - Closes #1423 was justified on a false premise: that Ready::HUP means "the peer will send no more bytes," so the frontend-hung-up-while-draining stage could discard zero.storage unconditionally without ever touching a reassembly in progress. mio's is_read_closed() (which Ready::HUP is defined from) is true on a TCP half-close with data still queued in the kernel receive buffer, not only on a fully drained close, so a CONTINUATION frame split across TCP segments can still have its second segment readable after HUP fires. The stage now carries the same header_block_reassembly_in_progress() guard its five sibling call sites already had (the WINDOW_UPDATE-drain and RST_STREAM-drain stages in the same function, the deferred-initial-GOAWAY stage beside them, graceful_goaway's drain-defer decision, and flush_zero_buffer), restoring the guard the first version of this change removed. #1423 is closed by this changeset, but not by the mechanism the first version claimed. The property test (reassembly_property) is extended: it now actually composes a graceful_goaway deferral into the same interleave set as the WINDOW_UPDATE/RST_STREAM/HUP-while-draining triggers - the first version claimed this in four places without doing it, and generated a dead zeroth interleave that was never read - and generates each interleave point at either a frame boundary or mid-frame, splitting a CONTINUATION fragment's own bytes across two simulated TCP segments so the accumulator actually holds unretired bytes when the interleave fires; generating whole-frame writes only, as the first version did, always found zero.storage empty at interleave time and could not reach the B2 shape at all. Composing the deferral surfaced its own bug during development: the HUP-while-draining interleave's test-only drain-flag setter also flips draining() to true, so a plan combining both would silently take the already-draining branch of graceful_goaway instead of deferring - fixed by checking connection.drain.draining() directly instead of a separately tracked "did we already send GOAWAY" flag. Tests: a_legitimate_continuation_survives_a_hup_while_draining still pins the frame-boundary shape of #1423; a new a_continuation_frame_split_by_tcp_segmentation_survives_a_hup_while_draining pins the mid-frame shape B2 found, red on the unguarded stage (reproducing the predicted StringDecodingError(NotEnoughOctets) desync) and green with the guard restored; a new a_priority_self_dependency_reset_does_not_leak_the_reassembly_accumulator pins the accumulator leak, red on the un-retired early return and green after; the three existing pinning tests for #1396/#1397/#1401 still pass; the extended quickcheck property passes at both its default iteration count and at QUICKCHECK_TESTS=2000; the e2e test (try_h2_continuation_survives_a_graceful_drain_mid_reassembly) now asserts a GOAWAY witness so it cannot pass on a run where the race it targets never fired. LIFECYCLE.md invariant 24, doc/h2_mux_internals.md, doc/testing.md and CHANGELOG.md updated for both the original design and these findings, and softened where the first version overclaimed. Citation drift re-anchored throughout LIFECYCLE.md, including drift this changeset's own edits introduced after an earlier re-anchoring pass missed a later hunk; a small number of pre-existing wrong citations unrelated to this change (three in LIFECYCLE.md, one in doc/testing.md, and a handful in CHANGELOG.md's timer-accuracy entry that predate this branch and are outside the citation checker's doc/ + LIFECYCLE.md scope) are left as found. CHANGELOG.md also now documents the copy-cost trade-off of the multi-frame path (one memcpy per CONTINUATION frame, offset by the CVE-2024-27316 refusal path's old eager copy going away) and a behaviour change: payload_len > available_space() no longer implicitly caps a block's total size at the zero buffer's capacity now that zero.storage is cleared every frame instead of held for the whole block - only max_header_list_size (default 65536) still does. Round 2 (independent re-review of `bf407254`): CI runs `check_doc_citations.py --base "${{ github.event.pull_request.base.sha }}"` (`.github/workflows/ci.yml`), which for this branch is `f76c8eb3` — a check this changeset had never actually run. Against that exact base it exited 1 on a citation this changeset re-anchored to `h2.rs:6058` (the "close" backend-stream teardown line): a DIFFERENT LIFECYCLE.md citation happened to read that same number at `f76c8eb3`, and the checker's own drift rule keys identity on the (path, number) pair, not on which paragraph carries it. Re-anchored to the range `h2.rs:6057-6059`, which cannot collide, per the checker's own advice ("or better, cite a symbol"): `check_doc_citations.py --base f76c8eb` now exits 0. The round-1 report of "15 citations found and fixed, all verified" undercounted: it missed the `end_stream` Client/Server range pair (`LIFECYCLE.md:1030`/`:1033`, off by the same +17 as the rest but never actually corrected despite being investigated), and left two disclosed-as-pre-existing citations (`LIFECYCLE.md:303`, `:323`) that were in fact fixable now that their exact-source targets were re-derived directly (`grep -n` for the construct each sentence names, not an offset formula) — `:303`'s three-site illustration list now reads `h2.rs:6097/6194/6219` (`reset_stream`'s reset, `end_stream`'s Client-arm and Server-arm `ForwardTerminated` retirements — all independently grep-verified `StreamState::Unlinked` assignment sites), and `:323`'s `unlink_stream` call-site pair now reads `h2.rs:6145/6089` (keeping `6089`, which was already correct). `doc/testing.md`'s own `emit_pending_size_update_if_new_block` arm site drifted the same way, `h2.rs:5424` (now itself a different-but-real `handle_rst_stream_frame` citation) corrected to `h2.rs:5476` (`self.pending_table_size_update = Some(capped);`). This round independently re-enumerated every citation whose value differs from `f76c8eb3` (91 across `LIFECYCLE.md` and `doc/testing.md` by this round's own count — broader than a narrower "re-anchored only" count, since it also covers freshly authored citations, not just re-anchored ones) and verified each by reading the cited source line(s) against the sentence's own claim, not by re-deriving from the same shift formula that produced these errors. All checked out except the ones named above, now fixed, and the one citation (`LIFECYCLE.md:371`) this changeset's own text already discloses as pre-existing and intentionally left. `check_doc_citations.py --base f76c8eb` exits 0. Two more items from this round. First, a residual this changeset's B2 guard opens: with `h2_graceful_shutdown_deadline_seconds` explicitly set to `0` (`None`, "indefinite wait explicitly opted in" per `h2_drain.rs`'s own doc comment), `Mux::shutting_down_inner`'s forced-close branch never fires, and a peer dying mid-CONTINUATION during a drain leaves `zero.storage` non-empty forever — `ConnectionH2::has_pending_write` (`h2.rs:4400-4407`) never flips to `false`, and shutdown waits indefinitely. Traced through source rather than assumed; documented in CHANGELOG.md as a real, narrow (opt-out-of-the-default-deadline-only) hole the fix opens, not fixed in this changeset. Second, `check_doc_citations.py`'s `doc_files()` never covers `CHANGELOG.md` (108 `file.rs:NNN` matches, 105 unique, by this script's own `CITATION` regex, none of them checked by anything) — recorded in that function's own docstring. Round 3 (final): two one-line corrections from a second independent pass. `LIFECYCLE.md:303`'s "Transitions:" enumeration cited three of the four real `StreamState::Unlinked` assignment sites (`h2.rs:6097/6194/6219`) and silently dropped the fourth: `6237` is `EndStreamAction::CloseDelimited`'s sibling arm to `6219`'s `ForwardTerminated`, in the same `match end_stream_decision(stream)` — now `h2.rs:6097/6194/6219/6237`. And this changeset's own prior claim of "102 citations, measured" in `check_doc_citations.py`'s docstring was itself unverified: counted with the script's own `CITATION` regex (`PATH = r"[A-Za-z0-9_][A-Za-z0-9_./-]*\.rs"`, `SPAN = r"[0-9]+(?:-[0-9]+)?"`) rather than an ad hoc backtick-anchored grep, CHANGELOG.md carries 108 matches (105 unique `(path, spans)` pairs) — the backtick requirement in the earlier grep silently excluded citations not wrapped in backticks. Docstring corrected to state both numbers and the regex used to produce them. `check_doc_citations.py --base f76c8eb` and `--self-test` both exit 0. Round 4 (final, PR #1440 CI fix): CI's `Doc citations` job gates on the pull request's base sha (`github.event.pull_request.base.sha`), which for a branch stacked on another branch but opened against `main` is `main`'s sha, not the parent branch's — for #1440 that is `595920e91c45`, not `f76c8eb3`. Both prior rounds verified only against `f76c8eb3` (the direct parent), which was insufficient: `mod.rs:1339` at `LIFECYCLE.md:681` and `:696` (both citing `counter`'s declaration in `Mux::ready_inner`) were already correct relative to `f76c8eb3` — unchanged, unmoved, genuinely accurate — but wrong relative to `595920e91c45`, because unrelated commits between that main sha and `f76c8eb3` shifted `mod.rs` and coincidentally left `mod.rs:1339` holding different, also-plausible content (`if self.frontend.readiness().event.is_hup()`) at the older base. Re-derived from the construct each sentence names (`grep -n 'let mut counter = 0;' mod.rs` -> `1339`, inside `fn ready_inner`, confirmed `1338` is that function's closing `) -> SessionResult {` and `1339` is the declaration itself — both non-blank, so a tight range is valid) and re-anchored both citations to `mod.rs:1338-1339`, breaking the collision with the stale base-era content the same way as the earlier `6058`/`2706` collisions. `check_doc_citations.py --base 595920e` and `--base f76c8eb` both exit 0. `cargo +nightly fmt --all -- --check` exits 0; nothing else re-run since only `LIFECYCLE.md` changed. Closes #1423 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 22, 2026
H2DrainState (draining, peer_last_stream_id, started_at, graceful_shutdown_deadline, initial_goaway_pending) was already socket-free. What was not is the six ConnectionH2 functions that read and wrote it: graceful_goaway, goaway, send_initial_goaway, handle_goaway_frame, peer_gone_after_final_goaway, and the GOAWAY stage of flush_pending_control_frames. Move the decision - draining or not, defer-or-send, budget-elapsed - into h2_drain.rs behind the same closed-API shape hpack_state.rs, h2_flow_control.rs, h2_stream_table.rs and h2_flood_detector.rs established in the four prior extraction steps: - H2DrainState::begin_graceful_drain replaces graceful_goaway's state-mutating half, returning a GracefulDrainDecision (AlreadyDraining / DeferInitial / SendInitial). - H2DrainState::take_deferred_initial_goaway replaces the check-and-clear at the top of flush_pending_control_frames' GOAWAY stage. - H2DrainState::enter_final_goaway replaces the two-field mutation in goaway(); H2DrainState::observe_peer_goaway replaces it in handle_goaway_frame, which now reads back its own recorded peer_last_stream_id() for the retry-loop comparison. - H2DrainState::deadline_elapsed replaces graceful_shutdown_deadline_elapsed's body, taking now: Instant as an explicit parameter instead of reading a clock. Every decision method that needs the header-block-reassembly guard takes it as a caller-computed bool rather than reaching for self.zero/self.state itself - h2_drain.rs has neither - which keeps the module structurally unable to reintroduce the zero.storage dual-role clobber (#1396, #1397, #1401) that LIFECYCLE.md's new invariant 24 documents. peer_gone_after_final_goaway and force_disconnect stay on ConnectionH2 untouched. Pure relocation, no behaviour change: proved by the compiler and the existing suite, including the #1397/#1401 regression tests passing unmodified. Reported but not fixed here: flush_pending_control_frames' frontend_hung_up_while_draining() stage clears zero.storage without checking header_block_reassembly_in_progress(), unlike every stage below it in the same function - a live gap of the same bug class. Also fixes 73 LIFECYCLE.md/doc/testing.md line citations that drifted from this changeset's line-number shifts in h2.rs (mechanically relocated via exact-text diff mapping against the branch base, each spot-verified), and the one pre-existing rule-1 failure that drift caused. Also fixes LIFECYCLE.md prose that quoted pre-refactor private-field access syntax on this and the three prior extractions' closed-API types (self.drain.draining, self.drain.started_at, self.streams, self.rst_sent, and a struct snippet showing expect_read/expect_write as pub when they are private) - code that no longer compiles now that those fields are private. The narrative paragraph in section 2.2 is rewritten to describe the actual API (begin_graceful_drain, enter_final_goaway, take_deferred_initial_goaway) instead of raw field assignment. The citation gate does not catch this class of drift: a line citation can resolve to a real, unchanged, on-topic line while the code fragment quoted in the surrounding prose no longer compiles. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 22, 2026
…ol-frame scratch ConnectionH2::zero served two incompatible roles: the read-side accumulator a HEADERS/CONTINUATION field block was reassembled into across however many readable() passes a block took (headers.header_block_fragment, a window over zero.storage), and the write-side scratch buffer every control-frame flush (WINDOW_UPDATE, RST_STREAM, GOAWAY) clears and reuses. Three bugs (#1396, #1397, #1401) shipped from the two roles sharing one buffer, each patched with its own header_block_reassembly_in_progress() guard, and a fourth site (#1423) was found unguarded while landing the third. Add h2_header_reassembly.rs: HeaderBlockAccumulator owns its bytes (Vec<u8>, no new dependency) instead of borrowing a window into zero.storage. The initiating HEADERS frame's fragment is copied out and zero.storage cleared in the same step that enters ContinuationHeader; each CONTINUATION frame's payload is folded in and zero.storage cleared again in the same step that leaves ContinuationFrame; the block is retired (decoded, or handed unread to the CVE-2024-27316 refusal path) through the single exit point matching the single entry point. The old zero.storage.end -= 9 trick that kept a CONTINUATION frame's incoming header from disturbing the accumulated fragment's physical position is gone; every zero-stream frame now frees zero.storage the same way every other frame type already did. No write-side code holds a field named header_reassembly, so a control-frame flush cannot reach the accumulated bytes of a reassembly in progress on its own: that write-side half of the collision is unrepresentable by construction, in every build profile. It is not the whole story. Review of the first version of this change found two hazards the type does not close by itself: - A same-module, read-side misuse can still leak the accumulator across streams: handle_headers_frame's RFC 9113 5.3.1 self-dependency early return retired the stream without retiring the accumulator, so the next HEADERS frame on an unrelated stream decoded against the previous stream's stale bytes. Fixed by retiring the accumulator on that return before the reset_stream/remove_dead_stream/return, and adding a debug_assert on the fast path confirming it never observes in-progress state there. debug_assert compiles out in release, so the type does not make this class of bug impossible by itself - it is caught here only because a human reviewed the code path. "Unrepresentable by construction" is therefore true for the write side only; the module doc, LIFECYCLE.md and CHANGELOG.md now say exactly that instead of overclaiming it for the whole type, and no longer claim a release build panics loudly on misuse (debug_assert compiles out there; a release build silently starts a fresh block instead, the #1396/#1397 shape). - Closes #1423 was justified on a false premise: that Ready::HUP means "the peer will send no more bytes," so the frontend-hung-up-while-draining stage could discard zero.storage unconditionally without ever touching a reassembly in progress. mio's is_read_closed() (which Ready::HUP is defined from) is true on a TCP half-close with data still queued in the kernel receive buffer, not only on a fully drained close, so a CONTINUATION frame split across TCP segments can still have its second segment readable after HUP fires. The stage now carries the same header_block_reassembly_in_progress() guard its five sibling call sites already had (the WINDOW_UPDATE-drain and RST_STREAM-drain stages in the same function, the deferred-initial-GOAWAY stage beside them, graceful_goaway's drain-defer decision, and flush_zero_buffer), restoring the guard the first version of this change removed. #1423 is closed by this changeset, but not by the mechanism the first version claimed. The property test (reassembly_property) is extended: it now actually composes a graceful_goaway deferral into the same interleave set as the WINDOW_UPDATE/RST_STREAM/HUP-while-draining triggers - the first version claimed this in four places without doing it, and generated a dead zeroth interleave that was never read - and generates each interleave point at either a frame boundary or mid-frame, splitting a CONTINUATION fragment's own bytes across two simulated TCP segments so the accumulator actually holds unretired bytes when the interleave fires; generating whole-frame writes only, as the first version did, always found zero.storage empty at interleave time and could not reach the B2 shape at all. Composing the deferral surfaced its own bug during development: the HUP-while-draining interleave's test-only drain-flag setter also flips draining() to true, so a plan combining both would silently take the already-draining branch of graceful_goaway instead of deferring - fixed by checking connection.drain.draining() directly instead of a separately tracked "did we already send GOAWAY" flag. Tests: a_legitimate_continuation_survives_a_hup_while_draining still pins the frame-boundary shape of #1423; a new a_continuation_frame_split_by_tcp_segmentation_survives_a_hup_while_draining pins the mid-frame shape B2 found, red on the unguarded stage (reproducing the predicted StringDecodingError(NotEnoughOctets) desync) and green with the guard restored; a new a_priority_self_dependency_reset_does_not_leak_the_reassembly_accumulator pins the accumulator leak, red on the un-retired early return and green after; the three existing pinning tests for #1396/#1397/#1401 still pass; the extended quickcheck property passes at both its default iteration count and at QUICKCHECK_TESTS=2000; the e2e test (try_h2_continuation_survives_a_graceful_drain_mid_reassembly) now asserts a GOAWAY witness so it cannot pass on a run where the race it targets never fired. LIFECYCLE.md invariant 24, doc/h2_mux_internals.md, doc/testing.md and CHANGELOG.md updated for both the original design and these findings, and softened where the first version overclaimed. Citation drift re-anchored throughout LIFECYCLE.md, including drift this changeset's own edits introduced after an earlier re-anchoring pass missed a later hunk; a small number of pre-existing wrong citations unrelated to this change (three in LIFECYCLE.md, one in doc/testing.md, and a handful in CHANGELOG.md's timer-accuracy entry that predate this branch and are outside the citation checker's doc/ + LIFECYCLE.md scope) are left as found. CHANGELOG.md also now documents the copy-cost trade-off of the multi-frame path (one memcpy per CONTINUATION frame, offset by the CVE-2024-27316 refusal path's old eager copy going away) and a behaviour change: payload_len > available_space() no longer implicitly caps a block's total size at the zero buffer's capacity now that zero.storage is cleared every frame instead of held for the whole block - only max_header_list_size (default 65536) still does. Round 2 (independent re-review of `bf407254`): CI runs `check_doc_citations.py --base "${{ github.event.pull_request.base.sha }}"` (`.github/workflows/ci.yml`), which for this branch is `f76c8eb3` — a check this changeset had never actually run. Against that exact base it exited 1 on a citation this changeset re-anchored to `h2.rs:6058` (the "close" backend-stream teardown line): a DIFFERENT LIFECYCLE.md citation happened to read that same number at `f76c8eb3`, and the checker's own drift rule keys identity on the (path, number) pair, not on which paragraph carries it. Re-anchored to the range `h2.rs:6057-6059`, which cannot collide, per the checker's own advice ("or better, cite a symbol"): `check_doc_citations.py --base f76c8eb` now exits 0. The round-1 report of "15 citations found and fixed, all verified" undercounted: it missed the `end_stream` Client/Server range pair (`LIFECYCLE.md:1030`/`:1033`, off by the same +17 as the rest but never actually corrected despite being investigated), and left two disclosed-as-pre-existing citations (`LIFECYCLE.md:303`, `:323`) that were in fact fixable now that their exact-source targets were re-derived directly (`grep -n` for the construct each sentence names, not an offset formula) — `:303`'s three-site illustration list now reads `h2.rs:6097/6194/6219` (`reset_stream`'s reset, `end_stream`'s Client-arm and Server-arm `ForwardTerminated` retirements — all independently grep-verified `StreamState::Unlinked` assignment sites), and `:323`'s `unlink_stream` call-site pair now reads `h2.rs:6145/6089` (keeping `6089`, which was already correct). `doc/testing.md`'s own `emit_pending_size_update_if_new_block` arm site drifted the same way, `h2.rs:5424` (now itself a different-but-real `handle_rst_stream_frame` citation) corrected to `h2.rs:5476` (`self.pending_table_size_update = Some(capped);`). This round independently re-enumerated every citation whose value differs from `f76c8eb3` (91 across `LIFECYCLE.md` and `doc/testing.md` by this round's own count — broader than a narrower "re-anchored only" count, since it also covers freshly authored citations, not just re-anchored ones) and verified each by reading the cited source line(s) against the sentence's own claim, not by re-deriving from the same shift formula that produced these errors. All checked out except the ones named above, now fixed, and the one citation (`LIFECYCLE.md:371`) this changeset's own text already discloses as pre-existing and intentionally left. `check_doc_citations.py --base f76c8eb` exits 0. Two more items from this round. First, a residual this changeset's B2 guard opens: with `h2_graceful_shutdown_deadline_seconds` explicitly set to `0` (`None`, "indefinite wait explicitly opted in" per `h2_drain.rs`'s own doc comment), `Mux::shutting_down_inner`'s forced-close branch never fires, and a peer dying mid-CONTINUATION during a drain leaves `zero.storage` non-empty forever — `ConnectionH2::has_pending_write` (`h2.rs:4400-4407`) never flips to `false`, and shutdown waits indefinitely. Traced through source rather than assumed; documented in CHANGELOG.md as a real, narrow (opt-out-of-the-default-deadline-only) hole the fix opens, not fixed in this changeset. Second, `check_doc_citations.py`'s `doc_files()` never covers `CHANGELOG.md` (108 `file.rs:NNN` matches, 105 unique, by this script's own `CITATION` regex, none of them checked by anything) — recorded in that function's own docstring. Round 3 (final): two one-line corrections from a second independent pass. `LIFECYCLE.md:303`'s "Transitions:" enumeration cited three of the four real `StreamState::Unlinked` assignment sites (`h2.rs:6097/6194/6219`) and silently dropped the fourth: `6237` is `EndStreamAction::CloseDelimited`'s sibling arm to `6219`'s `ForwardTerminated`, in the same `match end_stream_decision(stream)` — now `h2.rs:6097/6194/6219/6237`. And this changeset's own prior claim of "102 citations, measured" in `check_doc_citations.py`'s docstring was itself unverified: counted with the script's own `CITATION` regex (`PATH = r"[A-Za-z0-9_][A-Za-z0-9_./-]*\.rs"`, `SPAN = r"[0-9]+(?:-[0-9]+)?"`) rather than an ad hoc backtick-anchored grep, CHANGELOG.md carries 108 matches (105 unique `(path, spans)` pairs) — the backtick requirement in the earlier grep silently excluded citations not wrapped in backticks. Docstring corrected to state both numbers and the regex used to produce them. `check_doc_citations.py --base f76c8eb` and `--self-test` both exit 0. Round 4 (final, PR #1440 CI fix): CI's `Doc citations` job gates on the pull request's base sha (`github.event.pull_request.base.sha`), which for a branch stacked on another branch but opened against `main` is `main`'s sha, not the parent branch's — for #1440 that is `595920e91c45`, not `f76c8eb3`. Both prior rounds verified only against `f76c8eb3` (the direct parent), which was insufficient: `mod.rs:1339` at `LIFECYCLE.md:681` and `:696` (both citing `counter`'s declaration in `Mux::ready_inner`) were already correct relative to `f76c8eb3` — unchanged, unmoved, genuinely accurate — but wrong relative to `595920e91c45`, because unrelated commits between that main sha and `f76c8eb3` shifted `mod.rs` and coincidentally left `mod.rs:1339` holding different, also-plausible content (`if self.frontend.readiness().event.is_hup()`) at the older base. Re-derived from the construct each sentence names (`grep -n 'let mut counter = 0;' mod.rs` -> `1339`, inside `fn ready_inner`, confirmed `1338` is that function's closing `) -> SessionResult {` and `1339` is the declaration itself — both non-blank, so a tight range is valid) and re-anchored both citations to `mod.rs:1338-1339`, breaking the collision with the stale base-era content the same way as the earlier `6058`/`2706` collisions. `check_doc_citations.py --base 595920e` and `--base f76c8eb` both exit 0. `cargo +nightly fmt --all -- --check` exits 0; nothing else re-run since only `LIFECYCLE.md` changed. Closes #1423 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 22, 2026
…lush cannot clobber header reassembly (#1440) * refactor(mux-h2): separate HEADERS+CONTINUATION reassembly from control-frame scratch ConnectionH2::zero served two incompatible roles: the read-side accumulator a HEADERS/CONTINUATION field block was reassembled into across however many readable() passes a block took (headers.header_block_fragment, a window over zero.storage), and the write-side scratch buffer every control-frame flush (WINDOW_UPDATE, RST_STREAM, GOAWAY) clears and reuses. Three bugs (#1396, #1397, #1401) shipped from the two roles sharing one buffer, each patched with its own header_block_reassembly_in_progress() guard, and a fourth site (#1423) was found unguarded while landing the third. Add h2_header_reassembly.rs: HeaderBlockAccumulator owns its bytes (Vec<u8>, no new dependency) instead of borrowing a window into zero.storage. The initiating HEADERS frame's fragment is copied out and zero.storage cleared in the same step that enters ContinuationHeader; each CONTINUATION frame's payload is folded in and zero.storage cleared again in the same step that leaves ContinuationFrame; the block is retired (decoded, or handed unread to the CVE-2024-27316 refusal path) through the single exit point matching the single entry point. The old zero.storage.end -= 9 trick that kept a CONTINUATION frame's incoming header from disturbing the accumulated fragment's physical position is gone; every zero-stream frame now frees zero.storage the same way every other frame type already did. No write-side code holds a field named header_reassembly, so a control-frame flush cannot reach the accumulated bytes of a reassembly in progress on its own: that write-side half of the collision is unrepresentable by construction, in every build profile. It is not the whole story. Review of the first version of this change found two hazards the type does not close by itself: - A same-module, read-side misuse can still leak the accumulator across streams: handle_headers_frame's RFC 9113 5.3.1 self-dependency early return retired the stream without retiring the accumulator, so the next HEADERS frame on an unrelated stream decoded against the previous stream's stale bytes. Fixed by retiring the accumulator on that return before the reset_stream/remove_dead_stream/return, and adding a debug_assert on the fast path confirming it never observes in-progress state there. debug_assert compiles out in release, so the type does not make this class of bug impossible by itself - it is caught here only because a human reviewed the code path. "Unrepresentable by construction" is therefore true for the write side only; the module doc, LIFECYCLE.md and CHANGELOG.md now say exactly that instead of overclaiming it for the whole type, and no longer claim a release build panics loudly on misuse (debug_assert compiles out there; a release build silently starts a fresh block instead, the #1396/#1397 shape). - Closes #1423 was justified on a false premise: that Ready::HUP means "the peer will send no more bytes," so the frontend-hung-up-while-draining stage could discard zero.storage unconditionally without ever touching a reassembly in progress. mio's is_read_closed() (which Ready::HUP is defined from) is true on a TCP half-close with data still queued in the kernel receive buffer, not only on a fully drained close, so a CONTINUATION frame split across TCP segments can still have its second segment readable after HUP fires. The stage now carries the same header_block_reassembly_in_progress() guard its five sibling call sites already had (the WINDOW_UPDATE-drain and RST_STREAM-drain stages in the same function, the deferred-initial-GOAWAY stage beside them, graceful_goaway's drain-defer decision, and flush_zero_buffer), restoring the guard the first version of this change removed. #1423 is closed by this changeset, but not by the mechanism the first version claimed. The property test (reassembly_property) is extended: it now actually composes a graceful_goaway deferral into the same interleave set as the WINDOW_UPDATE/RST_STREAM/HUP-while-draining triggers - the first version claimed this in four places without doing it, and generated a dead zeroth interleave that was never read - and generates each interleave point at either a frame boundary or mid-frame, splitting a CONTINUATION fragment's own bytes across two simulated TCP segments so the accumulator actually holds unretired bytes when the interleave fires; generating whole-frame writes only, as the first version did, always found zero.storage empty at interleave time and could not reach the B2 shape at all. Composing the deferral surfaced its own bug during development: the HUP-while-draining interleave's test-only drain-flag setter also flips draining() to true, so a plan combining both would silently take the already-draining branch of graceful_goaway instead of deferring - fixed by checking connection.drain.draining() directly instead of a separately tracked "did we already send GOAWAY" flag. Tests: a_legitimate_continuation_survives_a_hup_while_draining still pins the frame-boundary shape of #1423; a new a_continuation_frame_split_by_tcp_segmentation_survives_a_hup_while_draining pins the mid-frame shape B2 found, red on the unguarded stage (reproducing the predicted StringDecodingError(NotEnoughOctets) desync) and green with the guard restored; a new a_priority_self_dependency_reset_does_not_leak_the_reassembly_accumulator pins the accumulator leak, red on the un-retired early return and green after; the three existing pinning tests for #1396/#1397/#1401 still pass; the extended quickcheck property passes at both its default iteration count and at QUICKCHECK_TESTS=2000; the e2e test (try_h2_continuation_survives_a_graceful_drain_mid_reassembly) now asserts a GOAWAY witness so it cannot pass on a run where the race it targets never fired. LIFECYCLE.md invariant 24, doc/h2_mux_internals.md, doc/testing.md and CHANGELOG.md updated for both the original design and these findings, and softened where the first version overclaimed. Citation drift re-anchored throughout LIFECYCLE.md, including drift this changeset's own edits introduced after an earlier re-anchoring pass missed a later hunk; a small number of pre-existing wrong citations unrelated to this change (three in LIFECYCLE.md, one in doc/testing.md, and a handful in CHANGELOG.md's timer-accuracy entry that predate this branch and are outside the citation checker's doc/ + LIFECYCLE.md scope) are left as found. CHANGELOG.md also now documents the copy-cost trade-off of the multi-frame path (one memcpy per CONTINUATION frame, offset by the CVE-2024-27316 refusal path's old eager copy going away) and a behaviour change: payload_len > available_space() no longer implicitly caps a block's total size at the zero buffer's capacity now that zero.storage is cleared every frame instead of held for the whole block - only max_header_list_size (default 65536) still does. Round 2 (independent re-review of `bf407254`): CI runs `check_doc_citations.py --base "${{ github.event.pull_request.base.sha }}"` (`.github/workflows/ci.yml`), which for this branch is `f76c8eb3` — a check this changeset had never actually run. Against that exact base it exited 1 on a citation this changeset re-anchored to `h2.rs:6058` (the "close" backend-stream teardown line): a DIFFERENT LIFECYCLE.md citation happened to read that same number at `f76c8eb3`, and the checker's own drift rule keys identity on the (path, number) pair, not on which paragraph carries it. Re-anchored to the range `h2.rs:6057-6059`, which cannot collide, per the checker's own advice ("or better, cite a symbol"): `check_doc_citations.py --base f76c8eb` now exits 0. The round-1 report of "15 citations found and fixed, all verified" undercounted: it missed the `end_stream` Client/Server range pair (`LIFECYCLE.md:1030`/`:1033`, off by the same +17 as the rest but never actually corrected despite being investigated), and left two disclosed-as-pre-existing citations (`LIFECYCLE.md:303`, `:323`) that were in fact fixable now that their exact-source targets were re-derived directly (`grep -n` for the construct each sentence names, not an offset formula) — `:303`'s three-site illustration list now reads `h2.rs:6097/6194/6219` (`reset_stream`'s reset, `end_stream`'s Client-arm and Server-arm `ForwardTerminated` retirements — all independently grep-verified `StreamState::Unlinked` assignment sites), and `:323`'s `unlink_stream` call-site pair now reads `h2.rs:6145/6089` (keeping `6089`, which was already correct). `doc/testing.md`'s own `emit_pending_size_update_if_new_block` arm site drifted the same way, `h2.rs:5424` (now itself a different-but-real `handle_rst_stream_frame` citation) corrected to `h2.rs:5476` (`self.pending_table_size_update = Some(capped);`). This round independently re-enumerated every citation whose value differs from `f76c8eb3` (91 across `LIFECYCLE.md` and `doc/testing.md` by this round's own count — broader than a narrower "re-anchored only" count, since it also covers freshly authored citations, not just re-anchored ones) and verified each by reading the cited source line(s) against the sentence's own claim, not by re-deriving from the same shift formula that produced these errors. All checked out except the ones named above, now fixed, and the one citation (`LIFECYCLE.md:371`) this changeset's own text already discloses as pre-existing and intentionally left. `check_doc_citations.py --base f76c8eb` exits 0. Two more items from this round. First, a residual this changeset's B2 guard opens: with `h2_graceful_shutdown_deadline_seconds` explicitly set to `0` (`None`, "indefinite wait explicitly opted in" per `h2_drain.rs`'s own doc comment), `Mux::shutting_down_inner`'s forced-close branch never fires, and a peer dying mid-CONTINUATION during a drain leaves `zero.storage` non-empty forever — `ConnectionH2::has_pending_write` (`h2.rs:4400-4407`) never flips to `false`, and shutdown waits indefinitely. Traced through source rather than assumed; documented in CHANGELOG.md as a real, narrow (opt-out-of-the-default-deadline-only) hole the fix opens, not fixed in this changeset. Second, `check_doc_citations.py`'s `doc_files()` never covers `CHANGELOG.md` (108 `file.rs:NNN` matches, 105 unique, by this script's own `CITATION` regex, none of them checked by anything) — recorded in that function's own docstring. Round 3 (final): two one-line corrections from a second independent pass. `LIFECYCLE.md:303`'s "Transitions:" enumeration cited three of the four real `StreamState::Unlinked` assignment sites (`h2.rs:6097/6194/6219`) and silently dropped the fourth: `6237` is `EndStreamAction::CloseDelimited`'s sibling arm to `6219`'s `ForwardTerminated`, in the same `match end_stream_decision(stream)` — now `h2.rs:6097/6194/6219/6237`. And this changeset's own prior claim of "102 citations, measured" in `check_doc_citations.py`'s docstring was itself unverified: counted with the script's own `CITATION` regex (`PATH = r"[A-Za-z0-9_][A-Za-z0-9_./-]*\.rs"`, `SPAN = r"[0-9]+(?:-[0-9]+)?"`) rather than an ad hoc backtick-anchored grep, CHANGELOG.md carries 108 matches (105 unique `(path, spans)` pairs) — the backtick requirement in the earlier grep silently excluded citations not wrapped in backticks. Docstring corrected to state both numbers and the regex used to produce them. `check_doc_citations.py --base f76c8eb` and `--self-test` both exit 0. Round 4 (final, PR #1440 CI fix): CI's `Doc citations` job gates on the pull request's base sha (`github.event.pull_request.base.sha`), which for a branch stacked on another branch but opened against `main` is `main`'s sha, not the parent branch's — for #1440 that is `595920e91c45`, not `f76c8eb3`. Both prior rounds verified only against `f76c8eb3` (the direct parent), which was insufficient: `mod.rs:1339` at `LIFECYCLE.md:681` and `:696` (both citing `counter`'s declaration in `Mux::ready_inner`) were already correct relative to `f76c8eb3` — unchanged, unmoved, genuinely accurate — but wrong relative to `595920e91c45`, because unrelated commits between that main sha and `f76c8eb3` shifted `mod.rs` and coincidentally left `mod.rs:1339` holding different, also-plausible content (`if self.frontend.readiness().event.is_hup()`) at the older base. Re-derived from the construct each sentence names (`grep -n 'let mut counter = 0;' mod.rs` -> `1339`, inside `fn ready_inner`, confirmed `1338` is that function's closing `) -> SessionResult {` and `1339` is the declaration itself — both non-blank, so a tight range is valid) and re-anchored both citations to `mod.rs:1338-1339`, breaking the collision with the stale base-era content the same way as the earlier `6058`/`2706` collisions. `check_doc_citations.py --base 595920e` and `--base f76c8eb` both exit 0. `cargo +nightly fmt --all -- --check` exits 0; nothing else re-run since only `LIFECYCLE.md` changed. Closes #1423 Signed-off-by: Florentin Dubois <[email protected]> * test(e2e): replace the H2 CONTINUATION+drain sleeps with observable gates test_h2_continuation_survives_a_graceful_drain_mid_reassembly sequenced three events with two fixed thread::sleep(150ms) windows: sozu reading stream 3's partial HEADERS, the soft_stop drain landing on that connection, and the CONTINUATION completing the block. Neither window is guaranteed under load. Measured on a 20-core box at load average 219, the test failed 3 runs out of 3 with anchor_ok=true stream3_ok=false drain_witnessed=true - the intended interleaving simply never happened, so the run proved nothing and the assertions failed anyway. No in-band probe can establish either ordering. RFC 9113 6.2/6.10 forbid interleaving any frame into an open header block and handle_continuation_header_state answers GOAWAY(PROTOCOL_ERROR) for a non-CONTINUATION frame header, so a PING round-trip would destroy the connection it was meant to measure. The drain is equally invisible: graceful_goaway takes GracefulDrainDecision::DeferInitial while reassembly is in progress, precisely so serializing a GOAWAY cannot clobber the block, so in the interleaving under test no GOAWAY is emitted until the CONTINUATION completes - gating on one would wait for a frame that correct behaviour guarantees will not come, and would proceed only in the runs where the premise had already been missed. The control plane can see both. Both gates are bounded polls with a 5-second deadline, matching the anchor-reached-backend poll already in this test: - h2.frames.rx.headers ticking once proves handle_frame dispatched the partial HEADERS to handle_headers_frame, which with END_HEADERS clear is what assigns H2State::ContinuationHeader. Counter and transition are one synchronous pass, so a later command round-trip observing the increment proves the state is live. - server.live dropping to 0 proves Server::run completed an iteration with shutting_down set. shut_down_sessions() runs immediately after that gauge write in the same iteration and is what reaches Mux::shutting_down -> ConnectionH2::graceful_goaway; command responses are produced earlier in the loop body, so a query returning 0 was answered no earlier than the next iteration. - A second tick of the same counter proves the CONTINUATION was consumed, via the (H2State::ContinuationFrame(_), _) arm's re-entry into handle_frame(Frame::Headers(..)). The anchor stream is now held rather than merely slow. Its 600ms delay was an ordering requirement expressed as a duration, and the gates above cost control-plane round-trips whose cost is set by machine load: with the drain gate measured at 352ms on one attempt and 642ms on the next, the anchor resolved first, the drain concluded the connection had nothing left to wait for, and the CONTINUATION was never read - stream 1 served, stream 3 dropped. DelayedH2Backend::start_held holds every response until release(), called once the CONTINUATION is confirmed consumed, so the ordering holds by construction at any load. start() is unchanged for its two existing callers: the release flag starts set, so that loop never runs. query_proxy_metric returns None instead of panicking when the worker has already exited, so a worker that dies mid-poll surfaces as the caller's own timeout and diagnostic rather than a panic thrown from inside a query helper. Verified: 3 isolated runs green where the previous shape failed 3 of 3, and 6 concurrent invocations under 60 CPU burners all green where the previous shape failed 5 of 6 at comparable load. Inverting the guarantee turns it red: corrupting the accumulated block in graceful_goaway fails with "sozu never completed stream 3's header block" and left: Fail / right: Success. Inverting only graceful_goaway's reassembly_in_progress decision does NOT turn it red - after this branch's extraction the block lives in HeaderBlockAccumulator rather than zero.storage, so that decision no longer protects this shape on its own. The previous test shape did not detect that inversion either; its colour tracked machine load, not behaviour. CHANGELOG folds into the existing entry rather than adding its own: the test does not exist on main, git log -S naming it returns only 3be8c88, so a separate Fixed entry would announce repairing a defect that never shipped. Signed-off-by: Florentin Dubois <[email protected]> --------- Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 23, 2026
…e protects test_h2_continuation_survives_a_graceful_drain_mid_reassembly wrote stream 3's CONTINUATION in a single TLS write, so the soft-stop drain always landed on a frame BOUNDARY: reassembly in progress, but zero.storage empty and the accumulated block already copied into ConnectionH2::header_reassembly, where no write-side site names it. graceful_goaway's GracefulDrainDecision::DeferInitial therefore protected nothing the test could observe - forcing its reassembly_in_progress argument to false left the test green, measured 3/3 at 04fade6, so the production guarantee could have been deleted outright without this test noticing (#1453). The window that decision still guards is the one h2_header_reassembly.rs names: one CONTINUATION frame mid-socket_read(), its already-read bytes parked in zero.storage while expect_read still owes the rest, which send_initial_goaway's zero.storage.clear() destroys on its way to serializing the GOAWAY. Split the CONTINUATION across two TLS writes with the drain triggered between them - the wire-level twin of the mid-frame interleave reassembly_property already generates at the unit level. No production code changed. The ordering holds by construction, not by timing; no sleep sequences the two writes. The new gate is bytes_in, which ConnectionH2::handle_read advances on every frontend socket read, PARTIAL ones included - precisely what h2.frames.rx.headers cannot do, since handle_frame ticks it only on a frame completed and it can therefore never witness a frame still arriving. read_space caps each read at exactly the bytes the current frame stage expects, so the first chunk costs exactly two reads (the 9-byte frame header, then the partial payload) and the counter settles at exactly baseline + first_chunk.len(). Reaching that total is what proves the half-read frame is parked; an overshoot fails the run loudly rather than being rounded away by the poll's <, since it would mean something other than this test's own writes feeds the counter. Discrimination re-measured, because this test's colour has been observed to track machine load rather than behaviour and one red on a quiet box settles nothing: inverting reassembly_in_progress to false now reds it 63 invocations out of 63 with no green at all - 15/15 sequentially at 1-minute load 2.2-6.4, and 48/48 under a 6-concurrent harness at load 4.5-31 - every one through the same StringDecodingError(NotEnoughOctets) HPACK decoder desync #1397/#1401 already showed, and none through any other mechanism. The unmodified guarantee is green 25/25 sequentially and 36/36 under 6-way concurrency. Under artificial 2x-CPU-oversubscription (peak 1-minute load 47.6) the changed test fails 4/48 and the UNCHANGED test measured the same way (peak 49.1) fails 11/48, both with the identical anchor_ok=true stream3_ok=false drain_witnessed=true shape: collect_response_frames's fixed 30x50ms collection window, a pre-existing property this changeset deliberately does not widen - a deadline raised to make a run land is the defect #1453 exists to remove. doc/testing.md gains the convention this defect class distils: a test for a guarantee that protects a mid-frame window has to reach that window, a whole-frame write never does, and the only thing that settles it is inverting the production decision and confirming the test turns red. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 23, 2026
…e protects (#1481) test_h2_continuation_survives_a_graceful_drain_mid_reassembly wrote stream 3's CONTINUATION in a single TLS write, so the soft-stop drain always landed on a frame BOUNDARY: reassembly in progress, but zero.storage empty and the accumulated block already copied into ConnectionH2::header_reassembly, where no write-side site names it. graceful_goaway's GracefulDrainDecision::DeferInitial therefore protected nothing the test could observe - forcing its reassembly_in_progress argument to false left the test green, measured 3/3 at 04fade6, so the production guarantee could have been deleted outright without this test noticing (#1453). The window that decision still guards is the one h2_header_reassembly.rs names: one CONTINUATION frame mid-socket_read(), its already-read bytes parked in zero.storage while expect_read still owes the rest, which send_initial_goaway's zero.storage.clear() destroys on its way to serializing the GOAWAY. Split the CONTINUATION across two TLS writes with the drain triggered between them - the wire-level twin of the mid-frame interleave reassembly_property already generates at the unit level. No production code changed. The ordering holds by construction, not by timing; no sleep sequences the two writes. The new gate is bytes_in, which ConnectionH2::handle_read advances on every frontend socket read, PARTIAL ones included - precisely what h2.frames.rx.headers cannot do, since handle_frame ticks it only on a frame completed and it can therefore never witness a frame still arriving. read_space caps each read at exactly the bytes the current frame stage expects, so the first chunk costs exactly two reads (the 9-byte frame header, then the partial payload) and the counter settles at exactly baseline + first_chunk.len(). Reaching that total is what proves the half-read frame is parked; an overshoot fails the run loudly rather than being rounded away by the poll's <, since it would mean something other than this test's own writes feeds the counter. Discrimination re-measured, because this test's colour has been observed to track machine load rather than behaviour and one red on a quiet box settles nothing: inverting reassembly_in_progress to false now reds it 63 invocations out of 63 with no green at all - 15/15 sequentially at 1-minute load 2.2-6.4, and 48/48 under a 6-concurrent harness at load 4.5-31 - every one through the same StringDecodingError(NotEnoughOctets) HPACK decoder desync #1397/#1401 already showed, and none through any other mechanism. The unmodified guarantee is green 25/25 sequentially and 36/36 under 6-way concurrency. Under artificial 2x-CPU-oversubscription (peak 1-minute load 47.6) the changed test fails 4/48 and the UNCHANGED test measured the same way (peak 49.1) fails 11/48, both with the identical anchor_ok=true stream3_ok=false drain_witnessed=true shape: collect_response_frames's fixed 30x50ms collection window, a pre-existing property this changeset deliberately does not widen - a deadline raised to make a run land is the defect #1453 exists to remove. doc/testing.md gains the convention this defect class distils: a test for a guarantee that protects a mid-frame window has to reach that window, a whole-frame write never does, and the only thing that settles it is inverting the production decision and confirming the test turns red. Signed-off-by: Florentin Dubois <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Found while instructing #1339 (Q10/Q11, the socket boundary). Standalone and independent of any
sans-io decision.
This is the case PR #1396 identified but deliberately did not touch: a stream that is never
refused.
The defect
ConnectionH2::zeroserves two purposes at once.It is the read-side accumulation buffer for a HEADERS+CONTINUATION field block in progress —
header_block_fragmentis a(start, len)window into it that must stay valid across however manyreadable()passes the block takes, which is the protocol's own design.It is also the write scratch space
flush_pending_control_framesreuses to serialize any queuedWINDOW_UPDATE or RST_STREAM, on any stream.
Mux::readydispatches frontendreadable()thenwritable()in the same sweep. So ordinaryconnection-level flow-control housekeeping, landing between a stream's HEADERS and its CONTINUATION,
cleared
zero.storageout from under the accumulating fragment.No attacker is required. A WINDOW_UPDATE queued by normal flow control is enough.
The failure is silent, which is the worst part: the clobbered bytes still HPACK-decode. A legitimate
two-frame block carrying
x-sozu-marker: legitimate-valuecame back as("from", <garbage>)— awrong header pair, not a decode error.
The fix
header_block_reassembly_in_progress()(h2.rs:3887) is true whileself.stateisContinuationHeaderorContinuationFrame. It gates the WINDOW_UPDATE drain (h2.rs:3950) and theRST_STREAM drain (
h2.rs:4021) offlush_pending_control_frames(h2.rs:3899) to defer ratherthan flush.
Nothing is dropped: both frame kinds already arm
WRITABLEat queue time, so the nextwritable()after the block completes drains them normally.
This mirrors protection the codebase already applies to the same buffer in the other direction — a
stalled zero-buffer write already disables READABLE so a fresh read cannot clobber it. The read side
simply had no equivalent.
Red-then-green
Not test-shaped: the fix is a pure
self.stateguard over pre-existingH2Statevariants, sharingno literal with the test's marker header or values.
Flagged, not fixed
graceful_goaway(h2.rs:5011) unconditionally clearsself.zero.storageath2.rs:5029toserialize the advisory GOAWAY, despite its own comment stating the intent to keep reading in-flight
streams during the drain window. A worker's graceful shutdown or hot reload landing mid-reassembly
hits the identical corruption — unconditionally, every time, not only when a control frame
happens to be queued. Different trigger (
Mux::shutting_down, not the readable/writable sweep), soit wants its own changeset and its own test.
Docs
LIFECYCLE.mdgains the new invariant and 39 citation re-anchors forced by this changeset's own lineshift;
doc/h2_mux_internals.mddocuments the gated stages; one drifted citation indoc/testing.mdrepaired.
check_doc_citations.py --base origin/main: 0 unresolved, 0 drifted.