Repository navigation
perf(mux-h2): reuse the write pass IoSlice vector across passes - #1578
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 26, 2026 14:55
`H2Shell::write_streams` built a fresh `Vec<IoSlice<'static>>` on every pass. The first descriptor `h2_transmit::gather` pushed allocated it and the pass freed it on return, so every transmitting pass cost one heap allocation and every response at least one. Keep the vector as a private `io_slices` field of `H2Shell`. It is cleared, never freed, so only its capacity survives between passes, and no descriptor does: `gather` clears it on entry, `confirm` clears it before `Kawa::consume`, and the `unsafe` window is still the same three statements. The field is private, so the bracket still cannot be split from outside the crate. No new dependency and no new `unsafe`. `a_warm_write_pass_allocates_nothing` counts one warm pass through the shared `test_allocations` counter: 1 -> 0 allocations under `cargo test --release`. The debug build still counts one `format!` from `finalize_write`'s `cfg(debug_assertions)` instrumentation. Measured on a release build with one worker, a `python3 -m http.server` backend and an LD_PRELOAD allocation counter, sending 100 requests over one `curl --http2` connection: worker heap allocations went from 6825-6906 to 6571-6636 (three runs each). `intentrace -p` counts the same `writev(2)` calls before and after: 600 for 100 sequential connections, and 204 for 100 requests on one connection. Closes #1571 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
perf/h2-write-iovec-no-alloc
branch
from
September 26, 2026 16:32
0b80949 to
c9412d1
Compare
This was referenced Sep 26, 2026
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 26, 2026
Closes #1580 ## What `ConnectionH1::writable` built a fresh `Vec<IoSlice>` on every write pass, in both directions (response to the frontend, request to the backend). It allocated on the first descriptor and then made one `realloc` per doubling. An H1 header block is dozens of `Store` blocks, one per status-line piece and four per header, so `intentrace` shows 45 descriptors in the `writev(2)` of a `curl` request and 32 in that of a `python3 -m http.server` response. This is #1571 on the H1 side, and #1578's mechanism is already shared. `h2_transmit::gather` and `h2_transmit::confirm` are generic over `Kawa<T: AsBuffer>`, and `gather` does exactly what the H1 loop did. So the change reuses that pair and adds no new abstraction: - `ConnectionH1` gets an `io_slices: Vec<IoSlice<'static>>` field. It is `pub(super)` only because the two constructors live in `mux/connection.rs`, like `peer_address`. - `writable` replaces its hand-written loop and its `queued` sum with `h2_transmit::gather`, and its `kawa.consume(size)` with `h2_transmit::confirm`. ## Safety argument Only the vector's capacity survives a pass, never a descriptor: - `gather` clears the vector on entry, and `confirm` clears it before `Kawa::consume`. - Between the two, `writable` makes the vectored write, which reborrows the descriptors and cannot retain them. It then copies the accepted bytes into the replay capture, which reads the descriptors and writes to `retry_buffer`, never to `kawa`, and pushes one debug event. - The window is therefore wider than H2's three statements, and the `SAFETY` comment describes this shape rather than copying H2's. - Its one early `return` inside the window is taken only when the vector is empty. - If the write panics, the stranded descriptors are dropped without being read (`IoSlice` has no `Drop`), and the next `gather` clears them before anything could read them. `h1.rs` gains its first `unsafe` block, which is the call to `gather` under that function's existing `# Safety` contract. There is no new `unsafe` code and no new dependency. The docs of `h2_transmit.rs` and `doc/h2_mux_internals.md` now name the second caller. ## Measurements **Unit tests.** `a_warm_h1_response_write_pass_allocates_nothing` (`Position::Server`) and `a_warm_h1_request_write_pass_allocates_nothing` (`Position::Client`, freshly dialled, so the replay capture stays off) each count the allocations of one warm `writable` pass. They use the shared `crate::test_allocations` counter; no new `#[global_allocator]`. The pass writes 16 `Store` blocks to a live loopback peer. | | before | after | |---|---|---| | `cargo test --release`, response | 3 | **0** | | `cargo test --release`, request | 3 | **0** | | `cargo test` (debug), each side | 3 | **0** | On a3e72a3, one block per pass costs 1 allocation. With 16 blocks, the 3 allocations are one `alloc` and two `realloc`s (4 → 8 → 16). To see the tests fail, give `writable` a per-pass local vector in place of `self.io_slices`, as their doc comments describe. That measures `left: 3, right: 0` in both profiles. **Release binary**, built with `--no-default-features --features crypto-ring,opentelemetry,splice,simd`. The setup is one worker, an H1 listener, and a `python3 -m http.server` backend. The counts come from `intentrace -p <worker> --trace writev`, with ANSI codes stripped and lines anchored on the syscall-name field: | workload (N=100) | before | after | |---|---|---| | `writev(2)`, 100 sequential connections | 200 | 200 | | `writev(2)`, 100 requests on one `curl` connection | 200 | 200 | | descriptors per `writev(2)` | 100 × 45, 100 × 32 | 100 × 45, 100 × 32 | The `writev(2)` count does not change: the change moves where the descriptors live, not how many go into each call. ## Rebased on #1578 Rebased on `b5169d44`, which includes #1578. The two callers of `gather` now share one "two production callers" paragraph in its docs, and the H1 field sits beside H2's private `io_slices` field. ## Checks The following all exit 0: - `cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd` - `cargo +nightly fmt --all -- --check` - clippy with the same features and `--all-targets -- -D warnings` - `cargo test -p sozu-lib` (1161), `-p sozu` (226), `-p sozu-command-lib` (185) - `cargo test -p sozu-e2e -- --skip tests::fuzz_tests::` (449) - sim test and sim clippy under `RUSTFLAGS="--cfg tokio_unstable"` - `check_doc_citations.py` `--self-test`, `--root .`, `--base b5169d4`, and `--audit`. Four `h1.rs` citations in the two `LIFECYCLE.md` files are re-anchored to the same text in the same function. - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 28, 2026
…h the request lifecycles (#1656) ## Summary Writes up the hot-path zero-copy and system-call work merged between 2026-09-26 and 2026-09-28, and rewrites the request lifecycle documentation so it describes the code as it now stands. The work covers the access logs, the request id, `TCP_INFO`, `ClusterId`, the H1 header editor, the H2 output queue and HPACK codec, the read and write paths, accept and close, session setup, and the drain loop. The new document says what changed, how it works, why it was done, and what was measured before and after each change. The lifecycle documents now say, for UDP, TCP, H1, H2 and the mux, which system calls and allocations each step still pays on the nominal path. Documentation and comments only: every changed `.rs` line is a comment (`git diff origin/main -- '*.rs' | grep '^[-+]' | grep -vE '^[-+]\s*(//|\*|$)|^(\+\+\+|---)'` prints nothing), and no production code, test or dependency changes. ## Files | File | Why | |---|---| | `doc/hot_path_zero_copy.md` (new) | Campaign document. §1 goal and rules; §2 method (fixed scenario, instruments) and the closing measurement; §3 one section per theme, each with its mechanism, rationale, before/after figures and PRs; §4 correctness and safety fixes found along the way; §5 invariants and the tests that hold them; §6 the 66 PRs merged in the window. | | `doc/lifetime_of_a_session.md` | Rewritten: event loop, accept, TLS, PROXY pre-flight, the H1, H2, TCP and UDP lifecycles, the mux session, close, soft stop and GOAWAY. Each protocol has a table of the system calls and allocations still paid on the nominal path. | | `lib/src/protocol/udp/LIFECYCLE.md` | Removes the `SelectBackend` / `BackendResolved` round trip, which no longer exists, and adds a §13 per-datagram cost table. Citations converted to symbols. | | `lib/src/protocol/mux/LIFECYCLE.md` | Adds §12, what a request costs on the nominal path. Converts the last five line citations outside pinned blocks, corrects the "cross-client" wording, and replaces `Router::connect` with `Router::plan_connect`. | | `lib/src/protocol/kawa_h1/LIFECYCLE.md` | 23 line citations converted to symbols. The §2.1/§2.2 wording from #1655 is kept. | | `doc/h2_mux_internals.md` | Corrects the "cross-client" wording in three places. The pinned blocks are unchanged. | | `CHANGELOG.md` | Corrects the "cross-client" wording in the #1627, #1631 and #1632 entries, and adds a `docs` entry. | | `doc/README.md` | Links the new document. | | `doc/architecture.md`, `CLAUDE.md` | Both still described `file.rs:LINE` citations, and `CLAUDE.md` still pointed at the stale `lifetime_of_a_session.md`. | | `doc/udp_simulation.md`, `doc/testing.md` | Describe the `ChangeBackendSet` action that replaced `BackendResolved` in the UDP simulator. | | comments in `lib/src/{http,https}.rs`, `lib/src/protocol/mux/{mod,h2,stream}.rs`, `lib/src/udp.rs`, `lib/src/protocol/udp/{flow,manager}.rs` | Section references into the rewritten `lifetime_of_a_session.md` (the close path is now §11), the retired UDP `SelectBackend` / `BackendResolved` round trip, and the frontend-connection scope of a shared H2 backend connection. Line counts unchanged, so no pinned block moves. | ## Closing measurement Measured on 2026-09-28. Two release binaries (`--no-default-features --features crypto-ring,opentelemetry,splice,simd`, glibc malloc), one built at `b5169d44` and one at `c086b456`, run interleaved pass by pass with two repetitions each. During the intentrace passes the one-minute load average was 10.7–24.9 in the first repetition and 2.7–8.5 in the second for the scenarios without keep-alive, and 1.5–2.9 for the keep-alive ones. Setup: one worker, a `file://` access log, a `python3 -m http.server` backend on loopback (an HTTP/1.1 variant for the keep-alive rows), `curl`, N = 20. Instruments: system calls with `intentrace -p <worker>`, ANSI codes stripped and counted on the system-call name field, cross-checked by an `LD_PRELOAD` descriptor tracer; allocations with an `LD_PRELOAD` malloc counter. Figures are per request; ranges are the two repetitions. | Scenario | System calls (intentrace) | Heap operations | Bytes requested | |---|---|---|---| | H1, one request per connection | 26.25–26.70 → **18.45–18.85** | 83.65–83.85 → **39.95–40.35** | 84 327–84 445 → **15 793–16 069** | | H1 keep-alive, 20 requests | 14.75 → **9.65** | 50.80 → **7.80** | 8 362 → **1 322** | | H1 keep-alive over TLS | 15.75 → **10.70** | 63.30 → **20.25–20.30** | 10 644–10 680 → **3 638–3 640** | | H2 over TLS, one request per connection | 61.25–61.60 → **40.15–40.75** | 412.15–413.90 → **240.60–241.75** | 137 094–137 857 → **47 559–47 963** | | H2 over TLS, 20 streams on one connection | 25.05 → **13.55** | 83.40–83.90 → **41.15–42.00** | 11 021–11 029 → **4 792–4 825** | | TCP relay (splice) | 39.00–39.10 → **36.05–36.15** | 31.45 → **14.45** | 4 068 → **3 778** | **Baseline limit.** `b5169d44` was the first release-build baseline. It already included #1552, #1553, #1557, #1558, #1561, #1565, #1568, #1578 and #1581, so their gains are not in this table; each is given, with its own figures, in its section of the document. All other per-PR figures come from the PR descriptions. UDP was not traced: its costs are read from the code and labelled as such. The TLS rows include 15 `getrandom(2)` per handshake, which comes from `crypto-ring`. That is the default provider (`bin/Cargo.toml`, `lib/Cargo.toml`, the Dockerfile, the RPM and Arch packages), so default builds pay it; a `crypto-aws-lc-rs` build issues none on this path (§3.13). Earlier reference points: the campaign's first map (2026-09-26, `LD_PRELOAD` interposer on a debug build, `stdout` access log) counted about 25.1 system calls per H1 request and 34.8 per H2 request, and undercounted because it did not interpose `fcntl` or `recv`. The 106.25 → 25.35 figure is the `tcp://` access-log pass of #1552, measured on its base `ca058989`. ## Doc/code contradictions corrected - Reusing a keep-alive backend involves no liveness probe. What exists is a replay on a fresh connection (`ReplayOnFreshBackend`). - `TcpSession::shutting_down` answers `true`: a TCP session is closed on the first soft-stop pass. It has done so since `be5dd44b` (2020-01-10). - The UDP soft stop is `UdpProxy::notify`'s `SoftStop` arm, not `shutting_down`, and it is active: `Drain`, then `close_all_flows` on every listener session, then the listener sockets are deregistered. - An H1 backend EOF is read by a later `readable` since #1606, not together with the last bytes. - `backend.pool.size` is incremented in `Mux::dial_backend`. - A new UDP flow also costs three `fcntl`, a `getsockname` and a `getpeername` in `udp_connect`, even in release builds. - The UDP simulator's `BackendResolved` action is now `ChangeBackendSet`. - The UDP LIFECYCLE described a `SelectBackend` / `BackendResolved` round trip that no longer exists; selection is done in the core. - `Router::connect` (removed) was cited instead of `Router::plan_connect`. Two code comments in `lib/src/protocol/mux/h2.rs` still name it; they are left for a later change. - An H2 backend connection belongs to one `Mux` session and carries only the streams of one frontend connection. The #1627, #1631 and #1632 entries called it shared by several clients. Another user is reachable only behind an intermediary that multiplexes users on one frontend connection. - Drifted citations: `h2.rs:1439` now pointed at an empty `///` line, and `https.rs:1065` no longer pointed at the shutdown write-up. ## Open question **TCP soft stop.** On soft stop, a TCP relay session is closed on the first pass, with whatever bytes it still has in flight and no drain of its own. The documentation states this without calling it a bug; whether it is the intended behaviour is for the maintainers to decide. ## Also reflected - #1654 (#1647): a draining H2 session waits for a header block still arriving or for a request awaiting its backend link, and a forced close is preceded by a final `GOAWAY(NO_ERROR)`. - #1655 (kawa 0.7.2): the #1651/#1653 guards are described as shipped and now defense in depth. Their `content_length_invalid` counters stay at zero unless kawa regresses. ## Validation - `python3 .github/scripts/check_doc_citations.py --self-test` → exit 0 - `python3 .github/scripts/check_doc_citations.py --root .` → exit 0 (54 line citations, 794 test names, 15 pinned blocks) - `python3 .github/scripts/check_doc_citations.py --root . --base origin/main` → exit 0 ("none of the 87 cited lines compared against f5136d6 changed their text") - `python3 .github/scripts/check_doc_citations.py --audit --root .` → exit 0. It reports 3 advisory findings, all in files this PR does not touch (`doc/configure_admin_ops.md`, `lib/src/protocol/proxy_protocol/LIFECYCLE.md`). - `cargo +nightly fmt --all -- --check` → exit 0 - `cargo build --locked` → exit 0 - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` → exit 0 - Relative markdown links in the touched files were checked with a script: 0 broken. CI has no markdown link checker. 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 #1571
What
H2Shell::write_streamsbuilt a freshVec<IoSlice<'static>>on every write pass. The first descriptorh2_transmit::gatherpushed allocated it, and the pass freed it on return. Every transmitting pass therefore cost one heap allocation, and every response at least one.The vector is now a private
io_slicesfield ofH2Shell, reused for the connection's lifetime. The production change is three touches inlib/src/protocol/mux/h2.rs: the field, its one construction site, and the three statements in theTransmitarm that now nameself.io_slices.Safety argument (unchanged window, no new
unsafe)gatherclears it on entry andconfirmclears it beforeKawa::consume.returnbetween those two calls. The only thing entered while the descriptors are live issocket_write_vectored, which cannot retain them.IoSlicehas noDrop). The nextgatherclears them before anything could read them.write_streams, so the bracket still cannot be split from outside the crate.The narration in
h2.rs,h2_transmit.rs,h2_write_pass.rs,sim/tests/h2_simulation.rsanddoc/h2_mux_internals.mdnow says this.Test allocator
The test uses the shared per-thread counter
crate::test_allocationsthat #1565 added tolib/src/lib.rs. There is still exactly one#[global_allocator]underlib/src.Measurements
Unit test
a_warm_write_pass_allocates_nothingcounts the allocations of one warmwrite_streamspass that transmits two blocks through a loopback socket:cargo test --releasecargo test(debug)The remaining debug allocation is the
format!infinalize_write's#[cfg(debug_assertions)]Quiescearm. It does not exist in release, and the test accounts for it explicitly.To see the test fail, restore the per-pass local in
write_streams:left: 1, right: 0in release,left: 2, right: 1in debug.Release binary, built with
--no-default-features --features crypto-ring,opentelemetry,splice,simd(system malloc):python3 -m http.serverbackend, TLS H2 frontend.LD_PRELOADmalloc/calloc/realloc/memalign counter, read around each workload window.curl --http2connection (3 runs)intentrace -p <worker> --trace writev, 100 sequential connectionsintentrace -p <worker> --trace writev, 100 requests on one connectionThe
writev(2)count does not change: the change moves where the descriptors live, not how many go into each call. LOAD1 ranged 7.3–14.7 during the runs. These are counts, not timings, so the load does not skew them.Prior art
h20.4.15 writes through tokio-util'spoll_write_buf(h2/src/codec/framed_write.rs:142), which gathers into a stack[IoSlice; 64](tokio-util/src/util/poll_buf.rs:126-133).h2c->mbuf(src/mux_h2.c:5073) and sends each contiguous chunk with one stackstruct iovec(src/raw_sock.c:463-474).A stack array bound to the borrow of
kawacould remove the'staticrelabelling altogether. It would change the publich2_transmit::gathersignature, though, so it is left out of this PR, as the issue explains.Signed-off-by: Florentin Dubois [email protected]