Skip to content

fix(mux-h2): keep reading after a stream is reaped mid DATA payload - #1599

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
fix/h2-readable-resume
Sep 27, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
fix/h2-readable-resume

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

When the per-stream idle reap or a reset removes a stream while the connection is reading a DATA payload into that stream's buffer, H2StreamTable::remove sets expect_read to None and changes nothing else. The connection stays in H2State::Frame with nothing to read. Every later readable() then returns at the expect_read() == None early exit, so the rest of the payload and every frame behind it stay unread until the connection timeout. Every other stream on that connection stalls with it.

A stream parked on buffer pressure and then reaped ends up in the same state, and READABLE interest is removed as well. try_resume_reading cannot restore it, because the stream no longer exists.

Fix

remove_dead_stream hands the unread remainder to skip_orphaned_data_payload, which does three things:

  • moves the connection to H2State::Discard with expect_read = Some((Zero, n)) and no field block, and drops the remainder as it is read, in pieces no larger than the free space in zero. The remainder is never buffered whole and never answered with a GOAWAY. HAProxy skips a dropped frame's payload the same way (src/mux_h2.c:4706-4716 at 0ceb8c65).
  • credits the frame's whole payload_len to the connection receive window (RFC 9113 §6.9), as handle_data_frame does for DATA on a closed stream. HAProxy does the same (src/mux_h2.c:4152-4157).
  • restores READABLE interest only while zero_holds_output() is false.

Backend end_stream RST

The skip makes a backend-side bug reachable. On a Position::Client connection, end_stream wrote its RST_STREAM(CANCEL) into zero without marking zero as holding output and without stopping reads. The next frame header was then read in behind the RST, and the backend connection took our own RST for one of the backend's frames. It answered with GOAWAY(PROTOCOL_ERROR), which killed every other multiplexed stream.

The RST now goes through queue_zero_output, the PING and SETTINGS ACK path from #1601:

