Repository navigation
fix(mux-h2): never re-link a request encoded for another H2 backend connection - #1639
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 28, 2026 00:40
FlorentinDUBOIS
force-pushed
the
fix/h2-backend-stale-relink
branch
from
September 28, 2026 02:09
aeab5cc to
256607b
Compare
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 28, 2026
…#1638) Closes #1631 ## Problem On a backend H2 connection (`Position::Client`), `ConnectionH2::start_stream` allocates the stream id and registers it as soon as the router links a request, but the HEADERS leave with a later write pass. When the frontend gives up in between (client RST_STREAM or disconnect, stream idle timeout, backend timeout), `ConnectionH2::end_stream` and `ConnectionH2::cancel_timed_out_streams` queued `RST_STREAM(CANCEL)` for a stream the backend had never seen: | Backend connection state | What the backend received (reproduced on `d5161919`) | |---|---| | `Header`, HEADERS not written (or encoded and parked unsent) | `RST_STREAM(1)` on an idle stream: RFC 9113 §5.1/§6.4 connection error | | `ClientPreface` (TCP connect in progress) | `RST_STREAM(1)` **before** `PRI * HTTP/2.0` (§3.4) | | `ServerSettings` (preface out, server SETTINGS not read) | sozu itself force-disconnects: `Unexpected combination: (Writable, ServerSettings, Client)` | `Router::connect` multiplexes the streams of several clients on one backend connection, including one still `Connecting`, so one cancelled request took all of them down. While reproducing the third row I found it does not need `end_stream`: `start_stream` alone arms WRITABLE, and a backend connection is `Connected` from its first writable, before its preface is written, so the router links onto it during the handshake window and the next writable force-disconnects it (`a_request_linked_during_the_handshake_goes_out_after_the_settings` is red on `d5161919` with no `end_stream` at all). ## Fix - `Position::Client` arm of `ConnectionH2::end_stream`: RST only if `stream.front.consumed` (on this position exactly "a request byte reached this socket"; a stream's first frame is its HEADERS). A stream the backend never saw is retired with no frame — what hyperium/h2 does for a stream still pending open. HAProxy (`h2_frame_check_vs_state`) and hyperium/h2 (`Recv::ensure_not_idle`) both answer the idle-stream RST with GOAWAY(PROTOCOL_ERROR). - `ConnectionH2::cancel_timed_out_streams`: same guard before `enqueue_rst`. - `H2WritePhase::Prepare` arm of `ConnectionH2::poll_write_target` (found by the adversarial review): a request that turned `Error` while its backend stream is registered and its HEADERS never left (an H1 frontend rejecting a malformed chunked body answers 400 itself and leaves the backend stream in place) is no longer handed to the converter, whose `initialize` queued `RST_STREAM(INTERNAL_ERROR)` for the idle stream. It is left for `end_stream` / the idle reaper, which retire it without a frame. Fixed at the emission point rather than in the H1 error arm so every producer of a front `Error` is covered and H1 backends are untouched. - `dispatch_writable_state`: `(ServerSettings, Client)` leaves the `Unexpected combination` arm; it withdraws WRITABLE and continues. The SETTINGS ACK the read queues re-arms it, so a request linked during the handshake goes out after it (RFC 9113 §3.4 even allows sending before the server preface; sozu keeps waiting, which is the smaller change). - `(ClientPreface, Client)` debug-asserts that nothing is queued ahead of the preface. - **R1 (pre-existing, same arm family, requested in review):** `ConnectionH1::readable`, `Position::Server` parse-error arm — when the response already started (`back.consumed`), it is cut with `forcefully_terminate_answer` and the connection closes for writing (`defer_close_for_tls_flush`) instead of a complete `HTTP/1.1 400` being spliced into the streamed body; before any response byte the 400 is kept. - TigerStyle post-conditions: no frame queued for a never-opened stream (`end_stream`, `cancel_timed_out_streams`), the wire id is retired, WRITABLE withdrawn / READABLE kept while awaiting SETTINGS. **Stream ids (RFC 9113 §5.1.1).** The burnt id is not reused; the next HEADERS on a higher id closes it implicitly on the backend, which is harmless since it never processed it. Order is preserved: a write pass resumes a parked stream first and otherwise prepares client streams in ascending id (default urgency), so a lower id never gets its HEADERS after a higher one because of this change. **HPACK:** a HEADERS block encoded and parked unsent (#1627 situation on `Position::Client`) is dropped with the stream, and #1630's `parked_header_block` resets the encoder table on the next pass — `a_backend_stream_ended_with_its_headers_parked_is_not_reset` checks the next stream's block decodes on the backend. Nominal path: one `bool` read per retired backend stream, no allocation. ## Tests (red → green) All in `lib/src/protocol/mux/h2.rs`; red obtained by applying only the test changes onto the `d5161919` source (the first six) and the `6eef0ba1` source (the last). - `a_backend_stream_ended_before_its_headers_left_is_not_reset`: red `left: [0, 0, 4, 3, 0, 0, 0, 0, 1, 0, 0, 0, 8], right: []` - `a_backend_stream_ended_before_the_preface_leaves_the_preface_first`: red `the connection preface must come first, got [0, 0, 4, 3, 0, 0, 0, 0, 1, 0, 0, 0, 8, 80, 82, 73, ...]` - `a_backend_stream_ended_during_the_handshake_keeps_the_connection`: red `the shared connection must survive the handshake, got Error` - `a_request_linked_during_the_handshake_goes_out_after_the_settings` (liveness of the withdrawn readiness): red `premise: nothing is written before the server SETTINGS, got [] in Error` - `a_backend_stream_reaped_before_its_headers_left_is_not_reset`: red `a stream reaped before its HEADERS left must not be reset` - `a_backend_stream_ended_with_its_headers_parked_is_not_reset` (paced socket, 0-byte first write): red `no frame may name stream 1, which the backend never saw: [(3, 0, 1, [0, 0, 0, 8]), (1, 5, 3, ...)]` - `a_backend_stream_whose_request_failed_before_its_headers_left_is_not_reset` (reviewer's scenario): red on `6eef0ba1` `no frame may name stream 1, which the backend never saw: [(3, 0, 1, [0, 0, 0, 2])]` - `h1::tests::a_request_error_after_the_response_started_cuts_it_instead_of_splicing_a_400` (R1): red with the new arm removed, `no 400 may follow a response already on the wire, got "HTTP/1.1 400 Bad Request\r\n..."` - `end_stream_on_a_backend_mid_data_payload_sends_its_rst_before_reading_on`: fixture now sets `front.consumed = true` (the backend is answering, so the request left); it still pins that an opened stream IS reset. ## Commands - `cargo build --locked` -> exit 0; `cargo build --all-features --locked` -> exit 0 - `cargo clippy --all-targets --locked -- -D warnings` -> exit 0 - `cargo clippy --all-targets --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -- -D warnings` -> exit 0 - `cargo +nightly fmt --all -- --check` -> exit 0 - `cargo test --workspace --locked -- --skip tests::fuzz_tests:: --test-threads=8` -> exit 0, 2215 passed, 0 failed - `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked` -> exit 0, 31 passed - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` -> exit 0 - `python3 .github/scripts/check_doc_citations.py` `--self-test`, `--root .`, `--root . --base origin/main`, `--audit --root .` -> all exit 0 ## Docs `LIFECYCLE.md` §2.2 (backend handshake states), §8.2 (never RST a backend stream still idle), §8.4, new invariant 29; `doc/h2_mux_internals.md` new "A backend stream the backend never saw"; CHANGELOG (Fixed, two entries). Line citations shifted by this change re-anchored. ## Coordination Merge order #1640, #1638, #1639. #1639 is rebased after this one and numbers its LIFECYCLE invariant 30. Line citations this diff touches are converted to symbol citations where possible, so the next rebases do not conflict on them. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
fix/h2-backend-stale-relink
branch
2 times, most recently
from
September 28, 2026 08:24
096a01b to
4b9fd7c
Compare
…onnection An H2 backend's write pass encodes a request in kawa.prepare: the request's header blocks are popped and front.out holds HEADERS frames with that connection's stream id and a field block encoded against that connection's HPACK table. When the socket took none of it, front.consumed stayed false, so when the connection was lost end_stream_decision answered Reconnect, and a GOAWAY below the stream made ConnectionH2::handle_goaway_frame re-link it. The stale frames then went out first on the new connection, usually one Router::connect shares with other clients: decoded against that connection's table they rebuild a request with other clients' indexed fields, or fail with PROTOCOL_ERROR/COMPRESSION_ERROR and close every stream on it. Stream::front_bound_to_backend marks a request an H2 backend has encoded (one store in the Position::Client prepare, no allocation), cleared with the front kawa where the slot takes a new request. end_stream_decision answers it 502 instead of Reconnect; handle_goaway_frame answers it a whole 503 (refused unprocessed, RFC 9110 15.6.4) instead of re-linking it, since the empty Error answer of forcefully_terminate_answer is a RST_STREAM for an H2 frontend but silence for an H1 one; and, as defense in depth, ConnectionH2::start_stream refuses a request whose front.out already holds output. The request cannot be encoded again: its blocks are gone, and keeping a copy of every request's blocks would cost the nominal path. H1 backends keep Reconnect: their prepared output is plain HTTP/1.1 bytes any fresh connection sends as they are. Closes #1632 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
fix/h2-backend-stale-relink
branch
from
September 28, 2026 09:34
4b9fd7c to
66fc838
Compare
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 28, 2026
…se with a final GOAWAY (#1654) Closes #1647 ## Mechanism - `ConnectionH2::handle_header_state` creates the stream (`ConnectionH2::create_stream`) as soon as the HEADERS frame header arrives, and `ConnectionH2::handle_headers_frame` parks the connection in `H2State::ContinuationHeader` while END_HEADERS is clear. The stream stays `StreamState::Idle`. - `Mux::shutting_down_inner` (`lib/src/protocol/mux/mod.rs`) kept a draining session open only for `Linked` and non-quiesced `Unlinked` streams. Once the advisory `GOAWAY(NO_ERROR, 2^31-1)` was flushed, it returned `true` and `Server::shut_down_sessions` closed the session. - `ConnectionH2::finalize_write` sends the final GOAWAY only when the wire stream table is empty, and the forced-close arm (`graceful_shutdown_deadline_elapsed`) returned `true` without sending one. So the request was lost, and the client received no GOAWAY with a real `last_stream_id` (RFC 9113 §6.8). ## Fix - `Mux::shutting_down_inner` keeps an H2 frontend open: - while `ConnectionH2::peer_header_block_in_progress` holds (`ContinuationHeader` / `ContinuationFrame`); - while a stream is `StreamState::Link`. This is the state a CONTINUATION read by `Mux::drive_frontend_shutdown_io` leaves, outside `Mux::ready`, until the next `ready` pass links it. Without it, the same request could still be lost. Both waits are bounded by `h2_graceful_shutdown_deadline_seconds`. The request is then served, and `ConnectionH2::finalize_write` sends the final GOAWAY with its stream id. - When the budget elapses, `ConnectionH2::goaway_before_forced_close` queues the final `GOAWAY(NO_ERROR)` and it is flushed once, best effort, before the close. **Visible change:** this applies to every draining H2 session, with `Linked` streams included. Before, a forced close was preceded only by the advisory GOAWAY. - `last_stream_id` excludes a stream whose opening block never completed. When the block's stream is still `Idle`, the reported id is `stream_id - 2` (0 for stream 1). This is safe because: - every stream `create_stream` accepted has a lower id: RFC 9113 §5.1.1, enforced against `last_stream_id` in `handle_header_state`; - none can be accepted while the block is open (§6.10); - a higher id counted in `highest_peer_stream_id` can only be a refused stream. `ConnectionH2::goaway` now delegates to a private `goaway_with_last_stream_id`. Its other callers are unchanged. - Docs: - LIFECYCLE.md: new invariant **31** (30 is reserved by #1639), invariant 10 rewritten, §2.2, §8.1 and §8.3 updated. - `doc/h2_mux_internals.md`: shutdown section updated, and the pinned h2.rs blocks re-anchored. - `doc/configure.md` (the knob), CHANGELOG. ## Red / green New e2e tests (`e2e/src/tests/h2_tests.rs`), run on `ca42a2ea` without the fix: ``` H2 drain waits for header block - sent=true served=false goaways=[(2147483647, 0)] final_goaway_last=true stopped=true elapsed=10.49567ms test result: FAILED. 0 passed; 1 failed H2 drain deadline mid header block - goaways=[(2147483647, 0)] final_goaway_last=true never_forwarded=true stopped=true test result: FAILED. 0 passed; 1 failed ``` With the fix: ``` H2 drain waits for header block - sent=true served=true goaways=[(2147483647, 0), (1, 0)] final_goaway_last=true stopped=true elapsed=22.273184ms test result: ok. 1 passed H2 drain deadline mid header block - goaways=[(2147483647, 0), (0, 0)] final_goaway_last=true never_forwarded=true stopped=true test result: ok. 1 passed ``` `test_h2_graceful_drain_deadline_with_a_linked_stream_sends_final_goaway` covers the general forced-close change: a 1 s budget, a stream `Linked` to a backend that holds its response, then a soft-stop. With `goaway_before_forced_close` neutralized (its call removed from `Mux::shutting_down_inner`, the path main takes): ``` H2 drain deadline linked stream - goaways=[(2147483647, 0)] final_goaway_last=true stopped=true test result: FAILED. 0 passed; 1 failed ``` With the fix: ``` H2 drain deadline linked stream - goaways=[(2147483647, 0), (1, 0)] final_goaway_last=true stopped=true test result: ok. 1 passed ``` Each new e2e test was run 10 times in isolation: 10/10, 10/10 and 10/10. The `StreamState::Link` arm has no e2e test. Reaching it needs the CONTINUATION to arrive after `epoll_wait` returns and before `Server::shut_down_sessions` reads it in the same loop iteration. No command-channel or wire observation can place a write inside that window, so only timing could reach it, and the result would be flaky. The unit test pins that arm instead. The unit test `a_draining_h2_session_waits_for_a_stream_awaiting_its_link` (`lib/src/protocol/mux/mod.rs`) fails when the `StreamState::Link` arm is removed ("a draining H2 session must stay open for a stream awaiting its link") and passes with it. ## Validation (all exit 0) - `cargo +nightly fmt --all -- --check` - `cargo build --locked` - `cargo build --all-features --locked` - `cargo clippy --all-targets --locked -- -D warnings` - `cargo clippy --all-targets --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -- -D warnings` - `cargo test --workspace --locked -- --skip tests::fuzz_tests:: --test-threads=8`: e2e 486 passed, lib 1317 passed - `python3 .github/scripts/check_doc_citations.py --self-test`, `--root .`, `--root . --base origin/main`, `--audit --root .` - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` ## Rebase Rebased on `c086b456` (after #1639 and #1653). LIFECYCLE.md keeps main's invariant 30, then this change's 31. The pinned h2.rs blocks in `doc/h2_mux_internals.md` are re-anchored against the rebased `h2.rs`. The code diff is unchanged: `git patch-id --stable` over everything except `*.md` and CHANGELOG is `cff240bd6ce5b052ea69cf5597b2a1f88d12115d` both before (459f0a2) and after the rebase. 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.
Closes #1632
Problem
An H2 backend's write pass encodes a request in
kawa.prepare: the request'sStatusLine/Header/Flagsblocks are popped out offront.blocksandfront.outholds HEADERS/CONTINUATION frames carrying that connection's stream id and a field block encoded against that connection's HPACK table. The request counts as sent only once a byte moves (front.consumed). When the first write takes 0 bytes the stream is parked withfront.outfull andfront.consumed == false, and two paths then treated the request as untouched:H2Shell::closehands the stream to its frontend →end_stream_decisionanswersReconnecton!front.consumed;ConnectionH2::handle_goaway_framere-links every unconsumed stream abovelast_stream_id.Neither cleared
front.out(nor could restore the popped blocks), so the next backend's write pass sent the stale frames first.Router::connectprefers an existing, usually shared, H2 connection of the cluster: with a stream id above that connection's highest, the backend decodes the stale block against the shared table and rebuilds a request carrying other clients' indexed fields (cross-client substitution, silent); otherwise PROTOCOL_ERROR/COMPRESSION_ERROR takes every stream on it down.Reproduced (
a_request_encoded_for_one_backend_never_reaches_another, ond5161919): a request withx-api-key: alice-secretencoded on backend A and offered to backend B goes out on B unchanged —[(1, 5, 1, [130, 1, 11, 101, 120, 97, 109, 112, 108, 101, ... 64, 9, 120, 45, 97, 112, 105, 45, 107, 101, 121, ...])], i.e. HEADERS on A's stream id 1 with A's field block (incremental-indexedx-api-key).Options and choice
front.outand re-encode from the kawa: not possible —kawa.preparealready popped the blocks. Keeping them would mean copying every request's blocks on the nominal path (hyperium/h2 avoids the question by encoding at send time inFramedWrite::buffer; moving sozu's encoding out ofkawa.prepareis the broad refactor fix(mux-h2): reset the HPACK encoder table when an encoded block is dropped unsent #1630 already declined).503response: the backend refused the request without processing it (RFC 9110 §15.6.4); for a lost connection it is the502a consumed request already gets. REFUSED_STREAM was the first version of this PR, and the adversarial review showed its answer (forcefully_terminate_answer: an empty response kawa inError) is a RST_STREAM for an H2 frontend but nothing at all for an H1 frontend —ConnectionH1::writablewithdraws WRITABLE and the client waits for its timeout. The backend core cannot tell which frontend it serves, so it answers what both can write.Fix
Stream::front_bound_to_backend: set by thePosition::Clientprepare inConnectionH2::poll_write_targetwhen it leaves output (one store, no allocation); cleared with the front kawa where a slot takes a new request (Context::create_streamreuse,ConnectionH1keep-alive reset);falseinStream::new(debug-asserted).end_stream_decision(shared with H1):!consumed && front_bound_to_backend→SendDefault(502)instead ofReconnect(debug-asserted: such a request still holds its frames).handle_goaway_frame:front_bound_to_backend(unconsumed) →set_default_answer(503)instead of re-link (debug-asserted: a whole answer, never a silent error);consumedkeeps its existing REFUSED_STREAM answer; the re-link branch debug-assertsfront.outis empty.ConnectionH2::start_streamrefuses (before allocating an id) any request whosefront.outalready holds output — whatever produced it, including H1 bytes if a cluster'shttp2flag flipped between two attempts.H1 unaffected: an H1 backend never sets the flag. Its prepared output is plain HTTP/1.1 bytes that any fresh H1 connection sends as they are, so untouched H1 requests keep
Reconnect. The old connection's HPACK side is already handled by #1630: the refused stream is removed from its park, and the next pass resets the encoder table.Tests (red on
d5161919→ green)Connection level (
lib/src/protocol/mux/h2.rs, paced socket with a 0-byte first write; red obtained by applying only the test changes onto thed5161919source):a_request_encoded_for_a_backend_is_refused_on_goaway_not_relinked: reda request encoded for this backend must not be re-linked after its GOAWAYa_request_encoded_for_a_lost_backend_is_answered_not_relinked(the frontendend_streamthatH2Shell::closereaches): reda request encoded for a lost backend must not be re-linkeda_request_encoded_for_one_backend_never_reaches_another— the "no byte of one encoder leaves on another connection" property: red with A's HEADERS on B's wire (above)Decision level (
lib/src/protocol/mux/stream.rs):a_request_encoded_for_an_h2_backend_is_not_reconnected: red when thefront_bound_to_backendbranch is deleted,left: Reconnect, right: SendDefault(502)an_h1_client_behind_a_goaway_refusing_its_encoded_request_gets_a_response(realConnectionH1frontend behind the backend's GOAWAY): red with the REFUSED_STREAM answer,the H1 client must read an error response, got ""; green readsHTTP/1.1 503an_untouched_request_prepared_for_an_h1_backend_is_still_reconnected(realkawa::h1::BlockConverteroutput, unsent): red if the decision keys on!front.out.is_empty()instead of the flag,left: SendDefault(502), right: ReconnectCommands (on the pushed head, rebased on
cea53d67)cargo build --locked-> exit 0;cargo +nightly fmt --all -- --check-> exit 0cargo clippy --all-targets --locked -- -D warnings-> exit 0cargo test -p sozu-lib --locked -- --test-threads=8-> exit 0, 1331 passed, 0 failedpython3 .github/scripts/check_doc_citations.py--self-test,--root .,--root . --base origin/main,--audit --root .-> all exit 0Earlier head
256607bb(base5db53c60): build, all-features, clippy x2, fmt,cargo test --workspace2185 passed, sozu-sim 31 passed,cargo doc -D warnings, citations x4 -> all exit 0.Docs
LIFECYCLE.md§8.5 (decision table: new "encoded for an H2 backend, unsent" row and rationale), new invariant 30 (after #1638's 29);doc/h2_mux_internals.mdnew "An encoded request belongs to its backend connection"; CHANGELOG (Security). Line citations shifted by this change re-anchored.Coordination
Rebased on main after #1638 (
cea53d67); its LIFECYCLE invariant is 30, after #1638's 29. Line citations this diff shifts are converted to symbol citations (Context::create_stream,Mux::configured_frontend_timeout); only pinned code blocks keep line numbers.Signed-off-by: Florentin Dubois [email protected]