Skip to content

fix(mux-h2): never reset a backend stream whose HEADERS have not left - #1638

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
fix/h2-backend-stream-lifecycle
Sep 28, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
fix/h2-backend-stream-lifecycle

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

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
FlorentinDUBOIS force-pushed the fix/h2-backend-stream-lifecycle branch 3 times, most recently from 0ecbe60 to b16ccab Compare September 28, 2026 05:24
On a backend connection (Position::Client), ConnectionH2::start_stream
allocates the stream id when the router links a request, but the HEADERS
leave with a later write pass. ConnectionH2::end_stream and
ConnectionH2::cancel_timed_out_streams queued RST_STREAM(CANCEL) for a
stream retired in between, which the backend had never seen: a
connection error on an idle stream (RFC 9113 5.1, 6.4), queued ahead of
the client preface while the TCP connect was in progress (3.4). The
connection is shared by the streams of several clients (Router::connect),
so one cancelled request took all of them down.

A stream whose request never reached the socket (front.consumed false)
is now retired with no frame, as hyperium/h2 drops a stream still
pending open. Its id is burnt; the next HEADERS on a higher id closes it
implicitly (5.1.1). A HEADERS block parked unsent goes with it and
resets the HPACK encoder table on the next pass (#1627). For the same
reason the H2WritePhase::Prepare arm no longer hands the converter a
request in error whose HEADERS never left (an H1 frontend that rejects
a malformed body answers 400 itself and leaves the backend stream
registered): H2BlockConverter::initialize would queue the RST.

A write readiness while the server SETTINGS are awaited
(H2State::ServerSettings) no longer force-disconnects the connection as
an unexpected combination: start_stream arms one for every stream the
router links onto a Connected connection, whatever its handshake state.
It is withdrawn, and the SETTINGS ACK re-arms it. The ClientPreface arm
debug-asserts that nothing is queued ahead of the preface.

Also, in ConnectionH1::readable's Position::Server parse-error arm, a
request rejected after its response started (back.consumed) now cuts
that response and closes for writing, instead of splicing a complete
HTTP/1.1 400 into the body already streamed.

Closes #1631

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the fix/h2-backend-stream-lifecycle branch from b16ccab to de2df9f Compare September 28, 2026 06:44
@FlorentinDUBOIS
FlorentinDUBOIS merged commit cea53d6 into main Sep 28, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/h2-backend-stream-lifecycle branch September 28, 2026 07:49
FlorentinDUBOIS added a commit that referenced this pull request Sep 28, 2026
…onnection (#1639)

Closes #1632

## Problem

An H2 backend's write pass encodes a request in `kawa.prepare`: the request's `StatusLine`/`Header`/`Flags` blocks are popped out of `front.blocks` and `front.out` holds 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 with `front.out` full and `front.consumed == false`, and two paths then treated the request as untouched:

- the connection is lost → `H2Shell::close` hands the stream to its frontend → `end_stream_decision` answers `Reconnect` on `!front.consumed`;
- a GOAWAY below the stream → `ConnectionH2::handle_goaway_frame` re-links every unconsumed stream above `last_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::connect` prefers 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`, on `d5161919`): a request with `x-api-key: alice-secret` encoded 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-indexed `x-api-key`).

## Options and choice

1. Clear `front.out` and re-encode from the kawa: not possible — `kawa.prepare` already 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 in `FramedWrite::buffer`; moving sozu's encoding out of `kawa.prepare` is the broad refactor #1630 already declined).
2. **Refuse the retry once a request is encoded for an H2 backend (chosen).** Safe and small: the request never reaches another connection; the cost is an error answer in a race that required a 0-byte first write followed by the connection's loss. For the GOAWAY path the answer is a whole `503` response: the backend refused the request without processing it (RFC 9110 §15.6.4); for a lost connection it is the `502` a 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 in `Error`) is a RST_STREAM for an H2 frontend but nothing at all for an H1 frontend — `ConnectionH1::writable` withdraws 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 the `Position::Client` prepare in `ConnectionH2::poll_write_target` when it leaves output (one store, no allocation); cleared with the front kawa where a slot takes a new request (`Context::create_stream` reuse, `ConnectionH1` keep-alive reset); `false` in `Stream::new` (debug-asserted).
- `end_stream_decision` (shared with H1): `!consumed && front_bound_to_backend` → `SendDefault(502)` instead of `Reconnect` (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); `consumed` keeps its existing REFUSED_STREAM answer; the re-link branch debug-asserts `front.out` is empty.
- Defense in depth: `ConnectionH2::start_stream` refuses (before allocating an id) any request whose `front.out` already holds output — whatever produced it, including H1 bytes if a cluster's `http2` flag 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 the `d5161919` source):
- `a_request_encoded_for_a_backend_is_refused_on_goaway_not_relinked`: red `a request encoded for this backend must not be re-linked after its GOAWAY`
- `a_request_encoded_for_a_lost_backend_is_answered_not_relinked` (the frontend `end_stream` that `H2Shell::close` reaches): red `a request encoded for a lost backend must not be re-linked`
- `a_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 the `front_bound_to_backend` branch is deleted, `left: Reconnect, right: SendDefault(502)`
- `an_h1_client_behind_a_goaway_refusing_its_encoded_request_gets_a_response` (real `ConnectionH1` frontend behind the backend's GOAWAY): red with the REFUSED_STREAM answer, `the H1 client must read an error response, got ""`; green reads `HTTP/1.1 503`
- **H1 non-regression** `an_untouched_request_prepared_for_an_h1_backend_is_still_reconnected` (real `kawa::h1::BlockConverter` output, unsent): red if the decision keys on `!front.out.is_empty()` instead of the flag, `left: SendDefault(502), right: Reconnect`

## Commands (on the pushed head, rebased on `cea53d67`)

- `cargo build --locked` -> exit 0; `cargo +nightly fmt --all -- --check` -> exit 0
- `cargo clippy --all-targets --locked -- -D warnings` -> exit 0
- `cargo test -p sozu-lib --locked -- --test-threads=8` -> exit 0, 1331 passed, 0 failed
- `python3 .github/scripts/check_doc_citations.py` `--self-test`, `--root .`, `--root . --base origin/main`, `--audit --root .` -> all exit 0

Earlier head `256607bb` (base `5db53c60`): build, all-features, clippy x2, fmt, `cargo test --workspace` 2185 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.md` new "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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

h2: backend RST_STREAM for a stream whose HEADERS never left kills the shared backend connection

1 participant