Single read guard (unified with #1601)

The read guard in poll_read_target and the assertion in handle_header_state are the ones from #1601 (zero_holds_output()). This PR no longer adds its own. The same guard covers a stalled WINDOW_UPDATE or RST_STREAM flush, which leaves its unsent tail in zero under expect_write = Zero with READABLE still on. Slower CI runners hit that case through the assertion, and a regression test now pins it.

Tests

Each test was seen red with its part of the fix removed:

  • reaping_a_stream_mid_data_payload_keeps_the_connection_reading: red on the former main.
  • reaping_a_stream_parked_on_buffer_pressure_resumes_reading
  • a_remainder_near_max_frame_size_is_skipped_in_pieces
  • a_skipped_orphaned_data_payload_is_credited_to_the_connection_window
  • end_stream_on_a_backend_mid_data_payload_sends_its_rst_before_reading_on: without the fix the connection ends in state=GoAway and the backend receives nothing. With it, the backend receives exactly RST_STREAM(CANCEL), then the PING ACK.
  • skipping_an_orphaned_payload_keeps_readable_off_while_zero_holds_output
  • no_frame_header_is_read_while_zero_holds_unflushed_output: panics with the CI message when the zero_holds_output() guard is removed.

The #1601 tests still pass. The three e2e tests that failed in CI (test_h2_flow_control_on_orphaned_data, test_h2_large_payload, test_h2_mid_pass_rst_does_not_force_yield) pass 10 times out of 10 under taskset -c 0, with no assertion hit. The full e2e run gives 449 passed.

Docs

LIFECYCLE.md §5.4, doc/h2_mux_internals.md and CHANGELOG.md are updated. Doc citations are re-anchored to the same line text (check_doc_citations.py --base b03ffa2b: 215 cited lines unchanged).

Closes #1597

Signed-off-by: Florentin Dubois [email protected]

FlorentinDUBOIS added a commit that referenced this pull request Sep 26, 2026
…frame (#1601)

Closes #1600

## Problem

`handle_ping_frame` and the SETTINGS ACK serialise their acknowledgement into `zero` and set `expect_write = Some(Zero)` unconditionally. When the socket had taken only part of a HEADERS or DATA frame, the stream was parked as `expect_write = Some(Other { .. })`, and the ACK overwrote that park. The next `writable()` flushed `zero` first, then a fresh scheduler pass sent the rest of the frame. The peer read: first part of the frame, the ACK, the rest.

The same family showed up in three more places:

- `goaway()` and `send_initial_goaway()` clear `zero` and set `expect_write = Some(Zero)` even with a frame parked: the GOAWAY was flushed inside the frame and a queued ACK was destroyed. `send_initial_goaway` is what `Mux::shutting_down` reaches through `graceful_goaway`.
- `Mux::shutting_down` forces READABLE and calls `readable()` after `flush_zero_buffer`. With an ACK still in `zero`, the read landed on top of it: `handle_header_state` parsed the ACK as the peer's frame header, then cleared it.

## Fix

- `queue_zero_output` (both ACKs) and `park_zero_output` (both GOAWAYs) leave a stream park alone and set `zero_output_deferred`. The `Resume` arm of `poll_write_target`, once the parked frame is complete, hands `expect_write` to `Zero` and ends the pass, so queued control output follows the frame and precedes any other stream frame.
- `goaway()` and `send_initial_goaway()` append after output already queued in `zero` instead of clearing it. In `H2State::GoAway` a parked frame is still written, so the deferred GOAWAY can follow it.
- `poll_read_target` reads nothing into `zero` while it holds output (`zero_holds_output`: `expect_write == Some(Zero)` or `zero_output_deferred`), whatever forced READABLE. The flush restores READABLE interest, and the event is kept for that read. `handle_header_state` asserts that no output is pending.
- If the parked stream is removed before it resumes, the next control flush takes `zero` itself, so the connection does not stop reading.

HAProxy never hits this: `h2c_send_ping` and `h2c_ack_settings` (`src/mux_h2.c`) append at `br_tail(h2c->mbuf)`, the tail of the single output ring that also holds stream frames, and `h2_send` drains it in order. Sozu keeps control frames (`zero`) and stream frames (each stream's buffer) apart, so the order has to come from `expect_write`. Merging the two buffers is out of scope.

## Not fixed here

Removing a stream parked mid-frame (`H2StreamTable::remove` nulls the park; callers include peer RST_STREAM, `end_stream`, the idle reaper and `prune_inactive_streams_while_closing`) drops the rest of that frame, so the peer reads a truncated frame. This predates the change. Fixing it needs either keeping the remaining bytes (`remove_dead_stream` would need the stream context at every call site), delaying the removal until the frame is out, or a poisoned-wire state that stops every writer (control flush, GOAWAYs, `end_stream`'s RST, shutdown flush) and closes the connection. The test `a_deferred_ack_does_not_strand_reads_when_its_parked_stream_is_removed` therefore asserts only that the connection reads again, not the wire bytes.

## Interaction with #1599

#1599 adds a `debug_assert!` in `handle_header_state` that only checks `expect_write == Some(Zero)`. This PR adds one that covers `zero_output_deferred` too. Whichever of the two merges second must keep a single assertion, extended to `zero_output_deferred`, and re-run `check_doc_citations.py --base`.

## Tests

A test socket takes N bytes, then answers `WouldBlock`, and records what it took in order. It takes 20 bytes of a 41-byte DATA frame, then the output is parsed as the peer would parse it. Red on `fb7310fe`, green here:

- `a_forced_shutdown_read_does_not_eat_a_deferred_ack`: only the DATA frame reaches the peer, both ACKs are lost.
- `a_goaway_during_a_half_written_frame_follows_it_and_the_ack`: `Err("frame type 0x0 announces 32 bytes, 28 remain")`.
- `an_initial_goaway_during_a_half_written_frame_follows_it_and_the_ack`: `Err("frame type 0x64 announces 6579300 bytes, 8 remain")`.

Also: `a_ping_…` and `a_settings_during_a_half_written_frame_is_acknowledged_after_it` (red on main), `two_pings_…` and `settings_then_ping_during_one_park_are_acknowledged_after_the_frame`, and the orphan liveness test above. Each doc comment carries its TO SEE THIS RED recipe, all verified.

Local runs on this head, rebased on `f165a3dc`, each with exit 0: build (`--locked --no-default-features --features crypto-ring,opentelemetry,splice,simd`), `cargo +nightly fmt --all -- --check`, clippy `-D warnings`, tests for `sozu-lib` (1203 passed), `sozu` (113), `sozu-command-lib` (184), `sozu-e2e` (449), `sozu-sim`, the four `check_doc_citations.py` modes (`--base f165a3d`), and `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked`.

`doc/h2_mux_internals.md`, `lib/src/protocol/mux/LIFECYCLE.md` and `CHANGELOG.md` are updated; `h2.rs` line citations are moved to the same text.

Signed-off-by: Florentin Dubois <[email protected]>
When a stream was removed (per-stream idle reap, reset) while the
connection was reading a DATA payload into that stream's buffer,
H2StreamTable::remove nulled expect_read and nothing else changed. The
connection stayed in H2State::Frame with nothing to read, and every
later readable() pass returned at the expect_read() == None early exit.
The rest of the payload and every frame behind it went unread until the
connection timeout, stalling every stream on the connection. A stream
parked on buffer pressure and then reaped hit the same state with
READABLE interest removed as well.

remove_dead_stream now hands the unread remainder to
skip_orphaned_data_payload. That function moves the connection to
H2State::Discard with no field block and credits the frame's whole
payload_len to the connection receive window (RFC 9113 section 6.9, as
handle_data_frame does for DATA on a closed stream). It restores
READABLE interest only while zero_holds_output() is false. The
remainder is read and dropped in pieces no larger than the free space
in zero: it is never buffered whole and never answered with a GOAWAY,
the way HAProxy skips a dropped frame's payload.

The skip made a backend fault reachable. end_stream on a
Position::Client connection wrote its RST_STREAM(CANCEL) into zero
without marking zero as holding output or stopping reads. The next
frame header was read in behind it, the backend connection took our RST
for one of the backend's own frames, and it answered
GOAWAY(PROTOCOL_ERROR). The RST now goes through queue_zero_output, the
PING and SETTINGS ACK path from #1600, so it also waits for a
half-written stream frame. When zero holds bytes read from the backend,
the RST goes through enqueue_rst instead.

The read guard and header assertion are the ones #1600 added
(zero_holds_output); this change adds none of its own. They also cover
a stalled WINDOW_UPDATE or RST_STREAM flush, which leaves its unsent
tail in zero under expect_write = Zero with READABLE still on. Slower CI
runners hit that case through the assertion, and a regression test now
pins it.

Tests, each seen red with its part removed: idle reap mid payload
(red on the former main), the parked form reaped through
Mux::timeout, a 16 KiB remainder with 4 KiB buffers, the window credit,
the backend end_stream RST, READABLE held back while zero holds output,
and no header read over a stalled flush tail.

LIFECYCLE.md section 5.4, h2_mux_internals.md and CHANGELOG.md are
updated. Doc citations are re-anchored to the same line text.

Closes #1597

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 27, 2026
…#1605)

Closes #1603

## What changes

**A backend EOF read with its last bytes no longer costs an `epoll_wait` round.** An H1 backend read that returns `(n > 0, Closed)` now records `Ready::HUP` on that read (`ConnectionH1::readable`). The dead-backend check of `Mux::ready_inner` samples HUP at the top of each inner iteration, and the read armed the frontend, so the backend is closed on the pass's next inner iteration, after the bytes read with the EOF were parsed. Before, it waited for the `EPOLLRDHUP` edge the kernel had already queued for the same FIN, and the next `epoll_wait` returned at once only to deliver it. The new order is the one the pass already followed when `EPOLLRDHUP` arrived together with the last bytes (recv data, recv 0, close the backend, then forward to the client).

**No `shutdown(SHUT_WR)` on a socket whose peer has closed.** The four write-side shutdowns of the HTTP/HTTPS close paths (`HttpSession::close`, `HttpsSession::close`, `Mux::close`, the dead-backend sweep) go through `protocol::mux::shutdown_write`, which skips the call when:

- the connection's readiness carries HUP (`Connection::peer_closed`: `EPOLLRDHUP`/`EPOLLHUP`, or the H1 backend EOF read above), or
- on a TLS frontend, a read met the client's EOF or `close_notify` (`FrontRustls::peer_disconnected`), which no epoll event reports when the close follows in the same pass.

A backend sozu drops on its own (`force_disconnect`, `BackendStatus::Disconnecting`) writes HUP into a live backend's readiness, so it is excluded and keeps its shutdown.

## Why skipping the shutdown is safe

None of these descriptors is shared (no `dup`/`try_clone`/fork, see `doc/lifetime_of_a_session.md` §9), so the `close(2)` that follows is the last one. Linux's `tcp_close` then sends the FIN after the queued bytes itself when the receive queue is empty, or a RST when it is not, with or without a prior `shutdown(SHUT_WR)`. A peer that half-closed and is still reading therefore still receives its FIN; the tests check exactly that. What goes away is a syscall that, after an H2 client's `close_notify`, failed with `ENOTCONN` on most connections.

HAProxy draws the same line: `conn_sock_shutw` (`include/haproxy/connection.h`, "don't perform a clean shutdown if we're going to reset or if the shutr was already received") skips `shutdown(SHUT_WR)` once `CO_FL_SOCK_RD_SH` records the read0.

## What deliberately does not change

- **The TLS `close_notify` is kept**, although the issue's first framing considered skipping it once the peer had closed. RFC 8446 §6.1: "Each party MUST send a "close_notify" alert before closing its write side of the connection, unless it has already sent some error alert. This does not have any effect on its read side of the connection." TLS 1.3 only dropped the obligation to answer a `close_notify` *immediately*. HAProxy keeps it too: `h2_release` (`src/mux_h2.c`) and `h1_shutw_conn` (`src/mux_h1.c`) call `conn_xprt_shutw` unconditionally, and only `clean=0` makes `ssl_sock_shutw` quiet. On a reset peer `FrontRustls::socket_write` already short-circuits on `peer_reset`, so the remaining `close_notify` write is exactly the case the RFC requires. The one real `-1 writev` left would be sending GOAWAY and `close_notify` in one `write_tls`, which is `h2.rs` work (out of scope while #1599 is open there).
- **Frontend reads do not record HUP**, unlike the issue's proposal to do it in `update_readiness_after_read`. Over TLS a frontend `Closed` can be a `close_notify` on a TCP stream that is still open (`rustls_socket_read` answers `Closed` as soon as rustls has seen it), which the kernel does not report as read-closed, and a frontend HUP closes the whole session at the top of the next pass. The EOF round this issue measured was on the backend.
- **H2 backends** still close on the `EPOLLRDHUP` edge: the equivalent change belongs in `h2.rs` (left untouched because of #1599).
- Half-close handling is unchanged: a frontend HUP from epoll already closed the session before this change.

## Measurements

Release build, one worker, python `http.server` backend, 20 sequential requests each on its own connection, `LD_PRELOAD` fd tracer and `intentrace -p` (ANSI stripped, anchored on the syscall name), LOAD1 < 8, `f165a3dc` before, this branch after.

| | before | after |
|---|---|---|
| H1 fdtrace `shutdown`/req | 2.00 | 0.05 |
| H1 fdtrace `epoll_wait` rounds delivering an EOF already read | 3 | 0 |
| H1 fdtrace total/req | 23.55 | 21.45 |
| H1 intentrace `shutdown`/req | 2.00 | 0.00 |
| H1 intentrace total/req | 22.80 | 21.00 |
| H2 fdtrace `shutdown`/req | 2.00 (15 `ENOTCONN`) | 1.00 (1 `ENOTCONN`) |
| H2 fdtrace `epoll_wait` rounds delivering an EOF already read | 9 | 0 |
| H2 intentrace `shutdown`/req | 2.00 | 0.00 |
| H2 intentrace total/req | 43.95 | 41.90 |

The EOF round is timing-dependent (12 of 20 H1 requests in the measurement that opened the issue). The H2 fdtrace residual is the frontend shutdown on connections sozu closed on the client's GOAWAY before its `close_notify` arrived: the client is not yet known to have closed, so its shutdown is kept, and it succeeded (`ret=0`) on 19 of 20. The GOAWAY write (`len=39`) is present on all 20 H2 connections after the change.

## Tests (each seen red first)

- `an_h1_backend_eof_read_records_hup_and_a_frontend_one_does_not` (`mod.rs`)
- `a_backend_eof_read_with_its_last_bytes_closes_the_backend_in_the_same_pass` (`mod.rs`): drives a real `Mux::ready` pass; the backend is gone after the pass and the client received the bytes read with the EOF.
- `mux_close_skips_the_backend_shutdown_once_the_backend_closed` / `mux_close_keeps_the_backend_shutdown_while_the_backend_is_there` (`mod.rs`), counting shutdowns through `shutdown_write`; the peer observes the FIN in both, including a `Disconnecting` backend.
- `https_close_skips_the_frontend_shutdown_once_the_client_closed` (both predicates) / `https_close_keeps_the_frontend_shutdown_while_the_client_is_there` (`https.rs`).

Docs: `doc/lifetime_of_a_session.md` §9, `doc/h2_mux_internals.md`, `CHANGELOG.md`; 27 line citations (37 drifted line references, range ends included) re-anchored to the same text in the same function (`check_doc_citations.py --base f165a3d…` clean).

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit b19d94f into main Sep 27, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/h2-readable-resume branch September 27, 2026 01:02
FlorentinDUBOIS added a commit that referenced this pull request Sep 27, 2026
…put queue

`zero` was both the frame-header input buffer and the control-frame
output buffer, and stream frames were written from each stream's own
`kawa.out`, serialised against `zero` only through `expect_write`. When a
partial write parked a stream mid-frame and the stream was then removed
(a peer RST_STREAM, `end_stream`, expiry, `prune_inactive_streams_while_closing`),
the rest of that frame went with it, and the next bytes on the
connection landed inside what the peer still parsed as that frame
(#1604).

The connection now has one ordered output queue, `H2Output`
(`lib/src/protocol/mux/h2_output.rs`). It receives every control frame
and the unsent rest of the one stream frame a partial write cut, each
whole when queued; `zero` is input only. Stream frames stay zero-copy: a
transmit gathers the queue first, then the stream's `kawa.out` as
`IoSlice`s, in the same writev(2) (`h2_transmit::gather_after`). When
the write stops inside a frame, `h2_transmit::frame_tail` reads the
gathered frame headers and measures the rest of that frame, extended to
END_HEADERS for an unfinished header block (RFC 9113 section 6.10), and
`ConnectionH2::handle_write` has the queue adopt it, counted to the
stream at once. A stream therefore only owns frames the wire has not
started, and removing it drops whole unsent frames. The copy is bounded
by one frame or header block and paid only on a partial write, which is
how `h2` owns its in-flight DATA frame (`FramedWrite`'s `Encoder::next`)
and HAProxy every frame in its `mbuf` ring; sozu's stream storage is a
pool buffer with no reference count, so the in-flight rest is copied
rather than referenced. The queue holds 128 bytes inline, so a
connection that never meets backpressure allocates nothing for it.

With the shared buffer gone, so are its one-off defences:
`zero_output_deferred`, `queue_zero_output`/`park_zero_output`, the
`zero_holds_output` read guard and `handle_header_state`'s assertion,
the `ResumeZero` flush stage with its `H2ControlFlushStage` and
`ControlFlushResume` walk, `expect_write = Some(Zero)`, and the
reassembly guards of the WINDOW_UPDATE, RST_STREAM and shutdown flushes.
The control preamble queues its frames behind the queue and flushes it
once; the deferred initial GOAWAY goes out in the pass that queues it;
`flush_zero_buffer` becomes `flush_output_buffer`. Reads no longer stop
while an ACK waits: they stop once one buffer of output is queued, as
HAProxy's demux stops on a full `mbuf`. A backend connection turns
READABLE on itself after its preface, which the old `zero` resume did as
a side effect.

Three new tests reproduce #1604 and fail on a078550 with the peer's own
parse error ("frame type 0x0 announces 65536 bytes, 4 remain", "... 0
remain", "announces 32 bytes, 28 remain"); the #1599 and #1601 tests
keep their intent. Measured on release builds, 20 H2 requests one per
connection and 20 multiplexed: intentrace writev 120 -> 120 and 44 -> 44,
fdtrace writev 123 -> 122..124, mcount mallocs within run-to-run noise.

Docs: doc/h2_mux_internals.md, lib/src/protocol/mux/LIFECYCLE.md
(invariant 28, invariant 24 amended), CHANGELOG.md.

Closes #1604

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 27, 2026
…put queue (#1625)

Closes #1604

## Problem

`zero` was both the frame-header **input** buffer and the control-frame **output** buffer, and stream frames were written from each stream's own `kawa.out`, serialised against `zero` only through `expect_write`. When a partial write parked a stream mid-frame and the stream was then removed (peer RST_STREAM, `end_stream`, expiry, `prune_inactive_streams_while_closing`, any of the `remove_dead_stream` callers), the rest of that frame was dropped, and the next bytes on the connection — a control frame, a GOAWAY, another stream's frame — landed inside what the peer still parsed as that frame.

## Reproduced first (red on `a0785505`, then green)

Three new tests in `lib/src/protocol/mux/h2.rs` parse the wire the way the peer does:

| test | failure on `a0785505` |
|---|---|
| `a_removed_half_written_stream_still_completes_its_frame` (removal, then a PING ACK) | `left: Err("frame type 0x0 announces 65536 bytes, 4 remain")` |
| `a_removed_half_written_stream_does_not_corrupt_the_next_stream_frame` (removal, then another stream's DATA) | `left: Err("frame type 0x0 announces 65536 bytes, 0 remain")` |
| `a_peer_reset_of_a_half_written_stream_still_completes_its_frame` (peer RST_STREAM read while parked) | `left: Err("frame type 0x0 announces 32 bytes, 28 remain")` |

The #1599 and #1601 tests on the edge cases of `zero` (deferred ACK, GOAWAY and initial GOAWAY mid-frame, forced shutdown read, backend `end_stream` RST, orphaned DATA remainders) stayed green on that head and keep their intent here. On this tree, disabling the adoption of the cut frame's rest (`self.output.adopt_tail(kawa, tail)` → `let _ = (kawa, tail);`) reddens the three #1604 tests with the same messages and every #1601 test on the framing invariant's debug assertion.

## Design

One **ordered output queue** per connection, `H2Output` (`lib/src/protocol/mux/h2_output.rs`): every control frame, and the unsent rest of the one stream frame a partial write cut, each **whole** when queued. `zero` is input only.

- **Stream frames stay zero-copy.** A transmit gathers the queue first, then the stream's `kawa.out` blocks as `IoSlice`s into `kawa.storage`, in the same `writev(2)` (`h2_transmit::gather_after`, `ConnectionH2::gather_transmit`).
- **Commit on write.** When the write stops inside a stream frame, `h2_transmit::frame_tail` reads the gathered frame headers and measures the rest of that frame — extended through CONTINUATION up to END_HEADERS for an unfinished header block, since RFC 9113 §6.10 forbids any other frame in between — and `ConnectionH2::handle_write` has the queue adopt it (copied, consumed from the stream, counted to the stream at once). A stream therefore only owns frames the wire has not started; removing it drops whole unsent frames, never half of one.

Why a bounded copy rather than references into `kawa.out` kept alive after removal:

- **HAProxy** owns every committed byte in its `mbuf` ring: control frames are appended with `br_tail` (`h2c_ack_settings`, `h2c_send_ping`, `src/mux_h2.c`), and `h2s_make_data`'s zero-copy path *swaps* the whole stream buffer into the ring, falling back to `goto copy` when the swap cannot apply.
- **h2 (hyperium)** keeps one `FramedWrite` buffer for control frames and frame heads and holds an in-flight DATA payload **by value** in `Encoder::next` until written (`src/codec/framed_write.rs`); `has_capacity()` is false meanwhile. Its payload is a reference-counted `Bytes`, so liveness after the stream goes away is free.
- **Sōzu**'s stream storage is a pool buffer that a removed stream gives back, with no reference count. Keeping references alive would mean deferring the release of every removed stream's buffer (options (a)/(b) of #1604, which touch every removal site and the slot recycling in `Context`). Copying only the in-flight rest keeps the zero-copy path for everything else and bounds the copy to one frame or header block, paid only on a partial write.

The queue holds **128 bytes inline** (a frontend's whole server preface is 79) and spills to the heap only past that, so a connection that never meets backpressure allocates nothing for its output — as the pool buffer `zero` it replaces did not.

### Review fixes (second commit)

- **`frame_tail` is linear in the gathered slices.** It used to rescan from the first slice for every header byte, O(frames × slices), after every transmit; the reviewer measured ~1.9 ms per call for 2700 one-byte DATA frames (an H1 chunked body with tiny chunks). It now walks a forward-only cursor, and the shells call it only when `size < offered`. `the_walk_is_linear_in_the_slices` counts slice steps (≤ 5400 for 5400 slices; the rescan mutation gives 7292700).
- **`H2Output` gives back sent heap bytes while in use.** `consume` only advanced `head`, so a queue that never drained under backpressure kept every sent byte. It now compacts once the sent prefix is past the retained capacity and larger than what is left, and shrinks a capacity over 4× the rest. `a_queue_that_never_drains_stays_bounded` (without it: head 4096000, capacity 4 MiB).
- **Emptying the queue releases the read cap.** `frontend_hung_up_while_draining` cleared the queue but not `reads_wait_for_output`; `ConnectionH2::clear_output` now does both. `clearing_the_output_releases_the_read_cap`.
- Stale `zero` wording in `graceful_goaway` / `send_initial_goaway` fixed.
- **Corrected claim:** dropping a removed stream's unsent frames keeps the *framing* whole, not the HPACK tables — an unsent HEADERS block was already encoded and its insertions stay in the encoder table. `LIFECYCLE.md` invariant 28, `h2_output.rs` and `doc/h2_mux_internals.md` now say so. That desync predates this PR and is **#1627** (reproduced red on `771c9e90`, with a second path in `check_header_capacity`); it is not fixed here.

### Removed mechanisms

`zero_output_deferred`; `queue_zero_output` / `park_zero_output`; the `zero_holds_output` read guard and `handle_header_state`'s assertion; the `ResumeZero` flush stage with `H2ControlFlushStage` and `ControlFlushResume` (the control walk now queues and flushes **once**, `H2ControlFlushTarget::FlushOutput`); `expect_write = Some(Zero)` (only `Other` is ever parked, for scheduling); the reassembly guards of the WINDOW_UPDATE, RST_STREAM and shutdown flushes. `flush_zero_buffer` → `flush_output_buffer`. `expect_write` for `Other` stays: it keeps a parked stream first in line, but no longer carries framing.

### Behaviour changes, deliberately

- **READABLE no longer drops while an ACK waits.** Its only justification was the shared buffer. Reads now stop only once one buffer of output is queued (`output_read_cap`), as HAProxy's demux stops on a full `mbuf` (`H2_CF_DEM_MROOM`); `a_full_output_queue_stops_reading_until_it_drains` pins it.
- **A backend H2 connection turns READABLE on after its preface** in the `(ClientSettings, Client)` arm: the old `ResumeZero` stage did it as a side effect of flushing `zero`, and a client connection starts write-only. Found while removing that stage; `a_backend_connection_reads_once_its_preface_is_out` pins it.
- The deferred initial GOAWAY is sent in the pass that queues it instead of the next one.
- `h2_drain`'s deferral of the initial GOAWAY during header reassembly now protects no buffer; it is kept as drain policy (documented), since removing it changes the drain, not the output.

## Tests

New: the three #1604 tests; `a_cut_header_block_is_completed_before_the_ack` (cut inside HEADERS and exactly on the HEADERS/CONTINUATION boundary); `a_full_output_queue_stops_reading_until_it_drains`; `a_backend_connection_reads_once_its_preface_is_out`; `h2_output` unit tests (order, prepaid accounting, inline→heap spill and back); `h2_transmit` `frame_tail_cases` and `gather_after_offers_the_prefix_first_and_only_when_there_is_one`. Each new or rewritten test's "TO SEE THIS RED" recipe was run and its failure line recorded (2026-09-27).

No test was deleted without a replacement. Rewritten, with the intent kept:

- **Premises that read the old internals** now read the queue: the #1601 fixture's `!is_readable()` premise → `!output.is_empty()` (reads no longer stop); the two stalled-drain tests' and the two liveness tests' `expect_write == Some(Zero)` → queued output; the #1599 orphan tests detected the PING ACK "in `zero`" → in the queue.
- **Fixtures that queued non-frame bytes** as a stream's output (`FIRST_BLOCK`/`SECOND_BLOCK`, the 256 KiB rustls body) now hold real DATA frames of the same lengths: a stream's `kawa.out` only ever holds whole H2 frames, and the write pass now reads their headers. Byte counts and the byte-equality oracle are unchanged.
- `skipping_an_orphaned_payload_keeps_readable_off_while_zero_holds_output` → `skipping_an_orphaned_payload_reads_on_while_output_is_queued`, and `no_frame_header_is_read_while_zero_holds_unflushed_output` → `a_frame_header_read_leaves_queued_output_intact`: both pinned the cure for the shared buffer; the replacements pin the property that replaces it, and the second keeps the original wire assertion (WINDOW_UPDATE, then PING ACK).
- `a_deferred_ack_does_not_strand_reads_when_its_parked_stream_is_removed` asserts the queue drains (the wire is asserted by the new #1604 test it used to say was out of scope).
- `a_legitimate_continuation_survives_a_graceful_goaway` waits on the queue instead of `expect_write`.
- `reassembly_property::qc_h2_header_reassembly_survives_interleaved_control_frame_flushes` sets `TCP_NODELAY` on its loopback peer: the interleaved WINDOW_UPDATE is now really written (it used to be deferred during reassembly), which puts sozu's end in delayed-ACK mode, and the peer's Nagle then held its next small CONTINUATION for up to 40 ms, longer than the yield-bounded read loop waits. Baseline 5/5 green, this tree 0/3 without and 3/3 with.
- `sim/tests/h2_simulation.rs` mirrors the new transmit bracket and control flush.

## Measurements (release, `--no-default-features --features crypto-ring,opentelemetry,splice,simd`)

20 requests, H2 one connection per request (`h2`) and multiplexed on one connection (`h2mux`), 30-byte body, `worker_count = 1`, LOAD1 < 4. Before = `bdc74ecd` (#1620), after = this branch.

| | before | after |
|---|---|---|
| intentrace `h2` writev / total (ANSI stripped, anchored on the syscall name) | 120 / 822 | 120 / 821 |
| intentrace `h2mux` writev / total | 44 / 290 | 44 / 290 |
| fdtrace `h2` writev | 132 | 120 |
| mcount `h2` mallocs / 20 conns, 4 runs | 3601, 3573, 3581, 3560 | 3570, 3578, 3571, 3586 |
| mcount `h2mux` mallocs, 4 runs | 842, 831, 845, 845 | 884, 823, 831, 846 |
| mcount realloc_grow `h2` / `h2mux` | 1181–1214 / 251 | 1202–1217 / 248–251 |

No syscall is added, and allocations are within run-to-run noise; the same held against `a0785505` before #1620 landed. fdtrace `h2mux` writev varies with pacing (44–64 across runs on both trees). A first cut stored the queue in a plain `Vec`, which measured +1.35 malloc and +0.7 realloc per connection. That is why the queue has inline storage.

## Validation (rebased on `0155d40b`, head `16d6aba8`)

Build, `cargo +nightly fmt --check`, clippy `-D warnings` with `crypto-ring,opentelemetry,splice,simd`, `cargo test` for `sozu-lib` (1274), `sozu` and `sozu-command-lib`, `cargo doc -D warnings`, the four `check_doc_citations.py` runs, the sim test and clippy under `--cfg tokio_unstable`: all pass on `16d6aba8`. E2E (`-- --skip tests::fuzz_tests::`): 456 passed, 0 failed, the HPACK e2e tests included. The three #1604 tests still fail without the fix (the `adopt_tail` mutation) on this head, with the same peer parse errors.

H2 e2e, 10 runs, `taskset -c 0 cargo test -p sozu-e2e -- h2 --skip tests::fuzz_tests:: --test-threads=20`. One CPU with 20 threads: without `--test-threads` the pin runs the tests serially, about 5 h per run. The same loop was run on `bdc74ecd`:

| test | this branch | `bdc74ecd` |
|---|---|---|
| `test_h2_continuation_survives_a_graceful_drain_mid_reassembly` (a single GOAWAY, then nothing) | 5 / 10 | 9 / 10 — pre-existing, #1623 |
| `test_h2_settings_ack_timeout_goaways_the_frontend` (client cannot send its preface) | 7 / 10 | 7 / 10 — pre-existing, #1624 |
| `test_h2_large_chunked_7mb_drains_fully` | 1 / 10 | 0 / 10 |
| `test_h1_to_h2_basic_request` | 1 / 10 | 0 / 10 |

`test_h2_large_chunked_7mb_drains_fully` failed once: the client read EOF at 3.13 of 7.76 MB after 1.65 s, with no RST. That is a close, not a stall and not a frame desync; either of those would have left the client reading until its 30 s deadline. No debug assertion or panic from `lib/` appears in any log. I could not reproduce it: `h2_correctness` 5 runs on each tree, pinned to one CPU with 20 threads, 0 failures on both. It is reported here unattributed, not claimed as pre-existing. `test_h1_to_h2_basic_request` failed once in the same way (a stability iteration under load).

## Docs

`doc/h2_mux_internals.md` (new "ordered output queue" section, control preamble, `flush_output_to_socket`), `lib/src/protocol/mux/LIFECYCLE.md` (new invariant 28, invariant 24 and §5 amended), `CHANGELOG.md`; module docs of `h2_drain`, `h2_header_reassembly`, `h2_control_tx`, `h2_close`. Line citations re-anchored on the same text and function.

## Not touched

Rebased on `0155d40b` (#1626, which fixed #1622, on top of #1620 (the in-tree HPACK module), #1617, #1618 and #1621). The only conflict was a line citation in `doc/testing.md`; every addition #1626 made to the shared docs is kept, and `converter.rs`, `hpack_state.rs` and `hpack/` are untouched by this PR. `pkawa.rs`, `converter.rs`, `hpack_state.rs` and the HPACK codec branch in `h2.rs` are untouched.

**Related, tracked separately: #1627** (HPACK table desync when an encoded HEADERS block is dropped unsent, see above). #1622 (smallest table size before the last one) was fixed separately by #1626, which this branch is rebased on.

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.

mux-h2: reaping a stream mid DATA payload nulls expect_read and wedges the connection until timeout

1 participant