Skip to content

fix(mux-h2): reset the HPACK encoder table when an encoded block is dropped unsent - #1630

Merged
FlorentinDUBOIS merged 3 commits into
mainfrom
fix/hpack-dropped-block-desync
Sep 27, 2026
Merged

FlorentinDUBOIS merged 3 commits into
mainfrom
fix/hpack-dropped-block-desync

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1627

Problem

The connection's HPACK encoder changes its dynamic table when a block is encoded (kawa.prepare), not when it reaches the wire. Two paths dropped an encoded block unsent:

  1. A stream parked by socket backpressure with an encoded HEADERS/CONTINUATION (or trailers) block in its kawa.out is removed (peer RST_STREAM, expiry, end_stream, prune_inactive_streams_while_closing), or keeps its park while forcefully_terminate_answer / a default answer clears that queue.
  2. H2BlockConverter::check_header_capacity clears a block that outgrew MAX_HEADER_LIST_SIZE after its first fields were inserted and its pending size update was taken; H2WritePhase::End then also dropped the connection's size-update signal because the pass reported it emitted.
  3. (found by the adversarial review of this PR) H1 trailers split across two reads: kawa queues one Block::Header per trailer line and the closing Flags { end_header } only with the final CRLF, while ParsingPhase::Trailers is a main phase, so a write pass between the two reads encoded the first trailer lines and H2BlockConverter::finalize dropped them unfinished — trailers lost and the table shifted.

Impact (protocol / security)

Proven, and worse than a decode error. Dynamic entries are numbered from the newest (RFC 7541 §2.3.3), so each insertion the peer missed shifts every older entry one index down in the encoder's table only. The stale entries do stay at the tail, but a later block naming an older entry is read by the peer as another field, silently: hpack::tests::a_dropped_block_substitutes_fields_until_the_table_is_reset encodes x-c: 3 and the peer decodes x-a: 1; a literal naming x-c is read under the name x-a. Naming a newer entry fails with an invalid index / COMPRESSION_ERROR (the issue's repro). On an H2 backend connection the streams of several clients share one encoder, so a substituted field can come from another client's request. CHANGELOG entry under Security.

Fix

RFC 7541 §4.2: "This mechanism can be used to completely clear entries from the dynamic table by setting a maximum size of 0, which can subsequently be restored."

  • Encoder::reset_table empties the encoder table and records the updates 0, then the max size; the next block opens with both, so the peer empties its table too.
  • Only the stream parked in expect_write can hold unsent frames (a pass flushes each prepared stream before the next and stops at the first stall). Where a pass parks a stream, ConnectionH2::parked_header_block = h2_transmit::holds_header_frame(kawa) (frame-header walk, only on a park, no allocation). The next H2WritePhase::Start resets the table when the park is gone or its kawa.out is empty, before anything else is encoded.
  • check_header_capacity resets the table itself and re-arms the converter's pending signal; H2WritePhase::End now takes the pass's remaining signal (H2ConverterPass::pending_table_size_update) instead of clearing it on size_update_emitted.
  • A field block is encoded only once its closing Flags { end_header } is queued (header_block_is_queued_whole): the converter puts the first field back and ends the prepare; the H1 read that completes the trailers re-arms the writer (the Linked arm of ConnectionH1::readable), so the trailers go out whole.
  • Defense in depth: every converter path that still drops encoded bytes (check_header_capacity, the StatusLine::Unknown abort, finalize) goes through H2BlockConverter::discard_encoded_block, which resets the table and re-arms the signal. The Unknown arm is not reachable from the known producers (the H1 parser, pkawa and the default answers set the status line before pushing its block, and StatusLine::pop never leaves Unknown); it is covered through finalize.

No frame is sent for the dead stream; the cost is the dynamic entries the next blocks would have reused, once per dropped block. Nominal path: one bool test per pass, no allocation.

Two size updates at the start of a block are what #1626 already emits; the in-tree decoder refuses only a third (TooManySizeUpdates), and hyperium/h2's Decoder::decode (src/hpack/decoder.rs) accepts size updates until the first field (can_resize).

