Repository navigation
fix(hpack): signal the smallest table size before the last one - #1626
Merged
Merged
Conversation
When a peer sent two SETTINGS_HEADER_TABLE_SIZE changes before Sōzu wrote its next header block, for example 0 then 4096, the block opened with one dynamic table size update carrying the last value only. The encoder had emptied its table at 0; the peer's decoder, told only 4096, kept every entry. RFC 7541 §4.2 requires the smallest size reached, then the final one. The encoder now records both. HpackState::set_encoder_max_table_size calls Encoder::change_max_table_size, which tracks the smallest size set since the last block beside the last one, and the converter opens the block through Encoder::encode_size_updates_into: the smallest size when it is below the last, then the last. The state is two usizes in the encoder, so no allocation is added. ConnectionH2::pending_table_size_update and the write pass are unchanged: they still say whether a signal is owed, and lib/src/protocol/mux/h2.rs is not touched. A single change, or changes that never go below the last value, still produce the one update Sōzu sent before. A rising pair (6000 then 8192) emits both, which is what the smallest-then-final rule prescribes. Tests: three encoder/decoder unit tests (0 then 4096 with dynamic entries and table equality, one update when the size never goes below the last, smallest equal to the last), one test driving HpackState and H2ConverterPass as the H2 connection does, and the e2e test_h2_hpack_table_size_lowered_then_raised, which sends two SETTINGS frames before a request. Closes #1622 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 27, 2026 17:13
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]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 27, 2026
…ropped unsent (#1630) 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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #1622
Problem
When a peer sends two
SETTINGS_HEADER_TABLE_SIZEchanges before Sōzu writes its next header block, for example 0 then 4096, the block opened with one dynamic table size update carrying the last value only. Sōzu's encoder had emptied its table at 0; the peer's decoder, told only 4096, kept every entry. RFC 7541 §4.2 requires the smallest size reached in the interval, then the final size.Fix
The state and the emission live in the HPACK encoder;
lib/src/protocol/mux/h2.rsis not touched.Encoder::change_max_table_size(lib/src/protocol/mux/hpack/encoder.rs) sets the maximum size and records the smallest size set since the last block beside the last one (twousize, no allocation).Encoder::encode_size_updates_intoopens the block with the smallest size when it is below the last, then the last, and forgets the record. It returns 1 or 2, the most a block may open with.HpackState::set_encoder_max_table_sizenow callschange_max_table_size;H2BlockConverter::emit_pending_size_update_if_new_blockemits throughencode_size_updates_into.ConnectionH2::pending_table_size_updateand the write-pass plumbing are unchanged: they still say whether a signal is owed (and still hold the last size), the encoder says what it is. Debug assertions tie the two together.A single change, or changes that never go below the last value, emit the same byte sequence as before. A rising pair (e.g. 6000 then 8192 from 4096) emits both sizes, as the smallest-then-final rule says; nghttp2's deflater does the same (
min_hd_table_bufsize_max,lib/nghttp2_hd.c).Protocol / security impact
nghttp2_hd_inflate_change_table_size/ theNGHTTP2_HD_STATE_READ_TABLE_SIZEstate inlib/nghttp2_hd.c), so 4096 after 0 is a COMPRESSION_ERROR on the connection.Tests added
hpack::tests::a_size_lowered_then_raised_between_blocks_signals_both: encoder + in-tree decoder, dynamic entries, 0 then 4096 between blocks; the block opens with two updates and both tables stay identical.hpack::tests::a_size_never_lowered_below_the_last_signals_it_alone: one change, repeated values, a descending sequence ending at its minimum → one update, bytes identical to before.hpack::tests::a_smallest_size_equal_to_the_last_is_signalled_once: 4096, 0, 64, 0 → one update (0).hpack::tests::the_h2_converter_signals_the_smallest_table_size_first: drivesHpackState+H2ConverterPass+H2BlockConverterwith only the callsConnectionH2makes; uses no new API, so it runs against the unfixed code.test_h2_hpack_table_size_lowered_then_raised: two SETTINGS frames (0, 4096) before a request; the response block opens with both updates, and a second response on the connection carries none and still decodes.Red → green
hpack_state.rsandconverter.rsrestored toorigin/main(test kept):cargo test -p sozu-lib --locked --lib -- hpack::tests::the_h2_converter→FAILED ... the block opens with 0, then 4096: [3f, e1, 1f, 88, 40, ...].cargo test -p sozu-e2e --locked -- h2_hpack_table_size_lowered→stream 1 - opens_with_updates=false opens_with_any_update=true routed=true,test result: FAILED.Encoder::encode_size_updates_into:a_size_lowered_then_raised_between_blocks_signals_bothfails onthe dynamic tables diverged.Commands run (on the pushed commit)
cargo build --locked→ exit 0cargo clippy --all-targets --locked -- -D warnings→ exit 0cargo +nightly fmt --all -- --check→ exit 0cargo test -p sozu-lib --locked→test result: ok. 1252 passed; 0 failedcargo test -p sozu-e2e --locked -- h2_→test result: ok. 240 passed; 0 failedpython3 .github/scripts/check_doc_citations.py --self-test/--root ./--base origin/main/--audit --root .→ exit 0 each (the audit's findings are pre-existingLIFECYCLE.mdline citations unrelated to this diff).The cargo-fuzz targets were not run:
fuzz_hpack_roundtripdrivesEncoder::set_max_table_sizeand writes its own size updates, so it does not exercise the new path.Docs
CHANGELOG.md(Fixed),doc/h2_mux_internals.md(the size-update section),lib/src/protocol/mux/LIFECYCLE.md(one-or-two-update prefix), and three line citations re-pointed afterhpack_state.rs/converter.rsmoved (doc/README.md,doc/testing.md,doc/h2_mux_internals.md).Signed-off-by: Florentin Dubois [email protected]