Repository navigation
perf(udp): stop cloning the mio registry on every event-loop turn - #1553
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 26, 2026 10:28
FlorentinDUBOIS
force-pushed
the
perf/fd-lifecycle
branch
from
September 26, 2026 11:34
41642fb to
2a8f574
Compare
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 26, 2026
…EL (#1568) Closes #1567 When a session closes, sozu sent `EPOLL_CTL_DEL` for the front socket (`HttpSession::close`, `HttpsSession::close`) and for each backend socket (`Mux::close`, and the dead-backend sweep in `Mux::ready`), each immediately before that socket's `close(2)`. Linux removes a file from every epoll set on its last close, so these calls removed nothing the close would not. This PR drops those four call sites and leaves the removal to `close(2)`. ## Measured Release worker (`--no-default-features --features crypto-ring,opentelemetry,splice,simd`), `worker_count = 1`, backend `python3 -m http.server`, `curl` N=20 sequential requests. Same config and scenario on both sides; only the binary differs. | per request | H1 before | H1 after | H2 before | H2 after | |---|---|---|---|---| | `epoll_ctl` (intentrace -p) | 4.00 | **2.00** | 4.00 | **2.00** | | `epoll_ctl` (LD_PRELOAD interposer) | 4.00 (40 ADD + 40 DEL) | **2.00** (40 ADD) | 4.00 (40 ADD + 40 DEL) | **2.00** (40 ADD) | | `close` / `shutdown` / `accept4` / `socket` / `connect` on sockets | 2 / 2 / 2 / 1 / 1 | unchanged | 2 / 2 / 2 / 1 / 1 | unchanged | The two instruments agree on the aligned window. LOAD1 was 8.41 and 11.90 during the before passes, 4.35 and 4.29 during the after passes. Leak check: the worker's `/proc/<pid>/fd` count was 15 before and 15 after 1000 more requests, on H1 and on H2, all 1000 answered 200. The `close`, `epoll_wait` and `fcntl(F_DUPFD_CLOEXEC)` counts on the epoll fd are the `UdpProxy::health_poll` registry clone that #1553 fixes. They are out of scope here and unchanged. ## Why it is safe The one risk: a socket that is closed but still open through a duplicate stays in the epoll set, and can report events under a slab token already given to a new session. That cannot happen here: - **No duplicate of a session socket exists.** The tree has no `dup` or `try_clone` of a front or back socket. The `try_clone` calls in `Server::new` clone the mio `Registry`, which is the epoll fd, not a watched fd. The splice path uses its own pipes. SCM_RIGHTS (`command/src/scm_socket.rs`) carries listeners only. Workers never fork; forks happen in the main process (`fork_main_into_worker`, `bin/src/upgrade.rs`), which holds no session socket. - **Each socket closes before the next `epoll_wait`.** `shut_down_sessions_by_frontend_tokens` is the only caller of `ProxySession::close`. It removes the session from the slab, calls `close()`, and drops the last `Rc` on the spot; the other holders are stack locals. The dead-backend sweep drops its `Connection` at the end of its block. Backend connections are per session. - **mio keeps no state that needs the deregister.** In mio 1.2.3, epoll and kqueue use `stateless_io_source.rs` ("Both `kqueue(2)` and `epoll(2)` don't need to hold any user space state"). `Selector::deregister` is a bare `epoll_ctl(EPOLL_CTL_DEL)`, and `IoSource` has no `Drop` that relies on it. BSD also drops an fd's kevents on close. - **In-tree precedent.** A WebSocket session's backend socket has never been deregistered: `Pipe::close` (`lib/src/protocol/pipe.rs`) only adjusts `active_requests`, and nothing in `pipe.rs` calls `deregister`, so that socket has always relied on `close(2)` alone. - **Prior art.** HAProxy's epoll poller issues `EPOLL_CTL_DEL` on close only for `FD_CLONED` descriptors, i.e. ones shared across processes (`src/ev_epoll.c`, `__fd_clo`), and leaves every other fd to `close()`. tokio deregisters in `PollEvented::drop` because a general-purpose library cannot rule out duplicates, and because its driver must free its own `ScheduledIo` slot (`runtime/io/driver.rs`, `deregister_source`). Sockets that outlive the session are untouched: WebSocket upgrade, keep-alive backend reuse, the `register_socket` rollback, listener soft/hard stop, TCP proxy and health checks all keep their current code. ## Change - `lib/src/http.rs`, `lib/src/https.rs`: drop the front-socket deregister in `close`, plus the imports it used. - `lib/src/protocol/mux/mod.rs`: drop the backend-socket deregister in `Mux::close` and in the dead-backend sweep. - `L7Proxy::deregister_socket` stays in the public trait, now without a caller. Removing it would change the contract; left as a follow-up. - `doc/lifetime_of_a_session.md` §9 now states the argument; the CHANGELOG has an entry. Doc citations shifted by the removed lines are re-anchored to the same text (`check_doc_citations.py --base` green). ## Tests `closed_sessions_leave_their_sockets_to_close` (`lib/src/http.rs`, front) and `close_leaves_backend_sockets_to_their_last_close` (`lib/src/protocol/mux/mod.rs`, backend) read the kernel's epoll table from `/proc/self/fdinfo`. Each asserts that after `close()` the socket is still watched (no DEL issued), then that once its owner drops it is gone (the close removed it, with no leak and no duplicate). Both were seen red with the deregister put back ("must not deregister … it is about to close"), and green without it. ## Commands run - `cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd` — ok - `cargo +nightly fmt --all -- --check` — ok - `cargo clippy --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd --all-targets -- -D warnings` — ok - `cargo test --locked … -p sozu-lib` — 1160 passed; `-p sozu` — ok; `cargo test --locked -p sozu-command-lib` — 175 passed (that crate has none of the four features) - `cargo test --locked -p sozu-e2e -- --skip tests::fuzz_tests::` — 449 passed - `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim` and `cargo clippy -p sozu-sim --all-targets -- -D warnings` — ok - `check_doc_citations.py` `--self-test`, `--root .`, `--base d2d4bbd…`, `--audit --root .` — ok - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` — ok No protocol, wire, config, metric or log change. The only log lines removed are the `error!` for a failed deregister, which can no longer happen. Signed-off-by: Florentin Dubois <[email protected]>
`UdpProxy::health_poll`, called once per `Server::run` turn, cloned the worker's `Registry` before driving the UDP health prober. `try_clone` is an `fcntl(F_DUPFD_CLOEXEC)` of the epoll descriptor and dropping the clone a `close`, so every turn paid two syscalls, with or without a UDP cluster. The prober now borrows the registry the proxy already owns. Release build, one worker, python http.server backend, 20 sequential curl requests, counted by an LD_PRELOAD interposer and cross-checked by `intentrace -p` on the same window: H1 close 7.00 -> 2.00/req, fcntl 5.00 -> 0.00/req H2 close 8.10 -> 2.00/req, fcntl 6.10 -> 0.00/req Every removed close targeted an anon_inode:[eventpoll] duplicate, one per epoll_wait. No allocation is added. The clone also skipped the prober silently when the worker was out of descriptors (EMFILE). The new integration test exhausts the descriptor table and asserts a timed-out probe is still recorded; with the clone restored it fails with `left: 0, right: 1`. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
perf/fd-lifecycle
branch
from
September 26, 2026 14:29
2a8f574 to
7e05de3
Compare
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.
What
UdpProxy::health_poll(lib/src/udp.rs) is called byServer::runonce per event-loop turn. It cloned the worker's mioRegistrybefore driving the UDP health prober.Registry::try_cloneis anfcntl(F_DUPFD_CLOEXEC)of the epoll descriptor, and dropping the clone is aclose. So every turn paid two syscalls, whether or not a UDP cluster exists, because the prober's own "nothing configured" early return (UdpHealthChecker::poll) runs after the clone.The prober now borrows
self.registrydirectly: the fields are disjoint andpolltakes&Registrywithout keeping it. The change is one line. It adds no allocation.This came out of attributing sōzu's per-request
closecount, which looked too high: about 7 per H1 request for a request that opens 2 sockets. Resolving everycloseto what it closed showed the patternclose/req = 2 + epoll_wait/req. The 2 are the client and backend sockets. Every otherclosetargeted ananon_inode:[eventpoll]that had just been duplicated from the worker's epoll fd, and all of them came from this call site.Measured, before and after
Same setup on both sides: release build (
--no-default-features --features crypto-ring,opentelemetry,splice,simd),worker_count = 1, access log to stdout,python3 -m http.serverbackend, N = 20 sequentialcurlrequests, every response checked200with the expected HTTP version. The worker is the onlypgrep -P <master>child. The window is the trace lines between a snapshot taken just before and just after the 20 requests. Counts are per request (total / 20).closefcntlepoll_waitepoll_ctl/shutdown/accept4Machine load (
LOAD1) was 4.5 / 4.05 before and 6.9 / 6.2 after. Syscall counts do not depend on load, butepoll_waitper request does. Two H2 runs taken atLOAD112–19 both keptclose = 40 + epoll_waiton the old binary andclose = 40on the new one.Two independent instruments, one window. Each pass ran an
LD_PRELOADinterposer andintentrace -p <worker>at the same time. The interposer makes every real call through rawsyscall(2), resolves each fd through/proc/self/fdbefore closing it, and records errno. Before use it was checked against a known C case (11 closes including oneEBADF, a pipe, a file plus itsdup, an eventfd, a timerfd,accept4EAGAIN,epoll_ctlADD/MOD/DEL, and afork) and against RustdropofTcpStream/File. Over the aligned stretch (firstaccept4→ last socketclose), the two instruments agree on every count forclose,epoll_wait,epoll_ctl,shutdown,accept4,fcntl,socketandconnect, in all six passes. The interposer, which reads the value the program actually got back, saw no failedclosein any pass. On one H2 "after" pass, intentrace printedENOSYSfor 24 of the 40 socketclosecalls, and for 168 calls in total, while the interposer sawret=0on every one of those closes. That is intentrace misreading the return register underptrace, not a failure: the counts still match.Also fixed: silent loss of UDP health probing on
EMFILEWhen the worker had no free descriptor,
try_clonefailed andif let Ok(..)skipped the prober with nothing logged. An in-flight probe was never timed out and its backend's health was never updated.Tests
lib/tests/udp_health_descriptor_exhaustion.rshas one test, in its own integration binary because it lowersRLIMIT_NOFILEfor the whole process. It starts a TCP probe against a listener that never accepts, waits past the one-second probe timeout, fills every descriptor slot untilEMFILE, callshealth_poll, and asserts that the timed-out probe was recorded as a failure.Seen red: with the clone restored, it fails with
left: 0, right: 1("health_poll skipped the prober when no descriptor was free"). With the fix it passes. The test cannot observe the syscall count itself: a dup that is closed again right away leaves no trace. The before/after measurement above is the evidence for the count.Protocol / security impact
None. No wire format, configuration key, public API or dependency changes. The borrow replaces a clone that pointed to the same epoll instance.
Commands run (all exit 0)
cargo +nightly fmt --all -- --checkcargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simdcargo clippy --all-targets --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -- -D warningsRUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --lockedcargo test -p sozu-command-lib --locked;cargo test -p sozu-lib|sozu --locked <flags>;cargo test -p sozu-e2e --locked <flags> -- --skip tests::fuzz_tests::RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --lockedand itsclippy --all-targets -- -D warningscheck_doc_citations.py --self-test,--root .,--base f7491559,--audit --root .Docs:
CHANGELOG.md(🔄 Changed),lib/src/protocol/udp/LIFECYCLE.md§10.Signed-off-by: Florentin Dubois [email protected]