Alternatives considered: adopting the unsent HEADERS into H2Output does not cover path 2, delivers field blocks for streams already reset (possibly after a queued RST), and needs HEADERS split from DATA in kawa.out. Encoding at send time (hyperium/h2 encodes in FramedWrite::buffer and drops a reset stream's queue in Prioritize::clear_queue; HAProxy's hpack_encode_header never names a dynamic entry) would move encoding out of kawa.prepare, a broad refactor of the converter and the zero-copy output queue.

Tests (red -> green)

  • h2::tests::a_header_block_dropped_with_its_stream_keeps_the_peer_table_in_sync: red on 58550dd4 with left: [(3, false)], right: [(3, true)]

  • h2::tests::a_header_block_cleared_from_a_parked_stream_keeps_the_peer_table_in_sync: red with the park-still-in-place check disabled, same assertion

  • converter::tests::an_oversized_block_dropped_after_encoding_keeps_the_peer_table_in_sync: red without the reset, left: Err(InvalidIndex)

  • hpack::tests::a_dropped_block_substitutes_fields_until_the_table_is_reset: substitution proof, then the reset (zero allocation)

  • h2_transmit::tests::holds_header_frame_finds_a_block_behind_other_frames: every store split, zero allocation

  • fuzz_hpack_roundtrip: new drop-and-reset operation (control bit 0x40 without 0x80)

  • converter::tests::h1_trailers_split_across_reads_are_encoded_whole (real H1 parser + real converter + one peer decoder): red on fedb4304 — trailer never reaches the peer, next block fails to decode; red with the deferral disabled — trailer lost

  • h2::tests::a_header_block_parked_across_two_stalled_passes_keeps_the_peer_table_in_sync: red without the Resume-stall parked_header_block assignment, left: [(3, false)], right: [(3, true)]

  • h2::tests::an_oversized_block_reset_outlives_the_pass_that_dropped_it (connection level, block past MAX_HEADER_LIST_SIZE): red with the pre-image End arm, left: None, right: Some(4096)

  • converter::tests::an_unknown_status_line_keeps_the_size_update_signal and test_converter_finalize_clears_remaining_buffer: red when finalize clears out without the reset, left: None

  • h2::tests::a_chunked_response_closed_inside_its_trailers_ends_with_a_reset (real H1 parser + ConnectionH2::end_stream, liveness regression found by the re-review): red on d12c3299 — stream 1 stuck open, frames [(1, 0), (0, 0)]; red without the chunked CloseDelimited arm — silent END_STREAM [(1, 0), (0, 0), (0, 1)]; also checks the next response decodes on the peer

  • converter::tests::a_field_block_cut_short_never_stalls_its_stream: red when a block cut short is deferred, left: [], right: [(0, 1)]

Liveness: a deferred field block always ends. CloseDelimited on a chunked body ends with RST_STREAM (as ConnectionH1::terminate_close_delimited, RFC 9112 §7.1) and drops its unencoded blocks; a block the next queued flags do not close is dropped unencoded. A frame-header serialisation failure after encoding (unreachable: 9-byte buffer, length < 2^24) resets the table too (header_frame_failed, debug-asserted).

Converter unit tests that call H2BlockConverter::call directly now queue the closing flags first (queue_header_end), as every producer does before a write pass; their assertions are unchanged.

