Repository navigation
fix(mux-h2): send every committed frame whole through one ordered output queue - #1625
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 27, 2026 16:48
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 27, 2026
…utput queue Review of #1625. `h2_transmit::frame_tail` rescanned the gathered slices from the first one for every byte of every frame header, so its cost was the number of frames times the number of slices, and it ran after every transmit. A queue of 2700 one-byte DATA frames (an H1 chunked body with tiny chunks) took about 1.9 ms per call. It now reads frame headers through a forward-only cursor, linear in the slices, and the shells call it only when the write took less than it was offered. `H2Output::consume` only advanced `head`, so a queue that never drains to empty under steady backpressure kept every sent byte on its heap. It now moves the queued bytes to the front once the sent prefix is past the retained capacity and larger than what is left, and shrinks a capacity more than four times the rest. Emptying the queue (a peer that hung up while the connection drains) did not clear `reads_wait_for_output`, so the read cap could keep READABLE withdrawn with nothing left to wait for. Both emptying paths now release it. The `graceful_goaway` and `send_initial_goaway` comments still spoke of `zero`. `LIFECYCLE.md` invariant 28, `h2_output.rs` and `doc/h2_mux_internals.md` claimed that dropping a removed stream's unsent frames is invisible to the peer. That holds for framing but not for an already-encoded header block, whose HPACK insertions stay in the encoder table (#1627, older than the queue). Tests: the walk steps past each slice at most once for 2700 frames; a queue that never drains stays bounded; clearing the queue releases the read cap. Each reddens under the mutation its comment names. Signed-off-by: Florentin Dubois <[email protected]>
…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]>
…utput queue Review of #1625. `h2_transmit::frame_tail` rescanned the gathered slices from the first one for every byte of every frame header, so its cost was the number of frames times the number of slices, and it ran after every transmit. A queue of 2700 one-byte DATA frames (an H1 chunked body with tiny chunks) took about 1.9 ms per call. It now reads frame headers through a forward-only cursor, linear in the slices, and the shells call it only when the write took less than it was offered. `H2Output::consume` only advanced `head`, so a queue that never drains to empty under steady backpressure kept every sent byte on its heap. It now moves the queued bytes to the front once the sent prefix is past the retained capacity and larger than what is left, and shrinks a capacity more than four times the rest. Emptying the queue (a peer that hung up while the connection drains) did not clear `reads_wait_for_output`, so the read cap could keep READABLE withdrawn with nothing left to wait for. Both emptying paths now release it. The `graceful_goaway` and `send_initial_goaway` comments still spoke of `zero`. `LIFECYCLE.md` invariant 28, `h2_output.rs` and `doc/h2_mux_internals.md` claimed that dropping a removed stream's unsent frames is invisible to the peer. That holds for framing but not for an already-encoded header block, whose HPACK insertions stay in the encoder table (#1627, older than the queue). Tests: the walk steps past each slice at most once for 2700 frames; a queue that never drains stays bounded; clearing the queue releases the read cap. Each reddens under the mutation its comment names. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
fix/h2-ordered-output
branch
from
September 27, 2026 18:18
a0889ec to
16d6aba
Compare
This was referenced Sep 27, 2026
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 27, 2026
## What Two allocation cuts in `HttpContext::on_request_headers` / `on_response_headers` (`lib/src/protocol/kawa_h1/editor.rs`), the header editor shared by the H1 and H2 frontends. No syscall changes, and the bytes forwarded stay the same (pinned by a byte-exact test). 1. **`perf(h1)`: render the forwarding headers of a request through one scratch.** Each synthesised header took the scratch `Vec` itself (`Store::from_vec(std::mem::take(..))`). That hand-over cost two heap operations per header: `into_boxed_slice` shrinks the spare capacity with a `realloc`, and the next header regrows an empty `Vec` (8 → 16 → 32 → 64 bytes for `Forwarded`). Each header now takes an exact-size copy of one reused scratch. A bare request goes from 14 to 10 heap operations. 2. **`perf(h1)`: render a request's id once and share it across its headers.** The generated `X-Request-Id`, its copy for the access log, and the `Sozu-Id` value on the request and on the response were four renderings of the same ULID, each through `Ulid`'s allocating `Display`. The `Sozu-Id` name was also copied onto both. The id is now rendered on the stack and copied once into an `Rc<str>`, and all four share it through `kawa::Store::Shared`. The default `Sozu-Id` name is a `'static` literal; a renamed header is still copied. A client-supplied `X-Request-Id` is still forwarded verbatim, and `Sozu-Id` still carries Sōzu's own id. The request goes from 10 to 7 heap operations, and the response from 3 to 1. **Dependency note**: `Store::Shared` needs kawa's `rc-alloc` feature. That feature is in kawa's default set, and `sozu-lib` now enables it on the kawa 0.7.1 it already pins. No crate is added and `Cargo.lock` does not change. `HttpContext::x_request_id` becomes `Option<Rc<str>>`. ## Measurements Worker only, release build, 1 worker, `file://` access log. The load is one `curl --http1.1` process sending N = 20 requests over **one keep-alive connection**, after a warm-up. The backend is a Python `http.server` with `protocol_version = "HTTP/1.1"`. The same run is repeated twice (rep 1, rep 2), interleaving before and after. Before is `0155d40b` (`origin/main` when measured) and after is this branch on top of it. Syscalls are counted with `intentrace -p <worker>` on the production feature set (`--no-default-features --features jemallocator,crypto-aws-lc-rs`). Allocations are counted with an `LD_PRELOAD` malloc counter on the same code built without jemalloc (`--features crypto-aws-lc-rs`), because the counter cannot interpose jemalloc. LOAD1 was 8–25 on a 20-core host; every deterministic count below matched to the integer across both reps. | per request (20 req / 1 conn) | before | after | Δ | |---|---|---|---| | **H1 clear** heap operations (malloc+calloc+realloc) | 24.60 | 15.55 / 15.60 | **−9.05 (−37 %)** | | — malloc+calloc | 19.05 | 15.05 | −4.00 | | — realloc | 5.55 | 0.50 / 0.55 | −5.05 | | — bytes requested | 1572.7 | 1343.0 / 1382.2 | −190…−230 | | **H1 TLS** heap operations | 40.65 | 31.65 | **−9.00 (−22 %)** | | — bytes requested | 4731.9 | 4541.5 | −190.4 | | H1 clear syscalls (intentrace) | 11.55 | 11.55 | 0 | | H1 TLS syscalls (intentrace) | 11.85 | 11.85 | 0 | The unit tests predict the −9 exactly: −4 from the scratch and −5 from the id (−3 on the request, −2 on the response). After rebasing onto `58550dd4` (#1625), the branch head was measured again and gave the same numbers: 15.55 and 31.65 heap operations, 11.55 and 11.85 syscalls. The syscall shape per keep-alive request is 3 × `epoll_wait`, 3 × `recvfrom`, 3 × `writev` and 2 × `getsockopt(TCP_INFO)`. The third read/write pair comes from the test backend, not from Sōzu: Python's `http.server` sends the headers and the body as two segments. There is no per-request `epoll_ctl`, no read that ends in `EAGAIN`, and no `clock_gettime` trap. ## Tests (each seen red first) - `a_bare_request_costs_one_scratch_and_one_copy_per_forwarding_header` pins 7. It went red at `left: 14, right: 10` on the commit-1 recipe, then at `left: 11` with the `from_vec` hand-over restored and at `left: 10` with the per-header id renderings restored. - `a_response_shares_the_request_id_rendering` pins 1 allocation and the response bytes, on both the generated and the client-chosen `X-Request-Id` path. It went red at `left: 3, right: 1`. - `header_editing_output_is_byte_exact_across_keep_alive_requests`: three keep-alive requests with a renamed correlation header and `send_x_real_ip`, plus client-supplied `X-Forwarded-For`, `Forwarded` and `X-Request-Id`. This is a behaviour test and passed before and after. - `render_ulid_matches_the_display_rendering`: `0`, `u128::MAX` (top digit `7`), `1 << 127`, and generated ids. ## Commands run `cargo build --locked`, `cargo build --all-features --locked`, `cargo clippy --all-targets --locked -- -D warnings`, `cargo +nightly fmt --all -- --check`, `cargo test --workspace --locked -- --skip tests::fuzz_tests:: --test-threads=8`, and the four `check_doc_citations.py` runs (`--self-test`, the broken fixture tree exits 1, `--base origin/main`, plain). Everything passed on the rebased head except one run of `tests::tests::test_async`, where `client0` got 99 of its 100 responses. That was the full workspace run at LOAD1 ≈ 20: `try_async` reads each response with a single `receive()`, which is the one-segment read `doc/testing.md` warns about. The test then passed three times out of three when run alone (`cargo test -p sozu-e2e -- --exact tests::tests::test_async`). The `writev` shape, counted as regions and bytes per call, is identical before and after, and on the rebased head, for both the clear and TLS runs. The `Store::Shared` headers therefore go through `h2_transmit::gather` onto the wire unchanged. Two `editor.rs` line citations drifted because of the new code and were renumbered (`doc/h2_mux_internals.md`, `lib/src/protocol/kawa_h1/LIFECYCLE.md`). ## What is left on the H1 keep-alive path, measured, not in this PR - **`getsockopt(TCP_INFO)` ×2 per request** (17 % of the H1 syscalls). These are the frontend `sample_rtt` and the backend `peer_rtt` that feed the access log. Removing them means sampling the RTT less than once per request, which changes what the log reports. - **A per-connection cache of the rendered id and forwarding values** would save −5 heap operations per keep-alive request (7 → 2 in the unit test). It needs a new `HttpContext` field, and that field also has to be added to the exhaustive `HttpContext` literal in the H2 test fixtures in `h2.rs`. - **4 allocations per request carry the cluster id**: `consult_ip_gate` ×2, `track_cluster_ip`, and `Router::from_frontend`. These are left to the `ClusterId` → `Rc<str>` change. - **The replay capture `reserve`** (`ConnectionH1::writable`) costs 1 allocation (~request size) per request on a pooled upstream. - **The `reason` capture** costs 1 allocation per response; a table of standard reason phrases would remove it. - **rustls owned buffers on TLS**: about 5 allocations and ~900 B per request (encrypt output, received plaintext, `write_vectored`). **Pre-existing finding, not changed here:** on an H1 keep-alive connection every request carries the same `HttpContext::id`. The measured access log shows one request id across 20 requests. `HttpContext::reset` asserts the id is preserved, while `lib/src/protocol/kawa_h1/LIFECYCLE.md` says it "IS rotated per request" and `doc/configure.md` calls `%REQUEST_ID` a per-request ULID. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 27, 2026
`try_h2_continuation_survives_a_graceful_drain_mid_reassembly` ran its listener with the default 5 s `h2_graceful_shutdown_deadline_seconds`. That budget starts when the drain lands mid-reassembly, and every later step in the test waits on something: a `server.live` round-trip, then an `h2.frames.rx.headers` round-trip, then the backend's answer. On one contended CPU these steps added up past 5 s. The worker's debug log for a failing iteration shows the drain armed at 06.403, the deferred initial GOAWAY sent at 09.19 and "graceful-shutdown deadline elapsed, forcing close" at 12.53, with both streams still `Linked` and unanswered. The client therefore read the advisory GOAWAY and then EOF. Sozu enforced the budget it was configured with. The listener now sets the knob to `0`, meaning "wait for the streams", so the drain ends on the condition the test asserts: both streams served, then the final GOAWAY. It no longer ends on a clock. The assertions are unchanged. The forced close stays covered by `test_h2_graceful_shutdown_timeout_forces_close` and the two `test_h2_graceful_shutdown_deadline_configurable_*` tests. Each early return now drops the client connection before waiting for the worker, so a failed run cannot hang on a drain that has no deadline. Before #1625, forcing `GracefulDrainDecision::DeferInitial` to `SendInitial` made the test fail through one of these paths in 7.5 s instead of hanging. Closes #1623 Signed-off-by: Florentin Dubois <[email protected]>
This was referenced Sep 27, 2026
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 27, 2026
…trings (#1629) ## Motivation `sozu_command_lib::state::ClusterId` was `String`. Every routed request cloned its cluster id out of the route table (`RouteResult` built from the matched `Route::Frontend`), and the per-(cluster, source-IP) gate cloned it three more times: in `consult_ip_gate`, in `SessionManager::track_cluster_connection`, and as the `entry` key of `SessionManager::track_cluster_ip`. The last clone happened even when the track was an idempotent no-op. Production traffic always carries a source address, so it always goes through the gate. `ClusterId` is now `Arc<str>`. The route table, `HttpContext::cluster_id`, the gate's `SessionManager` maps, `ConnectPlan::Dial` and the backend connection's `Position::Client` all share the one allocation made when the frontend was added. The TCP and UDP listeners, sessions, pipes and preread routes share theirs in the same way. The protobuf messages (`command.proto`, generated `command.rs`, not edited) keep `String`. The id is converted once, when a request or a saved state enters `ConfigState` or a proxy. ## Measurements These counts come from the `test_allocations` counting allocator in `sozu-lib`. Each figure is the number of allocations per routed request on a reused backend connection, averaged over 64 requests after one warm-up. The measured path is `Router::plan_connect`, then on the gated path `consult_ip_gate` with its `SessionManager` bookkeeping and `Router::plan_connect_resume`, then the production release (`unlink_stream` + ledger drain). The harness was a temporary unit test beside `a_routed_request_on_a_reused_backend_connection_copies_no_cluster_id` and is not committed. The BEFORE numbers were measured on `0155d40b` and again on `58550dd4` (#1625 merged), with identical results. The AFTER numbers were measured on this branch, rebased on `58550dd4`, with `Arc<str>`. | Backend connection | Gate | Before (release) | After (release) | Before (debug) | After (debug) | |---|---|---|---|---|---| | H1 keep-alive | none (no source address) | 1 | **0** | 4 | 3 | | H1 keep-alive | per-(cluster, source-IP) | 4 | **0** | 7 | 3 | | H2 connected | none | 1.28 | **0.28** | 4.28 | 3.28 | | H2 connected | per-(cluster, source-IP) | 4.28 | **0.28** | 7.28 | 3.28 | - The remaining 0.28 on H2 is the backend H2 connection's stream table growing across the 64 streams. It is not a cluster id. - The remaining 3 in debug are the `DebugEvent::Str` history push, which is compiled out of release builds. - The frontend protocol (H1 or H2) makes no difference here. Routing stamps `HttpContext::cluster_id` the same way for both, so the axis that matters is the kind of backend connection. Allocation tests that pin the result: - `a_routed_request_on_a_reused_backend_connection_copies_no_cluster_id` now includes the gate's `SessionManager` bookkeeping in its measurement. Its control covers only the debug history, and it asserts `branched == controlled`. I saw it fail (release, 64 vs 0) by handing `track_cluster_connection` a fresh `ClusterId::from(&**cluster_id)`, then pass again once that was reverted. - `a_dial_moves_the_planned_cluster_id_into_the_backend_connection` also asserts that the new connection and the stream's `HttpContext` point at the same id. I saw it fail by stamping `ConnectPlan::Dial` with `ClusterId::from(&**cluster_id)`. - `a_tree_lookup_allocates_nothing_past_its_route_result`: the control no longer counts a copy of the cluster id. ## `Arc` rather than `Rc` A worker is single-threaded, but `ConfigState` and the `response` types are public API that embedders share across threads. - **proxy-manager** keeps `ConfigState` in `context::State` (`src/svc/context.rs`), behind a `tokio::sync::RwLock` inside an `Arc<Context>`. That value is captured by multi-threaded `tokio::spawn` tasks and used as an `axum::Extension`, so it must be `Send + Sync`. proxy-manager depends on `sozu-command-lib = "^2.2.0"`, so an `Rc<str>` alias would break its build on its next `cargo update`. An intermediate `Rc<str>` revision of this branch did exactly that when checked against proxy-manager: 36 errors per target. - **Assertion:** a compile-time assertion next to the alias (`command/src/state.rs`) now locks the contract. It holds `ClusterId`, `ConfigState`, `StateError` and `response::{HttpFrontend, TcpFrontend, UdpFrontend, Backend}` to `Send + Sync`. - With `Rc<str>` the crate fails with 14 `E0277` errors (`Rc<str>` cannot be sent / shared between threads safely): one `Send` and one `Sync` error for each of the seven types. - With `Arc<str>` it builds. - **Test harnesses:** the moonpool-sim harness and the e2e worker handle also rely on `Send`, and are unchanged. - **Cost:** an `Arc` clone is an uncontended atomic increment. - **proxy-manager check** (`origin/main` 1f61a03, temporary detached worktree, nothing committed): after `cargo update -p [email protected] --precise 2.2.1` and `cargo update -p mio --precise 1.2.3`, `cargo check --all-targets --config 'patch.crates-io.sozu-command-lib.path="<this branch>/command"'` → `EXIT=0`. The mio update is a lockfile-only change: sozu `main` already requires mio `^1.2.3`. ## API break - **`sozu-command-lib`**: - `state::ClusterId` changes from `String` to `Arc<str>`. The types stay `Send + Sync`, and a compile-time assertion now guarantees it. - The following follow it: the keys of `ConfigState::{clusters, backends, tcp_fronts, udp_fronts}`, `ConfigState::hash_state` / `get_cluster_ids_by_domain`, the fields of `StateError::UdpFrontendAddressTaken`, and `cluster_id` on `response::{HttpFrontend, TcpFrontend, UdpFrontend, Backend}`. - serde's `rc` feature is enabled on the existing serde dependency, so these types keep deriving `Serialize`/`Deserialize`. There is no new crate and `Cargo.lock` is unchanged. - JSON output and state hashes are unchanged, because `Arc<str>` serializes and hashes as the `str` it holds. - **`sozu-lib`**: `HttpContext::cluster_id`, `SessionManager::{track_cluster_ip, track_cluster_subnet, track_cluster_connection}`, `BackendConnectionError::{MaxConnectionRetries, TooManyConnectionsPerIp}`, `ProxySession::cluster_id`, `Pipe::set_cluster_id` and `protocol::udp::ClusterConfig::cluster` now take or return `ClusterId`. - To migrate, use `.into()` / `ClusterId::from(..)` from `&str` or `String`. This PR does not change protocol or security behaviour. No wire format, config key, metric, CLI flag or log line changes. The `lib/src/protocol/mux/{connection,mod,h2}.rs` diff is limited to types (plus one test fixture in `h2.rs`), and the branch was rebased on #1625. Doc citations were kept line-stable, so `check_doc_citations.py --base origin/main` passes without renumbering anything. ## Commands run (on the pushed SHA unless noted) - `cargo build --locked` → exit 0 - `cargo build --all-features --locked` → exit 0 - `cargo build --workspace --all-targets --all-features --locked` → exit 0 - `cargo clippy --all-targets --locked -- -D warnings` → exit 0 (also `--all-features`) - `cargo +nightly fmt --all -- --check` → exit 0 - `cargo test --workspace --locked --exclude sozu-e2e -- --skip tests::fuzz_tests::` → 1703 passed, 0 failed - `cargo test -p sozu-e2e --locked -- --skip tests::fuzz_tests:: --test-threads=8` → 456 passed, 0 failed - `cargo test --release -p sozu-lib --lib -- allocat copies_no_cluster_id a_dial_moves` → 20 passed - `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked` → 31 passed - `cargo check --bins --locked` in `fuzz/` → exit 0 (both fuzz targets that build a `ClusterConfig` / route table were updated) - `python3 .github/scripts/check_doc_citations.py --self-test` → 0; `--root .` → 0; `--root . --base origin/main` → 0; `--audit --root .` → 0 `CHANGELOG.md` (Changed) and the docs that described the old copies (`doc/testing.md`, `lib/src/protocol/mux/LIFECYCLE.md`, the `SessionManager` and mux doc comments) are updated in the same commit. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 28, 2026
…nsent The write pass debits the stream's and the connection's send windows when `H2WritePhase::Prepare` encodes DATA into `kawa.out`, before the socket takes any of it. RFC 9113 §6.9 counts only DATA that was sent, and the peer returns credit through WINDOW_UPDATE only for what it received. When the parked stream holding such DATA was removed (peer RST_STREAM, client cancel, timeout, `prune_inactive_streams_while_closing`) or had its queue cleared (`forcefully_terminate_answer`, a default answer), the frames were dropped and the credit was lost for the life of the connection. Enough drops closed the connection window, every stream's DATA stalled, and the flow-control-stall reaper cancelled streams that had done nothing wrong. Only the stream parked in `expect_write` holds unsent frames, the argument #1627 relies on. Where a pass parks a stream, `ConnectionH2::parked_data` now records the DATA payload `kawa.out` still holds whole (`h2_transmit::queued_data_payload`, the frame walk `holds_header_frame` already used, now shared, with no allocation). The rest of a frame a partial write cut is not counted: `H2Output` adopted it and sends it whole (#1625). `ConnectionH2::remove_dead_stream` gives that credit back to the connection window when it removes the parked stream, re-arming WRITABLE when the window reopens, and the next `H2WritePhase::Start` gives back to both windows whatever a live park no longer queues. `H2FlowControl::refund_send_window` asserts the window grows by exactly the refund; a queue that ends inside a DATA frame does not count it, so the connection gives back too little rather than too much. A refund can still pass 2^31-1 when the peer's WINDOW_UPDATEs, each valid on its own, overgranted while the DATA sat parked: that is peer input, so it is not applied and the connection answers GOAWAY(FLOW_CONTROL_ERROR), as for an overflowing increment (RFC 9113 §6.9.1), rather than asserting. Refunding the unsent part matches hyperium/h2, whose `Prioritize` reclaims reserved but unsent capacity on a reset (`reclaim_reserved_capacity`). HAProxy debits `h2s->sws`/`h2c->mws` when a frame enters the connection's `mbuf`, which a stream never drops. Debiting at transmit time instead would still need an in-flight counter, because the converter uses the window as its budget at prepare time, and would walk frames on every write rather than on a park. Three connection-level tests, red on 5db53c6: a parked window-sized body removed by the peer's RST_STREAM (the window stayed 0 and stream 3's body never left), a live parked stream whose queue a forced termination cleared (both windows stayed 0), and a partial write whose cut frame is sent whole while only the frames behind it are given back. Two more cover a second stalled pass, which must give nothing back, and a peer that overgrants before resetting the parked stream, which panicked on a debug assertion before and now gets GOAWAY(FLOW_CONTROL_ERROR). Closes #1641 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 28, 2026
…nsent The write pass debits the stream's and the connection's send windows when `H2WritePhase::Prepare` encodes DATA into `kawa.out`, before the socket takes any of it. RFC 9113 §6.9 counts only DATA that was sent, and the peer returns credit through WINDOW_UPDATE only for what it received. When the parked stream holding such DATA was removed (peer RST_STREAM, client cancel, timeout, `prune_inactive_streams_while_closing`) or had its queue cleared (`forcefully_terminate_answer`, a default answer), the frames were dropped and the credit was lost for the life of the connection. Enough drops closed the connection window, every stream's DATA stalled, and the flow-control-stall reaper cancelled streams that had done nothing wrong. Only the stream parked in `expect_write` holds unsent frames, the argument now records the DATA payload `kawa.out` still holds whole (`h2_transmit::queued_data_payload`, the frame walk `holds_header_frame` already used, now shared, with no allocation). The rest of a frame a partial write cut is not counted: `H2Output` adopted it and sends it whole (#1625). `ConnectionH2::remove_dead_stream` gives that credit back to the connection window when it removes the parked stream, re-arming WRITABLE when the window reopens, and the next `H2WritePhase::Start` gives back to both windows whatever a live park no longer queues. `H2FlowControl::refund_send_window` asserts the window grows by exactly the refund; a queue that ends inside a DATA frame does not count it, so the connection gives back too little rather than too much. A refund can still pass 2^31-1 when the peer's WINDOW_UPDATEs, each valid on its own, overgranted while the DATA sat parked: that is peer input, so it is not applied and the connection answers GOAWAY(FLOW_CONTROL_ERROR), as for an overflowing increment (RFC 9113 §6.9.1), rather than asserting. Refunding the unsent part matches hyperium/h2, whose `Prioritize` reclaims reserved but unsent capacity on a reset (`reclaim_reserved_capacity`). HAProxy debits `h2s->sws`/`h2c->mws` when a frame enters the connection's `mbuf`, which a stream never drops. Debiting at transmit time instead would still need an in-flight counter, because the converter uses the window as its budget at prepare time, and would walk frames on every write rather than on a park. Three connection-level tests, red on 5db53c6: a parked window-sized body removed by the peer's RST_STREAM (the window stayed 0 and stream 3's body never left), a live parked stream whose queue a forced termination cleared (both windows stayed 0), and a partial write whose cut frame is sent whole while only the frames behind it are given back. Two more cover a second stalled pass, which must give nothing back, and a peer that overgrants before resetting the parked stream, which panicked on a debug assertion before and now gets GOAWAY(FLOW_CONTROL_ERROR). Closes #1641 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 28, 2026
…nsent (#1646) ## Summary `H2WritePhase::Prepare` (`ConnectionH2::poll_write_target`, `lib/src/protocol/mux/h2.rs`) debits the stream's and the connection's send windows when it encodes DATA, before the socket takes any of it. When the parked stream holding such DATA was removed or had its `kawa.out` cleared, the frames were dropped but the credit was never given back, and the peer never returns credit for DATA it never received (RFC 9113 §6.9). Each drop shrank the connection window for the life of the connection, until every stream's DATA stalled. Scope, per the comment on #1631/#1632: a backend H2 connection belongs to one `Mux` session (`Mux::router`), so the damage stays within one session, but a long-lived frontend or backend connection could still starve. ## Fix Refund what will never be sent, rather than move the debit to transmit time (the converter needs the window as its budget at prepare time, so send-time accounting would still need an in-flight counter, and would walk frames on every write instead of on a park). - `ConnectionH2::parked_data` records, where a pass parks a stream, the DATA payload `kawa.out` still holds whole (`h2_transmit::queued_data_payload`). It shares the frame walk of `h2_transmit::holds_header_frame` (#1627), runs only on a park, and allocates nothing. The rest of a frame a partial write cut is in `H2Output` (#1625) and is sent whole, so it is not counted. - `ConnectionH2::remove_dead_stream`, which every removal goes through, gives the parked credit back to the connection window before `H2StreamTable::remove` clears the park, and re-arms WRITABLE when that reopens a closed window. - The next `H2WritePhase::Start` gives back, to both windows, the part of a live park's DATA that is no longer queued (`forcefully_terminate_answer`, a default answer). - `H2FlowControl::refund_send_window` uses `checked_add` and asserts that the window grows by exactly the refund. A queue that ends inside a DATA frame does not count that frame, so the connection gives back too little rather than too much. - A peer can push `window + unsent octets` past 2^31-1 with WINDOW_UPDATEs that are each valid on their own and are sent while the DATA sits parked. A refund that would overflow is therefore peer input. It is not applied, and the connection answers GOAWAY(FLOW_CONTROL_ERROR) exactly as `ConnectionH2::handle_window_update_frame` does for an overflowing increment (RFC 9113 §6.9.1). Nothing asserts on it. Prior art: hyperium/h2 `Prioritize::reclaim_reserved_capacity` returns reserved but unsent capacity on a reset. HAProxy debits `h2s->sws`/`h2c->mws` when a DATA frame enters the connection's `mbuf`, which is never dropped per stream. ## Tests (red on `5db53c60`, green here) - `data_dropped_with_its_parked_stream_gives_the_connection_window_back`: a 66535-octet body takes the whole connection window in one prepare, the socket takes 0 bytes, and the peer's RST_STREAM(1) removes the stream. On main the window stays at `0` and stream 3's 1000-octet body never leaves. The test also removes WRITABLE interest before the RST and asserts that the refund re-arms it (checked by mutation). - `data_dropped_from_a_live_parked_stream_gives_both_windows_back`: the same park, with `forcefully_terminate_answer` in place of the removal. On main both windows stay at `0`. - `data_a_partial_write_started_is_sent_whole_and_not_given_back`: the socket cuts the first DATA frame. The frame still leaves whole (16384 octets), and `window + DATA sent == 65535`. On main this reads `16384` against `65535`. If the whole prepare is refunded instead, it reads `81919`. - `data_still_parked_after_a_second_stalled_pass_is_not_given_back`: a second stalled pass keeps the park and must give nothing back. If `parked_data - queued` becomes `parked_data`, the window reads `65535` against `0`. - `a_refund_the_peer_pushed_past_the_window_ceiling_is_a_flow_control_error`: stream 1 is parked, then the peer sends `WINDOW_UPDATE(0, 2^31-1)` and `RST_STREAM(1)`. On `08730c9a` this hit the `debug_assert!` (a panic caused by network input). The connection now sends exactly one GOAWAY carrying FLOW_CONTROL_ERROR. If the overflow is dropped silently instead, no GOAWAY is sent (`left: 0, right: 1`). - Unit tests: `queued_data_payload_counts_only_data_payload_octets`, `refund_gives_back_consumed_credit_and_reports_a_reopened_window` and `a_refund_past_the_window_ceiling_is_an_overflow_and_changes_nothing`. The harness runs in `Position::Server`. The Start/Flush arms and `remove_dead_stream` never branch on position, so the backend path is the same code. Each `TO SEE THIS RED` recipe was checked by mutation. ## Commands - `cargo build --locked`, `cargo build --all-features --locked` - `cargo clippy --all-targets --locked -- -D warnings`, plus the same with `--no-default-features --features crypto-ring,opentelemetry,splice,simd` - `cargo +nightly fmt --all -- --check` - `cargo test --workspace --locked -- --skip tests::fuzz_tests:: --test-threads=8` - `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim` - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` - `check_doc_citations.py`: `--self-test`, the fixture root (exits 1 as expected), plain, and `--base origin/main` The `Store::Static` fixture works around CleverCloud/kawa#22 (`Store::consume` overflows on a split `Store::Alloc` in debug builds). ## Docs `lib/src/protocol/mux/LIFECYCLE.md` (§5.1 and a new invariant 28 property), `doc/h2_mux_internals.md` (new subsection "Prepared DATA dropped unsent gives its send credit back"), and `CHANGELOG.md` (Fixed). Line citations into `h2.rs` were re-anchored, because adding the production code shifted them. Closes #1641 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 28, 2026
…is incomplete A graceful drain deferred its initial GOAWAY(NO_ERROR, 2^31-1) while a HEADERS/CONTINUATION block was being reassembled. The deferral was added for #1401, when the GOAWAY was serialised into zero.storage, the buffer that also held the block. Since #1625 control frames go to the separate output queue and the block lives in ConnectionH2::header_reassembly, so the deferral protected no buffer. It still had an effect on the wire: when a soft-stop landed while a connection's only stream was mid-block, that stream was still Idle, Mux::shutting_down_inner did not wait for it, nothing was queued, and the session closed with no GOAWAY at all, against RFC 9113 §6.8. RFC 9113 §4.3/§6.10 constrain the sender of a field block, not a GOAWAY travelling the other way; hyperium/h2 (Connection::go_away_gracefully) and HAProxy (h2_process) send it unconditionally too. Remove the deferral: H2DrainState::initial_goaway_pending, GracefulDrainDecision::DeferInitial, take_deferred_initial_goaway and its test accessor, the reassembly_in_progress parameter of begin_graceful_drain, the deferred-GOAWAY stage of flush_pending_control_frames, the DeferInitial arm of graceful_goaway, and header_block_reassembly_in_progress, which has no caller left. test_h2_graceful_drain_mid_header_block_sends_goaway_before_closing pins the wire behaviour: red before (0 bytes, no GOAWAY before the close), green after. a_legitimate_continuation_survives_a_graceful_goaway now reads the advisory GOAWAY on the peer socket before the CONTINUATION is sent, then checks the block still decodes. The h2_drain unit tests that asserted the flag are replaced by tests of the remaining decisions. Docs: h2_drain.rs module doc, LIFECYCLE.md §2.2 and invariant 24, doc/h2_mux_internals.md, the sozu#1453 paragraph of doc/testing.md, the e2e test's doc comment and CHANGELOG. Line citations shifted by the removal are re-pointed. Closes #1637 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 28, 2026
…is incomplete A graceful drain deferred its initial GOAWAY(NO_ERROR, 2^31-1) while a HEADERS/CONTINUATION block was being reassembled. The deferral was added for #1401, when the GOAWAY was serialised into zero.storage, the buffer that also held the block. Since #1625 control frames go to the separate output queue and the block lives in ConnectionH2::header_reassembly, so the deferral protected no buffer. It still had an effect on the wire: when a soft-stop landed while a connection's only stream was mid-block, that stream was still Idle, Mux::shutting_down_inner did not wait for it, nothing was queued, and the session closed with no GOAWAY at all, against RFC 9113 §6.8. RFC 9113 §4.3/§6.10 constrain the sender of a field block, not a GOAWAY travelling the other way; hyperium/h2 (Connection::go_away_gracefully) and HAProxy (h2_process) send it unconditionally too. Remove the deferral: H2DrainState::initial_goaway_pending, GracefulDrainDecision::DeferInitial, take_deferred_initial_goaway and its test accessor, the reassembly_in_progress parameter of begin_graceful_drain, the deferred-GOAWAY stage of flush_pending_control_frames, the DeferInitial arm of graceful_goaway, and header_block_reassembly_in_progress, which has no caller left. test_h2_graceful_drain_mid_header_block_sends_goaway_before_closing pins the wire behaviour: red before (0 bytes, no GOAWAY before the close), green after. a_legitimate_continuation_survives_a_graceful_goaway now reads the advisory GOAWAY on the peer socket before the CONTINUATION is sent, then checks the block still decodes. The h2_drain unit tests that asserted the flag are replaced by tests of the remaining decisions. Docs: h2_drain.rs module doc, LIFECYCLE.md §2.2 and invariant 24, doc/h2_mux_internals.md, the sozu#1453 paragraph of doc/testing.md, the e2e test's doc comment and CHANGELOG. Line citations shifted by the removal are re-pointed. Closes #1637 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 28, 2026
…is incomplete A graceful drain deferred its initial GOAWAY(NO_ERROR, 2^31-1) while a HEADERS/CONTINUATION block was being reassembled. The deferral was added for #1401, when the GOAWAY was serialised into zero.storage, the buffer that also held the block. Since #1625 control frames go to the separate output queue and the block lives in ConnectionH2::header_reassembly, so the deferral protected no buffer. It still had an effect on the wire: when a soft-stop landed while a connection's only stream was mid-block, that stream was still Idle, Mux::shutting_down_inner did not wait for it, nothing was queued, and the session closed with no GOAWAY at all, against RFC 9113 §6.8. RFC 9113 §4.3/§6.10 constrain the sender of a field block, not a GOAWAY travelling the other way; hyperium/h2 (Connection::go_away_gracefully) and HAProxy (h2_process) send it unconditionally too. Remove the deferral: H2DrainState::initial_goaway_pending, GracefulDrainDecision::DeferInitial, take_deferred_initial_goaway and its test accessor, the reassembly_in_progress parameter of begin_graceful_drain, the deferred-GOAWAY stage of flush_pending_control_frames, the DeferInitial arm of graceful_goaway, and header_block_reassembly_in_progress, which has no caller left. test_h2_graceful_drain_mid_header_block_sends_goaway_before_closing pins the wire behaviour: red before (0 bytes, no GOAWAY before the close), green after. a_legitimate_continuation_survives_a_graceful_goaway now reads the advisory GOAWAY on the peer socket before the CONTINUATION is sent, then checks the block still decodes. The h2_drain unit tests that asserted the flag are replaced by tests of the remaining decisions. Docs: h2_drain.rs module doc, LIFECYCLE.md §2.2 and invariant 24, doc/h2_mux_internals.md, the sozu#1453 paragraph of doc/testing.md, the e2e test's doc comment and CHANGELOG. Prose citations the removal shifted now name a symbol; pinned code-block annotations, which quote their lines verbatim, are re-pointed. Closes #1637 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 28, 2026
…is incomplete A graceful drain deferred its initial GOAWAY(NO_ERROR, 2^31-1) while a HEADERS/CONTINUATION block was being reassembled. The deferral was added for #1401, when the GOAWAY was serialised into zero.storage, the buffer that also held the block. Since #1625 control frames go to the separate output queue and the block lives in ConnectionH2::header_reassembly, so the deferral protected no buffer. It still had an effect on the wire: when a soft-stop landed while a connection's only stream was mid-block, that stream was still Idle, Mux::shutting_down_inner did not wait for it, nothing was queued, and the session closed with no GOAWAY at all, against RFC 9113 §6.8. RFC 9113 §4.3/§6.10 constrain the sender of a field block, not a GOAWAY travelling the other way; hyperium/h2 (Connection::go_away_gracefully) and HAProxy (h2_process) send it unconditionally too. Remove the deferral: H2DrainState::initial_goaway_pending, GracefulDrainDecision::DeferInitial, take_deferred_initial_goaway and its test accessor, the reassembly_in_progress parameter of begin_graceful_drain, the deferred-GOAWAY stage of flush_pending_control_frames, the DeferInitial arm of graceful_goaway, and header_block_reassembly_in_progress, which has no caller left. test_h2_graceful_drain_mid_header_block_sends_goaway_before_closing pins the wire behaviour: red before (0 bytes, no GOAWAY before the close), green after. a_legitimate_continuation_survives_a_graceful_goaway now reads the advisory GOAWAY on the peer socket before the CONTINUATION is sent, then checks the block still decodes. The h2_drain unit tests that asserted the flag are replaced by tests of the remaining decisions. Docs: h2_drain.rs module doc, LIFECYCLE.md §2.2 and invariant 24, doc/h2_mux_internals.md, the sozu#1453 paragraph of doc/testing.md, the e2e test's doc comment and CHANGELOG. Prose citations the removal shifted now name a symbol; pinned code-block annotations, which quote their lines verbatim, are re-pointed. Closes #1637 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 28, 2026
…is incomplete (#1649) ## Summary A graceful drain deferred its advisory `GOAWAY(NO_ERROR, 2^31-1)` while a peer HEADERS/CONTINUATION block was being reassembled (`GracefulDrainDecision::DeferInitial`, added for #1401 when the GOAWAY was serialised into `zero.storage`, the buffer that also held the block). Since #1625 control frames go to the separate output queue and the block lives in `ConnectionH2::header_reassembly`, so the deferral protected no buffer. #1637 found that the e2e test built for it (sozu#1453) no longer notices the mutation `DeferInitial → SendInitial`. Re-running that mutation against the wire showed the deferral still had one effect, and a harmful one: a soft-stop landing while a connection's only stream is mid-block closes the session with **no GOAWAY at all**. That stream is still `StreamState::Idle`, `Mux::shutting_down_inner` (`lib/src/protocol/mux/mod.rs`) does not wait for it, and with the GOAWAY deferred nothing is queued. This violates RFC 9113 §6.8: "Endpoints SHOULD always send a GOAWAY frame before closing a connection". The deferral has no protocol basis: - RFC 9113 §4.3 ("Field blocks MUST be transmitted as a contiguous sequence of frames") and §6.10 constrain the **sender** of a field block, here the client. A GOAWAY travelling the other way interleaves nothing. - §6.8's "SHOULD send an initial GOAWAY frame with the last stream identifier set to 2^31-1" is not conditioned on the peer's state. - hyperium/h2 0.4.19: `Connection::go_away_gracefully` (`src/proto/connection.rs`) sends it at once, never consulting `FramedRead::partial`. - HAProxy `h2_process` (`src/mux_h2.c` @ `0ceb8c65f`) sends it on `PR_FL_STOPPED` without looking at the demux state. This PR removes the deferral. Behaviour change: the advisory GOAWAY now leaves in the drain pass itself, possibly before the rest of a peer's header block, and a session no longer closes mid-block without one. Closes #1637 ## Removed - `H2DrainState::initial_goaway_pending`, `GracefulDrainDecision::DeferInitial`, `H2DrainState::take_deferred_initial_goaway`, `H2DrainState::__test_initial_goaway_pending` (`lib/src/protocol/mux/h2_drain.rs`) - the `reassembly_in_progress` parameter of `H2DrainState::begin_graceful_drain` - the deferred-GOAWAY stage of `ConnectionH2::flush_pending_control_frames` and the `DeferInitial` arm of `ConnectionH2::graceful_goaway` (`lib/src/protocol/mux/h2.rs`) - `ConnectionH2::header_block_reassembly_in_progress`, which has no caller left ## Red → green New e2e test `test_h2_graceful_drain_mid_header_block_sends_goaway_before_closing` (`e2e/src/tests/h2_tests.rs`). It sends half a HEADERS block (no END_HEADERS) and waits on `h2.frames.rx.headers` (no timer) before calling `soft_stop()`. After `wait_for_server_stop()` it reads everything that reached the client and requires a `GOAWAY(NO_ERROR)`. On `a3cb11ae` (before the change), `unshare -rn`, `--exact`: ``` H2 drain mid-block - received 0 frames H2 drain mid-block - the session closed without a GOAWAY(NO_ERROR) (0 bytes received, stopped=true) stability check FAILED: iteration 1 of 1 did not succeed (a single clean run is required) test result: FAILED. 0 passed; 1 failed ``` The same shape measured with a scratch test before this change: 4/4 runs `bytes=0 goaway=false` on `main`, and 3/3 runs `GOAWAY error_code=0x0, bytes=17` with the `DeferInitial → SendInitial` mutation. After this change: `test result: ok. 1 passed`. ## Tests modified - `h2::tests::a_legitimate_continuation_survives_a_graceful_goaway` (`h2.rs`): it asserted the internal flag (`__test_initial_goaway_pending()` true, then false after `writable()`). It now reads the 17-byte `GOAWAY(NO_ERROR, STREAM_ID_MAX)` on the peer socket **before** sending the CONTINUATION, and keeps every decode assertion (block decodes byte-for-byte, peer dynamic table still resolves). It also asserts that `graceful_goaway` leaves `H2State::ContinuationHeader` untouched, and that completing the block queues no second GOAWAY. Seen red with the deferral reintroduced in `graceful_goaway`: `the peer must receive the advisory GOAWAY before it completes the block: WouldBlock`. - `h2_drain::tests::initial_state`: dropped the flag assertion (the field no longer exists). - `h2_drain::tests::begin_graceful_drain_sends_initial_when_no_reassembly` → `begin_graceful_drain_sends_the_initial_goaway_on_the_first_call`: same assertions minus the flag; the decision no longer takes a reassembly input. - `h2_drain::tests::begin_graceful_drain_defers_initial_during_reassembly`: removed. It asserted the removed decision; the wire behaviour it stood for is now asserted by the two tests above. - `h2_drain::tests::take_deferred_initial_goaway_only_fires_when_ready`: removed together with the method it tested. - `h2_drain::tests::enter_final_goaway_supersedes_a_deferred_initial_goaway` → `enter_final_goaway_after_a_graceful_drain_keeps_the_budget_armed`: there is no deferred GOAWAY left to supersede. It now pins that the final GOAWAY neither arms nor moves the forced-close budget, which `enter_final_goaway` also asserts as a new `debug_assert_eq!`. - `h2_drain::tests::enter_final_goaway_marks_draining_even_without_a_prior_graceful_drain`: added the `started_at == None` assertion. - `h2_drain::tests::begin_graceful_drain_is_idempotent_and_does_not_rearm_the_budget`, `deadline_elapsed_respects_configured_budget`, `deadline_elapsed_never_fires_when_deadline_is_none`: call sites only (one argument fewer). - `reassembly_property` (`h2.rs`): interleave variant `GracefulGoawayDefer` renamed `GracefulGoaway`, because it no longer defers. Behaviour unchanged, property green. - `test_h2_continuation_survives_a_graceful_drain_mid_reassembly` (e2e): doc comment and inline comments only. They described the GOAWAY as deliberately deferred. The corruption and `drain_witnessed` assertions are unchanged. ## Docs - `h2_drain.rs` module doc: the dual-role-hazard section is replaced by the history and the reason for removal. - LIFECYCLE.md §2.2 and invariant 24. - `doc/h2_mux_internals.md`: the `flush_pending_control_frames` stage list, and the field list of `H2DrainState`. - `doc/testing.md`: the sozu#1453 paragraph is now also the example of a guard made inert by a refactor and revealed by re-running its mutation. - `h2_header_reassembly.rs` module doc. - CHANGELOG (Fixed). Removing ~80 lines from `h2.rs` shifted 31 `file:NNN` citations in `doc/` and `LIFECYCLE.md`. They are re-pointed through a diff-based line mapping, and one that had already drifted on `main` (`h2.rs:5294`) now cites a symbol. A distinct defect found here, out of scope: #1647. A stream still in reassembly does not hold the drain open, so its request is lost and no final GOAWAY with the real `last_stream_id` is sent. ## Commands run (after rebase on `96b4bca9`) - `cargo +nightly fmt --all -- --check` → 0 - `cargo build --locked` → 0; `cargo build --all-features --locked` → 0 - `cargo clippy --all-targets --locked -- -D warnings` → 0 - `cargo clippy --all-targets --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -- -D warnings` → 0 - `cargo test --workspace --locked -- --skip tests::fuzz_tests:: --test-threads=8` → 2198 passed, 0 failed, 14 ignored - `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked` → 0 - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` → 0 - `check_doc_citations.py`: `--self-test` 0, broken fixture 1 (expected), `--base origin/main` 0, plain 0 - Stability, 10 sequential runs each, `unshare -rn` with `lo` up, one e2e process, `--exact`: - `test_h2_graceful_drain_mid_header_block_sends_goaway_before_closing` 10/10 - `test_h2_continuation_survives_a_graceful_drain_mid_reassembly` 10/10 - `git merge-tree --write-tree origin/main HEAD` clean 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 #1604
Problem
zerowas both the frame-header input buffer and the control-frame output buffer, and stream frames were written from each stream's ownkawa.out, serialised againstzeroonly throughexpect_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 theremove_dead_streamcallers), 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.rsparse the wire the way the peer does:a0785505a_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, backendend_streamRST, 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.zerois input only.kawa.outblocks asIoSlices intokawa.storage, in the samewritev(2)(h2_transmit::gather_after,ConnectionH2::gather_transmit).h2_transmit::frame_tailreads 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 — andConnectionH2::handle_writehas 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.outkept alive after removal:mbufring: control frames are appended withbr_tail(h2c_ack_settings,h2c_send_ping,src/mux_h2.c), andh2s_make_data's zero-copy path swaps the whole stream buffer into the ring, falling back togoto copywhen the swap cannot apply.FramedWritebuffer for control frames and frame heads and holds an in-flight DATA payload by value inEncoder::nextuntil written (src/codec/framed_write.rs);has_capacity()is false meanwhile. Its payload is a reference-countedBytes, so liveness after the stream goes away is free.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
zeroit replaces did not.Review fixes (second commit)
frame_tailis 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 whensize < offered.the_walk_is_linear_in_the_slicescounts slice steps (≤ 5400 for 5400 slices; the rescan mutation gives 7292700).H2Outputgives back sent heap bytes while in use.consumeonly advancedhead, 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).frontend_hung_up_while_drainingcleared the queue but notreads_wait_for_output;ConnectionH2::clear_outputnow does both.clearing_the_output_releases_the_read_cap.zerowording ingraceful_goaway/send_initial_goawayfixed.LIFECYCLE.mdinvariant 28,h2_output.rsanddoc/h2_mux_internals.mdnow say so. That desync predates this PR and is h2: HPACK encoder table diverges when an encoded HEADERS block is dropped unsent #1627 (reproduced red on771c9e90, with a second path incheck_header_capacity); it is not fixed here.Removed mechanisms
zero_output_deferred;queue_zero_output/park_zero_output; thezero_holds_outputread guard andhandle_header_state's assertion; theResumeZeroflush stage withH2ControlFlushStageandControlFlushResume(the control walk now queues and flushes once,H2ControlFlushTarget::FlushOutput);expect_write = Some(Zero)(onlyOtheris ever parked, for scheduling); the reassembly guards of the WINDOW_UPDATE, RST_STREAM and shutdown flushes.flush_zero_buffer→flush_output_buffer.expect_writeforOtherstays: it keeps a parked stream first in line, but no longer carries framing.Behaviour changes, deliberately
output_read_cap), as HAProxy's demux stops on a fullmbuf(H2_CF_DEM_MROOM);a_full_output_queue_stops_reading_until_it_drainspins it.(ClientSettings, Client)arm: the oldResumeZerostage did it as a side effect of flushingzero, and a client connection starts write-only. Found while removing that stage;a_backend_connection_reads_once_its_preface_is_outpins it.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_outputunit tests (order, prepaid accounting, inline→heap spill and back);h2_transmitframe_tail_casesandgather_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:
!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 fix(mux-h2): keep reading after a stream is reaped mid DATA payload #1599 orphan tests detected the PING ACK "inzero" → in the queue.FIRST_BLOCK/SECOND_BLOCK, the 256 KiB rustls body) now hold real DATA frames of the same lengths: a stream'skawa.outonly 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, andno_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_removedasserts the queue drains (the wire is asserted by the new h2: removing a stream parked mid-frame leaves a truncated frame on the wire #1604 test it used to say was out of scope).a_legitimate_continuation_survives_a_graceful_goawaywaits on the queue instead ofexpect_write.reassembly_property::qc_h2_header_reassembly_survives_interleaved_control_frame_flushessetsTCP_NODELAYon 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.rsmirrors 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.h2writev / total (ANSI stripped, anchored on the syscall name)h2muxwritev / totalh2writevh2mallocs / 20 conns, 4 runsh2muxmallocs, 4 runsh2/h2muxNo syscall is added, and allocations are within run-to-run noise; the same held against
a0785505before #1620 landed. fdtraceh2muxwritev varies with pacing (44–64 across runs on both trees). A first cut stored the queue in a plainVec, which measured +1.35 malloc and +0.7 realloc per connection. That is why the queue has inline storage.Validation (rebased on
0155d40b, head16d6aba8)Build,
cargo +nightly fmt --check, clippy-D warningswithcrypto-ring,opentelemetry,splice,simd,cargo testforsozu-lib(1274),sozuandsozu-command-lib,cargo doc -D warnings, the fourcheck_doc_citations.pyruns, the sim test and clippy under--cfg tokio_unstable: all pass on16d6aba8. E2E (-- --skip tests::fuzz_tests::): 456 passed, 0 failed, the HPACK e2e tests included. The three #1604 tests still fail without the fix (theadopt_tailmutation) 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-threadsthe pin runs the tests serially, about 5 h per run. The same loop was run onbdc74ecd:bdc74ecdtest_h2_continuation_survives_a_graceful_drain_mid_reassembly(a single GOAWAY, then nothing)test_h2_settings_ack_timeout_goaways_the_frontend(client cannot send its preface)test_h2_large_chunked_7mb_drains_fullytest_h1_to_h2_basic_requesttest_h2_large_chunked_7mb_drains_fullyfailed 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 fromlib/appears in any log. I could not reproduce it:h2_correctness5 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_requestfailed 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 ofh2_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 indoc/testing.md; every addition #1626 made to the shared docs is kept, andconverter.rs,hpack_state.rsandhpack/are untouched by this PR.pkawa.rs,converter.rs,hpack_state.rsand the HPACK codec branch inh2.rsare 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]