Out of scope, tracked separately: a request encoded for an H2 backend but not yet sent keeps stale frames when re-linked to a fresh backend (#1632); RST_STREAM on a backend stream still idle (#1631).

Commands

  • cargo build --locked -> exit 0; cargo build --all-features --locked -> exit 0
  • cargo clippy --all-targets --locked -- -D warnings -> exit 0
  • cargo +nightly fmt --all -- --check -> exit 0
  • cargo test -p sozu-lib --locked -> test result: ok. 1285 passed; 0 failed
  • cargo test -p sozu-e2e --locked -- h2_ --skip tests::fuzz_tests:: --test-threads=8 -> test result: ok. 240 passed; 0 failed
  • pinned toolchain 1.93.1: cargo test -p sozu-e2e -p sozu-lib --lib -> 460 passed and 1283 passed
  • RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked -> h2_simulation 13 passed, 31 passed in total, 0 failed
  • python3 .github/scripts/check_doc_citations.py --self-test, --root ., --base origin/main, --audit --root . -> all exit 0 (citations shifted by this change re-anchored)
  • cargo +nightly fuzz run fuzz_hpack_roundtrip -- -max_total_time=120 -> Done 888988 runs in 121 second(s) then Done 240720 runs in 121 second(s) (loaded host), no crash; the converter change is not reached by this target (it drives the codec only)

Local toolchain was rustc 1.98.1 (environment override of the pinned 1.93.1); no newer language feature is used.

Docs

LIFECYCLE.md §5.1 and invariants 25/28, doc/h2_mux_internals.md (new "A dropped header block resets both tables"), h2_output.rs module doc, fuzz/README.md, CHANGELOG (Security + Fixed).

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

…ropped unsent

The connection's HPACK encoder changes its dynamic table when a block is
encoded in `kawa.prepare`, not when the block reaches the wire. Two paths
dropped an encoded block without sending it, and the peer's decoder table
fell behind the encoder's (#1627):

- a stream parked by socket backpressure with an encoded HEADERS,
  CONTINUATION or trailers block still in its `kawa.out` was removed (peer
  RST_STREAM, expiry, `end_stream`, `prune_inactive_streams_while_closing`),
  or kept its park while `forcefully_terminate_answer` or a default answer
  cleared that queue;
- `H2BlockConverter::check_header_capacity` cleared a block that outgrew
  `MAX_HEADER_LIST_SIZE` after its first fields were inserted and its
  pending size update was taken, and `H2WritePhase::End` then dropped the
  connection's signal because the pass reported it as emitted.

The desync is not limited to decoding errors. Dynamic entries are numbered
from the newest (RFC 7541 §2.3.3), so every insertion the peer missed moves
the older entries one index down in the encoder's table only. A later block
naming an older entry is decoded by the peer as another field, with no
error: `hpack::tests::a_dropped_block_substitutes_fields_until_the_table_is_reset`
encodes `x-c: 3` and the peer reads `x-a: 1`, and a literal naming `x-c`
is read under the name `x-a`. On a backend connection the streams of
several clients share one encoder.

The fix uses the reset RFC 7541 §4.2 provides ("setting a maximum size of
0, which can subsequently be restored"). `Encoder::reset_table` empties the
encoder's table and records the size updates 0, then the maximum size, and
the next header block opens with both, which empties the peer's table too.
It is sound because only the stream parked in `expect_write` can hold
unsent frames and nothing is encoded before the next pass starts:

- where a pass parks a stream, `ConnectionH2::parked_header_block` records
  whether its `kawa.out` still holds a field block
  (`h2_transmit::holds_header_frame`, a frame-header walk that runs only on
  a park and allocates nothing); the next `H2WritePhase::Start` resets the
  table when the park is gone or its queue is empty;
- `check_header_capacity` resets the table itself and re-arms the
  converter's pending signal, and `H2WritePhase::End` now takes the pass's
  remaining signal back as the connection's instead of clearing it
  whenever an earlier block carried the old one.

Nothing is sent for the dead stream. The cost is the dynamic entries the
next blocks would have reused, once per dropped block. Adopting the
unsent HEADERS into the output queue would not cover the oversized-block
path and would deliver field blocks for streams already reset; encoding at
send time, as hyperium/h2 `FramedWrite::buffer` does, would move encoding
out of `kawa.prepare`, which the converter and the zero-copy output queue
are built around.

Tests, each seen red before the fix:
- `a_header_block_dropped_with_its_stream_keeps_the_peer_table_in_sync` and
  `a_header_block_cleared_from_a_parked_stream_keeps_the_peer_table_in_sync`
  (h2.rs): the peer failed to decode the next stream's block,
  `left: [(3, false)], right: [(3, true)]`;
- `an_oversized_block_dropped_after_encoding_keeps_the_peer_table_in_sync`
  (converter.rs): `left: Err(InvalidIndex)`.
Also `a_dropped_block_substitutes_fields_until_the_table_is_reset`
(hpack/tests.rs), `holds_header_frame_finds_a_block_behind_other_frames`
(h2_transmit.rs), and a drop-and-reset operation in the
`fuzz_hpack_roundtrip` script.

LIFECYCLE.md invariants 25 and 28, §5.1, doc/h2_mux_internals.md,
h2_output.rs, fuzz/README.md and CHANGELOG.md are updated; line citations
shifted by this change are re-anchored.

Closes #1627

Signed-off-by: Florentin Dubois <[email protected]>
The adversarial review of the #1627 fix found a third path that dropped an
encoded field block. kawa's H1 parser queues one `Block::Header` per trailer
line as it reads it, and the closing `Flags { end_header }` only with the
final CRLF. `ParsingPhase::Trailers` counts as a main phase, so a write pass
between the two reads encoded the first trailer lines, inserting them in
the encoder's table, and `H2BlockConverter::finalize` then cleared the
unfinished block. The trailers were lost, and the next block naming them
sent an index the peer never had. On a backend connection shared by
several clients, that is the same substitution #1627 describes.

`H2BlockConverter::call` now encodes a field block only once its closing
flags are queued (`header_block_is_queued_whole`). Otherwise it puts the
first field back and ends the prepare. The backend read that completes the
trailers wakes the writer through the H1 `Linked` arm, and the trailers go
out whole.

Every converter path that still drops encoded bytes goes through
`H2BlockConverter::discard_encoded_block`: `check_header_capacity`, the
`StatusLine::Unknown` abort, and `finalize` clearing an unfinished block.
That function resets the encoder's table and re-arms the pass's signal. No
producer queues a `StatusLine` block over an `Unknown` status line, since
`StatusLine::pop` leaves an empty `Request`/`Response`. The rule still
keeps its size update.

The converter unit tests that call `H2BlockConverter::call` directly now
queue the closing flags first, as every producer does before a write pass.
Their assertions are unchanged.

Tests, each seen red under the mutation it targets:
- `h1_trailers_split_across_reads_are_encoded_whole`: real H1 parser, real
  converter, one peer decoder. Red on fedb430: the trailer never reaches
  the peer and the next block fails to decode.
- `a_header_block_parked_across_two_stalled_passes_keeps_the_peer_table_in_sync`:
  red without the `parked_header_block` assignment in the Resume stall,
  `left: [(3, false)], right: [(3, true)]`.
- `an_oversized_block_reset_outlives_the_pass_that_dropped_it`
  (connection-level, a field block past `MAX_HEADER_LIST_SIZE`): red with
  the pre-image `End` arm, `left: None, right: Some(4096)`.
- `an_unknown_status_line_keeps_the_size_update_signal` and
  `test_converter_finalize_clears_remaining_buffer`: red when `finalize`
  clears `out` without the reset, `left: None`.

A request encoded for an H2 backend but not yet sent, then re-linked to a
fresh backend after a close or GOAWAY, keeps stale frames. That is a
separate retry issue, #1632.

LIFECYCLE.md invariant 28, doc/h2_mux_internals.md and CHANGELOG.md are
updated; line citations shifted by this change are re-anchored.

Refs #1627

Signed-off-by: Florentin Dubois <[email protected]>
Deferring a field block until its closing flags are queued (the fix for
H1 trailers split across reads) could stall a stream forever. When an
H1 backend closed a chunked `Connection: close` response inside its
trailers, `ConnectionH2::end_stream`'s `EndStreamAction::CloseDelimited`
arm queued `Flags { end_header: false, end_stream: true }` behind the
unfinished trailer. The converter never saw a closing `end_header`, put
the trailer back on every pass, and the stream never ended. It kept its
slot and sent neither END_STREAM nor RST_STREAM.

Two changes make waiting always end:

- `CloseDelimited` on a chunked body now ends the response with
  RST_STREAM, the way `ConnectionH1::terminate_close_delimited` already
  does. A chunked body closed before `0\r\n\r\n`, trailers included, is
  truncated (RFC 9112 §7.1). Its blocks that were not yet encoded,
  among them the unfinished trailer, are dropped without touching the
  HPACK table.
- `header_block_closing` tells a block still arriving (no flags queued)
  from one cut short (the next flags do not close it). A block cut short
  is dropped unencoded instead of being waited on, so no producer can
  stall a stream this way.

A HEADERS or CONTINUATION frame header that fails to serialise after its
block was encoded now resets the encoder's table too
(`H2BlockConverter::header_frame_failed`). It cannot fail: the buffer is
9 bytes and every length is below 2^24. It is asserted in debug builds
and safe in release.

Tests:
- `a_chunked_response_closed_inside_its_trailers_ends_with_a_reset`
  (h2.rs) uses the real H1 parser and `ConnectionH2::end_stream`. It was
  red on d12c329: stream 1 stayed open with frames `[(1, 0), (0, 0)]`.
  It is red again without the chunked `CloseDelimited` arm, because the
  truncated body ends with a silent END_STREAM. The same test checks
  that the next response decodes on the peer.
- `a_field_block_cut_short_never_stalls_its_stream` (converter.rs) is
  red when a block cut short is deferred: `left: [], right: [(0, 1)]`.

LIFECYCLE.md invariant 28, doc/h2_mux_internals.md and CHANGELOG.md are
updated. Line citations shifted by this change are re-anchored.

Refs #1627

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit d516191 into main Sep 27, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/hpack-dropped-block-desync branch September 27, 2026 23:20
FlorentinDUBOIS added a commit that referenced this pull request Sep 28, 2026
## Problem

The access log's `client_rtt` and `server_rtt` each cost one `getsockopt(TCP_INFO)` per request. The H1 log sites (`H1::Complete`, `H1::Upgrade`, `H1::EarlyHint`) and `Endpoint::peer_rtt` read their socket at every line, and `Mux::expire_client_rtt` forgot the H2 frontend sample at every pass (#1598 made the read lazy, not rarer). On an H1 keep-alive connection that was 2.00 of the worker's 11.55 syscalls per request.

## Change

Operator decision: accept one sample per connection.

- `memoized_rtt` (`lib/src/protocol/mux/mod.rs`) keeps a connection's first sample in a `Cell<Option<Option<Duration>>>` on the connection (`ConnectionH1::rtt`, new field; `H2Shell::local_rtt`, existing field) and answers every later request from it. `Connection::rtt` dispatches H1/H2.
- Every mux RTT read goes through it: the three H1 log sites, `EndpointServer::peer_rtt`, `EndpointClient::peer_rtt`, `ShellEndpoint::local_rtt` and `Mux::close`. A backend connection keeps its sample across keep-alive pool reuse, since the `Connection` carries it.
- `Mux::expire_client_rtt` and `H2Shell::expire_local_rtt` are removed.
- Pipe (TCP/WebSocket) and the TCP frontend already log once per session and are unchanged. After a WebSocket upgrade, `Pipe::log_request` still reads `socket_rtt` once, at the end of the session. That is one read per session, left out of scope.

No syscall added anywhere, no allocation added (one `Cell` of 16 bytes per `ConnectionH1`), no I/O path touched.

## Sampling point, and why

Hypothesis tested: "`tcpi_rtt` is 0 before the first data ACK". **Refuted** on Linux 7.2.7, loopback. A Python probe reading `TCP_INFO` (`tcpi_rtt`, `tcpi_rttvar`):

- straight out of `accept`: 34 / 27 / 29 µs over three trials. This is the SYN/SYN-ACK measurement.
- straight out of a blocking `connect`: 80 / 30 / 33 µs.
- after 1st/2nd/3rd request on the same connection: 34 → 33 → 1301 µs. The SRTT keeps drifting.

So a sample at `accept` would be valid. The chosen point is still **the connection's first access log**:
- frontend: the first request completed on the connection;
- backend: the first response logged through it.

The lazy read is free on a connection that never logs. A backend dial is still in flight when its non-blocking `connect(2)` returns. Semantics, now documented: **"RTT sampled at the connection's first request"**, repeated on every line of that connection. The value is frozen and no longer follows the kernel's SRTT. The two cells of one line come from two different instants.

## Measurement

`intentrace -p` on the worker. Release build `--no-default-features --features jemallocator,crypto-aws-lc-rs`, one worker, python `http.server` backend on loopback, `curl`, 20 requests on one client connection (plus warmup). Base `58550dd4`, runs interleaved base/after, two runs per cell, 1-minute load average 21–48 (shared host):

| scenario | syscalls/req before | after | `getsockopt`/req before | after |
|---|---|---|---|---|
| H1 keep-alive, plaintext | 11.55, 11.55 | 9.65, 9.65 | 2.00 | 0.10 |
| H1 keep-alive, TLS | 11.85, 11.85 | 9.95, 9.95 | 2.00 | 0.10 |
| H2, 20 streams multiplexed on 1 connection | 12.35, 12.20 | 11.35, 11.30 | 2.00 | 1.05 |

- **H1: −1.90 syscalls/req.** The remaining 0.10 is the two per-connection reads, one per side.
- **H2 multiplexed: −1.00.** Sozu dials one backend H1 connection per concurrent stream (20 `connect`s in the window), so the 20 backend reads remain, one per connection. Only the 19 repeated frontend reads disappear.
- **Access logs, after:** every one of the 27 lines per run carries both `client_rtt` and `server_rtt`, with no `-` cell. There are 4 distinct (client, server) pairs, one per client connection (readiness probe, two warmups, the measured one). Before: 27 distinct pairs.

## Tests

Seen red on `58550dd4` before the fix, green after:

- `keep_alive_requests_read_tcp_info_once_per_connection` (`h1.rs`, new). It drives 20 keep-alive requests through the real `H1::Complete` site of `ConnectionH1::writable`, with the backend recycled by `end_stream`/`start_stream` as a `Mux` does. It asserts two things:
  - 2 `TCP_INFO` reads in total. Red: `left: 40, right: 2`.
  - Both RTT cells are present on all 20 access lines, with identical values.
- `a_mux_pass_keeps_the_connection_sample_and_reads_none_without_a_log` (`mod.rs`). This rewrites `a_mux_pass_forgets_the_previous_sample_and_reads_none_without_a_log`. Red: `left: None, right: Some(Some(4321s))`.

Also rewritten: `snapshot_rtts_samples_the_frontend_once_per_pass` became `snapshot_rtts_samples_the_frontend_once_per_connection` (`h2.rs`). Its documented red (the memo hit removed from `memoized_rtt`) was checked: `left: 2, right: 1`. The old names are forwarded in `check_doc_citations.py` `RENAMED_TESTS`, because the CHANGELOG cites them.

## Docs

- `doc/configure.md` "When each cell is measured": **Changed** RTT semantics in access logs.
- `doc/observability.md`.
- `doc/h2_mux_internals.md`: new "One sample per connection" section, with the measurements.
- `lib/src/protocol/mux/LIFECYCLE.md`.
- `CHANGELOG.md` (Changed).

My line shifts in `h1.rs`, `h2.rs` and `mod.rs` moved 27 `file.rs:NNN` citations and three pinned blocks. They are re-anchored mechanically from a line diff, in both `LIFECYCLE.md`, `doc/testing.md` and `doc/h2_mux_internals.md`, and `--base origin/main` confirms every cited line's text is unchanged.

## Conflicts with open PRs

- `git merge-tree` against #1628 and #1629: clean. The new test uses `"test-cluster".into()`, so it compiles with #1629's `ClusterId` too.
- Against #1630: three pinned `h2.rs:NNNN` fence numbers in `doc/h2_mux_internals.md` / `LIFECYCLE.md` conflict, numbers only. Whichever PR merges second re-anchors them.
- `kawa_h1/editor.rs` and `HttpContext` are untouched.

## Commands run

- `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 +nightly fmt --all -- --check`
- `check_doc_citations.py` (tree, `--base origin/main`, `--self-test`, broken-fixture `--root` exit 1 with its failure report)
- `cargo test --workspace --locked -- --skip tests::fuzz_tests:: --test-threads=8`: 2160 passed, 0 failed.

Results:

- The full battery passed on the pre-amend tree.
- The final amend changed only a test literal (`to_owned()` → `into()`). After it I re-ran fmt, both clippy cells, the citation runs and the new test.
- A first battery run had one failure: `tests::tests::test_async` (client1 99/100 responses) under `--test-threads=8` at load average 40+. I ran it 3 times in isolation on this branch and 3 times on `58550dd4`: 6/6 green. The second full battery run was green.

Protocol/security impact: none. No framing, parsing, readiness or I/O change. The only change is when an access-log value is read.

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

## Problem

A `Connection: close` H1 backend that closes before its announced `Content-Length` had its body ended as if complete (#1633):

- H2 frontend: truncated DATA followed by a clean END_STREAM under `content-length: 10`. RFC 9113 §8.1.1 makes that response malformed.
- H1 frontend: the short body, `H1::Complete` in the access log, and the client connection kept alive. The client waits for bytes that never come, and a pipelined response would land where the client still expects the missing body.

`ConnectionH1::terminate_close_delimited` only treated `BodySize::Chunked` as truncated. The `EndStreamAction::CloseDelimited` arm of `ConnectionH2::end_stream` had the same shape (#1630 guarded chunked only).

Writing the red tests exposed a second defect, which also breaks the existing chunked fix whenever the backend says `Connection: close`. Once the back kawa is in `Error`, the backend's HUP reaches `end_stream_decision`. `Error` is not a main phase, so it answered `SendDefault(502)`, and `set_default_answer` wrote a 502 **behind the bytes already sent**:

- H1: `HTTP/1.1 200 OK … 4\r\nabcd\r\nHTTP/1.1 502 Bad Gateway …` on one connection, with the 502 inside the 200's body.
- H2: HEADERS 200, then the 502 page sent as DATA with END_STREAM on the same stream (`body_bytes=1454 end_stream=true rst=false`).

`test_h2_chunked_backend_crash_mid_stream_rsts` does not see this because its backend is keep-alive and never reaches `terminate_close_delimited`.

## Fix

- **`ConnectionH1::terminate_close_delimited`** (`lib/src/protocol/mux/h1.rs`): any body other than `BodySize::Empty` that is still in its body phase at the EOF is truncated (RFC 9112 §6.3 rule 5, §7.1). It gets the same `warn!`, the same `h1.backend_eof_before_message_complete` metric and the same `Error` phase as the chunked case. Only a body with neither framing ends cleanly at the close (rule 8).
- **`ConnectionH2::end_stream`, `CloseDelimited` arm** (`lib/src/protocol/mux/h2.rs`): the guard goes from `== Chunked` to `!= Empty`, with the same RST_STREAM, metric and `warn!`. This covers the socket-error and backend-timeout path.
- **`end_stream_decision`** (`lib/src/protocol/mux/shared.rs`): a back kawa in `Error` whose `consumed` is set (`Kawa::consume`, called by the H1 write path and the H2 converter) now gets `ForwardUnterminated`: RST_STREAM(INTERNAL_ERROR) on H2. If nothing of the response has left yet, the clean 502 still stands.
- **`ConnectionH1::writable`**: once a response in `Error` has been flushed, the H1 frontend closes (`defer_close_for_tls_flush`, so write-only shutdown and TLS close_notify). It is never kept alive. The client sees a close before `Content-Length`, which is the RFC 9112 §6.3 signal for an incomplete message, and no pipelined response can follow. `Mux::close` logs the stream as an error. This also fixes a keep-alive backend dying mid-body: before, the H1 client hung until the frontend timeout (`test_h1_keep_alive_backend_dying_mid_body_closes_client`, red without this hunk).

No allocation is added. The new `debug_assert!`s cover internal kawa invariants only: body phase on entry, `expects > 0` for a `Length` body still in its body phase, and an errored response that is not also terminated. None of them asserts on network input.

## Red → green

Every test below failed on `d5161919` (unmodified production code) and passes on this branch.

| Test | Red on `d5161919` |
|---|---|
| `h1::tests::only_a_close_delimited_body_ends_cleanly_at_the_backend_eof` | `a truncated Length(10) body must end in Error, got Terminated` |
| `shared::tests::an_errored_response_already_handed_to_the_client_is_not_replaced` | `left: SendDefault(502) right: ForwardUnterminated` |
| `h2::tests::a_content_length_response_cut_short_ends_with_a_reset` | `stream 1 must end with RST_STREAM, frames [(1, 0), (0, 0), (0, 1)]` |
| e2e `test_h2_content_length_truncated_by_backend_close_rsts` | `FAIL H2-CL-TRUNC: body_bytes=4, end_stream=true, rst=false` |
| e2e `test_h2_content_length_truncated_after_forwarded_head_rsts` | `FAIL H2-CL-TRUNC-SPLIT: body_bytes=4, end_stream=true, rst=false` |
| e2e `test_h2_chunked_truncated_by_closing_backend_rsts` | `FAIL H2-CHUNKED-TRUNC: body_bytes=1454, end_stream=true, rst=false` (the 502 page as DATA) |
| e2e `test_h1_content_length_truncated_by_backend_close_closes_client` | `the client connection was not closed: still open after 5s, read so far: "HTTP/1.1 200 OK … Content-Length: 10 … abcd"` |
| e2e `test_h1_content_length_truncated_after_forwarded_head_closes_client` | same, still open after 5s |
| e2e `test_h1_chunked_truncated_by_backend_close_closes_client` | `4\r\nabcd\r\nHTTP/1.1 502 Bad Gateway …` inside the 200 body |
| e2e `test_h1_keep_alive_backend_dying_mid_body_closes_client` | fails with only the `ConnectionH1::writable` hunk reverted |

Non-regression, green before and after:

- `test_h2_content_length_complete_then_backend_close_ends_stream` and `test_h1_content_length_complete_then_backend_close_stays_alive`: a whole 10-byte body followed by EOF ends cleanly. On H1 the same connection then serves a second request.
- `test_h2_close_delimited_body_ends_stream_at_backend_close` and `test_h1_close_delimited_body_ends_at_backend_close`: a body with no `Content-Length` ends cleanly at the EOF.
- `test_h2_chunked_backend_crash_mid_stream_rsts` and `test_h2_close_delimited_large_response`: unchanged.

The H1 truncation tests also check that `http.active_requests` goes back to 0 after the close.

## Protocol / security impact

- **Behaviour change:** a response that fails after some of it already reached the client is no longer followed by a default answer. This also applies to a backend parse error in the middle of a body. H2 clients get RST_STREAM(INTERNAL_ERROR). H1 clients get a connection close.
- **H1 pipelining:** after a truncated response, the pipelined requests behind it are no longer answered on that connection. The client must retry them on a new connection, which is RFC 9112 §9.3.2 behaviour after a close.
- **Unchanged:** close-delimited bodies and complete bodies behave as before.

## Neighbouring defect, not fixed here

After a close-delimited body (no `Content-Length`, no chunked), sozu forwards the backend's `Connection: close` to a keep-alive H1 client but does not close the client connection, so the client cannot find the end of the body until the frontend timeout. `test_h1_close_delimited_body_ends_at_backend_close` reads until the body arrives rather than until EOF, so it does not pin this.

The obvious fix, clearing `keep_alive_frontend`, would also close the whole H2 connection (the `close_frontend` check in `ConnectionH2`'s write pass), so it needs its own change and its own issue.

## Parallel work

The `h2.rs` production diff is limited to the `CloseDelimited` arm of `ConnectionH2::end_stream` (guard, comment, `warn!` argument, `debug_assert!` message), and the line count is unchanged so doc citations do not move. The other `h2.rs` changes are one new unit test and one doc-comment line in the existing chunked test. `ConnectionH2::start_stream` and the rest of `end_stream` are untouched. That keeps the overlap with `fix/h2-backend-stream-lifecycle` (#1631/#1632) to one arm.

## Docs

- `lib/src/protocol/mux/LIFECYCLE.md` §8.4: new "backend close before the end of the response" paragraph. The drifted `h1.rs:NNN` citations are replaced by symbols.
- `lib/src/protocol/kawa_h1/LIFECYCLE.md`: `on_response_headers` / `keep_alive_backend`, and `set_default_answer`'s new boundary.
- `doc/h2_mux_internals.md`: the close-delimited arm now also covers `Content-Length`.
- `doc/configure.md`: the `h1.backend_eof_before_message_complete` row names the real emission sites (the old `mux/h1.rs::back_readable` symbol no longer exists) and the H1 behaviour.
- `CHANGELOG.md`: new Fixed entry.

HAProxy and hyperium/h2 sources were not re-read for this change. The fix rests on RFC 9112 §6.3/§7.1 and RFC 9113 §8.1.1.

## Commands run

The red proofs above were taken on `d5161919`. The commands below ran on the pushed commit, rebased on `3a79685e`:

- `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 (`sozu-lib` 1292 passed, `sozu-e2e` 467 passed, 0 failed)
- `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` → exit 0
- `check_doc_citations.py --self-test` → exit 0
- `check_doc_citations.py --root .github/scripts/testdata/citations` → exit 1 with its `do not resolve` report, as expected
- `check_doc_citations.py --base origin/main` → exit 0
- `check_doc_citations.py` → exit 0
- the 11 new e2e tests (`cargo test -p sozu-e2e -- backend_close backend_rsts closing_backend forwarded_head dying_mid_body`), 5 consecutive runs → 11 passed each time

Closes #1633

Signed-off-by: Florentin Dubois <[email protected]>
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 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: HPACK encoder table diverges when an encoded HEADERS block is dropped unsent

1 participant