Skip to content

perf(socket): stop reading on a short read instead of reading until EAGAIN - #1606

Merged
FlorentinDUBOIS merged 3 commits into
mainfrom
perf/stop-on-short-read
Sep 27, 2026
Merged

FlorentinDUBOIS merged 3 commits into
mainfrom
perf/stop-on-short-read

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1602

What

Every read path kept calling recv(2) until EAGAIN, even after a recv that returned fewer bytes than it was offered. On a stream socket that short read already proves the receive queue is empty, so the next recv could only answer EAGAIN.

  • tcp_socket_read now issues one read per call through a new private plain_socket_read, generic over Read (like rustls_socket_read) so tests count every recv. A short read answers (n, WouldBlock) — what the old loop answered one EAGAIN later. A read that fills the buffer is not a short read and answers Continue. The loop disappears, and so does its breaker counter socket.read.infinite_loop.error (removed from names.rs and doc/configure.md; operator-visible, noted in the CHANGELOG).
  • rustls_socket_read wraps the stream in a ShortReadProbe that records the length read_tls offered (rustls returns only the count, rustls-0.23.45/src/msgs/deframer/buffers.rs:208,220). After a short read the pass makes no second recv, but still processes and drains what arrived, and still reports a close_notify that arrived with it: that read_tls returns Ok(0) without touching the socket (rustls-0.23.45/src/conn.rs:768-770), so it stays allowed.
  • update_readiness_after_read (lib/src/protocol/mux/mod.rs) keeps READABLE after a short read once HUP was seen, so the next pass reads the EOF.

Why it is safe

  • A new edge comes for new data. mio registers every socket with EPOLLET (mio-1.2.3/src/sys/unix/selector/epoll.rs:130, EPOLLIN|EPOLLRDHUP at :133). man 7 epoll (man-pages 6.13): edge-triggered mode "delivers events only when changes occur on the monitored file descriptor, that is, an event will be generated upon each receipt of a chunk of data", and in the EPOLLET Q&A: "For stream-oriented files (e.g., pipe, FIFO, stream socket) ... if you call read(2) by asking to read a certain amount of data and read(2) returns a lower number of bytes, you can be sure of having exhausted the read I/O space for the file descriptor." after_a_short_read_new_bytes_raise_a_new_edge checks this on a real loopback socket registered with mio: short read, no pending event, new bytes raise a new READABLE event, and so does the FIN.
  • HUP already seen → read until EOF. A FIN coalesced with the data raised its edge already; sozu folds it into Ready::HUP (command/src/ready.rs, From<&mio::event::Event>), merged with |= (Mux::update_readiness). No later event will announce the EOF, hence the exception in update_readiness_after_read. It cannot spin: the next read either returns bytes or size == 0, which drops READABLE (pinned by a_short_read_after_hup_keeps_readable_to_read_the_eof, a_short_read_without_hup_drops_readable, an_empty_read_after_hup_still_drops_readable). Same rule as HAProxy (src/raw_sock.c: fd_cant_recv when ret < try, then goto read0 if FD_POLL_HUP) and tokio (clear_readiness when 0 < n < len, tokio-1.53.1/src/io/poll_evented.rs:211-213, keeping closed states, src/runtime/io/scheduled_io.rs:357-362). A short read drains every byte before the FIN, so no data is ever left behind; only the EOF observation moves to the next pass.
  • Other callers. They already handled (n > 0, WouldBlock) (it is what read-then-EAGAIN produced). The pipe records HUP in ConnectionStatus independently of any EOF read (Pipe::frontend_hup, Pipe::backend_hup), and closes through check_connections once flushed; ExpectProxyProtocol, the TLS handshake and the TCP preread close on HUP. Two comments (pipe.rs, tcp.rs) that said the tail was read "to EOF" are adjusted.
  • A full buffer is not a short read: a_full_plain_buffer_is_not_a_short_read, a_plain_body_ending_on_a_full_buffer_still_needs_its_eagain.

Honest limits

  • TCP urgent data (OOB). The "a short read empties the queue" guarantee does not hold while a TCP urgent mark is queued: recv stops before the mark with bytes behind it. Reproduced on a real socket: AAAA, send(B, MSG_OOB), CCCC raise one edge; tcp_socket_read answers (4, WouldBlock) with AAAA, no event follows for 300 ms, and CCCC stays in the kernel. A stream carrying OOB data (telnet, rlogin, FTP ABOR) can stall until the peer's next send. HAProxy and tokio behave the same, and sozu never read OOB data before either. Documented in the plain_socket_read doc-comment, doc/lifetime_of_a_session.md §2.2 and the CHANGELOG.
  • The three e2e close-delimited tests (test_h1_close_delimited_response_fully_delivered, test_h2_close_delimited_large_response, test_h2_large_h1_response_close_delimited) pass with and without the HUP exception — I removed it and ran them: 3 passed. They do not discriminate it (the FIN most likely arrives in a separate event there). The exception is pinned instead by data_and_fin_in_one_edge_keep_readable_until_the_eof_is_read: on a real loopback socket registered with mio, data and FIN share ONE (readable, read_closed) edge, the short read answers (4, WouldBlock), no event follows, READABLE survives update_readiness_after_read, and the next read answers (0, Closed). It fails with the exception removed ("HUP was seen: READABLE must stay so the EOF is read") and passes with it.
  • A pass does not remember a short read made by an earlier call, on purpose: an edge may have arrived in between and already been folded into the READABLE the mux kept. So the EAGAIN after a call whose buffer filled from the last short read's plaintext remains (a_large_body_over_tls_arrives_intact pins exactly 1). That is where most of the remaining H2 EAGAINs come from.

Tests

Red then green: with the fix reverted (loop restored in plain_socket_read, probe ignored in rustls, HUP exception removed), 9 of the 27 targeted tests fail; with it, all pass. close_notify_in_the_short_read_is_reported_in_the_same_call fails on the naive variant that skips every read_tls after a short read. New plain-path tests: short read (1 recv, 0 EAGAIN), full buffer, FIN behind a short read, fragmented message, 1 MiB body (65 reads, 0 EAGAIN). New rustls tests: close_notify in the short read, FIN behind a short read, 64 KiB body. Two existing rustls tests encode the old count and are updated to the lower one (a_large_buffer_drains_the_record_in_one_short_recv: 2 → 1 reads; a_fragmented_record_is_read_again_until_it_completes: 2 → 1 and 3 → 2).

Trade with #1603 (rebased on main 13269c5e)

#1603/#1605 closed an H1 backend in the same pass when its last bytes and EOF came back from one recv. With a short read that recv is no longer issued, so:

  • FIN in the kernel before epoll_wait returned: the edge carries HUP, the backend is still closed in the same pass;
  • FIN landing after epoll_wait returned (READABLE without HUP): the backend is closed one epoll_wait round later, on the EPOLLRDHUP edge the FIN queued — and no later: that edge is already pending when the pass ends.

That is HAProxy's choice (src/raw_sock.c:315-338: stop on ret < try, let the poller report the EOF). The saved recv answers EAGAIN on every short read not followed by a FIN. Documented in the CHANGELOG, doc/lifetime_of_a_session.md §2.2 and the ConnectionH1::readable comment.

The #1605 tests were rewritten, not removed or weakened (commit 206a47b1, each referencing #1606 and HAProxy):

  • an_h1_backend_eof_read_records_hup_and_a_frontend_one_does_not keeps every assertion; the EOF is now met by the second readable, which records HUP on the backend and not on the frontend. Red when the HUP insertion in h1.rs is removed.
  • a_backend_eof_read_with_its_last_bytes_closes_the_backend_in_the_same_pass covers the coalesced edge (READABLE|HUP), closed in the same pass. Red when is_hup() is dropped from dead.
  • new a_fin_after_epoll_wait_closes_the_backend_on_the_next_round_at_the_latest, real loopback socket + mio: not closed in the first pass, RDHUP edge returned by a zero-timeout poll, closed on that round.

Note: the two intermediate commits of this branch do not pass those two #1605 tests; the branch head does. Squash-merge keeps main bisectable.

Measurement

Release builds of main 13269c5e (with #1605) and this branch, one worker, loopback, python backend that closes after each response (the #1605 scenario), 20 requests per scenario, LOAD1 < 2.

Syscalls per request:

scenario tool total recv/recvfrom EAGAIN (run) epoll_wait
H1 fdtrace 20.35 → 18.65 4.45 → 2.30 31 → 0 5.60 → 5.95
H1 intentrace 20.65 → 18.85 4.00 → 2.00 n/a 4.55 → 4.75
H2 fdtrace 35.25 → 34.35 10.70 → 9.45 88 → 68 8.45 → 8.65
H2 intentrace 42.10 → 41.05 6.00 → 5.00 n/a 4.95 → 4.90
H2 mux (1 conn) fdtrace 15.95 → 14.70 5.35 → 4.00 34 → 23 3.90 → 4.05
H2 mux (1 conn) intentrace 16.45 → 15.45 4.10 → 3.10 n/a 3.10 → 3.10

The total drops in every scenario; epoll_wait rises slightly in H1 (the extra round above). intentrace does not decode recvfrom results, so the EAGAIN split comes from fdtrace. The first measurement against f165a3dc (before #1605): H1 recv 114 → 58, H2 236 → 171, multiplexed 136 → 84.

Also

  • The FrontRustls::peer_addr comment still described HttpsSession::new seeding the peer with sock.peer_addr().ok(); since perf(server): reuse the accept(2) peer address and set TCP_NODELAY on the listener #1593 it uses the address accept(2) returned. Corrected.
  • doc/lifetime_of_a_session.md §2.2 and doc/h2_mux_internals.md describe the short-read stop; the mux LIFECYCLE.md and doc/testing.md citations shifted by the new lines in mux/mod.rs are re-anchored to the same text.

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

…AGAIN

A stream socket that answers fewer bytes than it was offered has emptied
its receive queue (man 7 epoll), so the recv(2) every read path issued
next could only answer EAGAIN.

- tcp_socket_read issues one read per call through a new private
  plain_socket_read, generic over Read so tests count every recv. A
  short read answers (n, WouldBlock); a read that fills the buffer is
  not a short read and answers Continue. The loop and its breaker go,
  and with them the socket.read.infinite_loop.error counter.
- rustls_socket_read observes the length read_tls offered through a
  ShortReadProbe adapter and makes no second recv in a pass after a
  short one. It still processes and drains what arrived, and still
  reports a close_notify that arrived with it, since that read_tls
  touches no socket.
- mio is edge-triggered, so bytes arriving after the short read raise
  the next event. A FIN that arrived with the data raised its edge
  already (HUP), so update_readiness_after_read keeps READABLE after a
  short read once HUP was seen and the next pass reads the EOF, as
  HAProxy (read0 on FD_POLL_HUP) and tokio (sticky closed readiness) do.

Measured on release builds, 20 requests per scenario, fdtrace: H1 recv
114 -> 58 (EAGAIN 51 -> 0), H2 236 -> 171 (EAGAIN 103 -> 66), 20
requests multiplexed on one H2 connection 136 -> 84 (EAGAIN 50 -> 23).

Also corrects the FrontRustls::peer_addr comment that still described
HttpsSession::new seeding the peer from getpeername(2), and re-anchors
the mux LIFECYCLE and testing citations the new lines in mux/mod.rs
shifted.

Closes #1602

Signed-off-by: Florentin Dubois <[email protected]>
…N case

A short read does not prove the receive queue empty while a TCP urgent
(out-of-band) mark is pending: recv stops before the mark with bytes
queued behind it, and no further edge comes. A stream carrying OOB data
(telnet, rlogin, FTP ABOR) can stall until the peer's next send, as it
does under HAProxy and tokio. State the limit in the plain_socket_read
doc-comment, in doc/lifetime_of_a_session.md and in the CHANGELOG.

Add data_and_fin_in_one_edge_keep_readable_until_the_eof_is_read: on a
real loopback socket registered with mio, the data and the FIN share one
edge; the short read answers (4, WouldBlock), no further event comes,
and READABLE must survive update_readiness_after_read so the next pass
reads (0, Closed). It fails without the HUP exception.

Signed-off-by: Florentin Dubois <[email protected]>
…ract

Since a read stops on a short read, the last bytes and the EOF of a
backend no longer come back from one recv. This is HAProxy's trade
(src/raw_sock.c: stop on ret < try, let the poller report the EOF): a
backend whose FIN lands after the epoll_wait that woke the pass is
closed one epoll_wait round later, on the EPOLLRDHUP edge the FIN
queued; when the FIN reached the kernel first, the edge carries HUP and
the backend is still closed in the same pass.

- an_h1_backend_eof_read_records_hup_and_a_frontend_one_does_not keeps
  every assertion; the EOF is met by the second readable, which records
  HUP on the backend and not on the frontend.
- a_backend_eof_read_with_its_last_bytes_closes_the_backend_in_the_same_pass
  now covers the coalesced edge (READABLE and HUP) and still closes in
  the same pass.
- a_fin_after_epoll_wait_closes_the_backend_on_the_next_round_at_the_latest
  pins the other case on a real loopback socket with mio: not closed in
  the first pass, the RDHUP edge already pending (zero-timeout poll),
  and closed on that round.

The ConnectionH1::readable comment, the CHANGELOG and
doc/lifetime_of_a_session.md state the trade and the measurement
against main 13269c5; the h1.rs citations it shifted are re-anchored.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 7c820e5 into main Sep 27, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the perf/stop-on-short-read branch September 27, 2026 02:08
FlorentinDUBOIS added a commit that referenced this pull request Sep 27, 2026
…rite (#1608)

Closes #1607

## What changes

Closing an H2 frontend over TLS on its final GOAWAY cost two `writev(2)` back to back, in the same pass:

```
recv    fd=16 ret=48            <- the client's GOAWAY
writev  fd=16 ret=39 len=39     <- our GOAWAY: H2Shell::flush_zero_to_socket -> FrontRustls::socket_write -> write_tls
writev  fd=16 ret=24 len=24     <- close_notify: H2Shell::close -> drain_tls_close_notify -> write_tls
close
```

`FrontRustls::socket_write` runs `write_tls` right after handing rustls the plaintext, so the GOAWAY is on the wire before anyone can queue the alert behind it.

- New `SocketHandler::socket_write_then_close(buf)`. Default body: `socket_write`, then `socket_close` if the whole of `buf` was taken, which is what every other handler did already. `FrontRustls` overrides it: `writer().write(buf)`, then `send_close_notify()` only if all of `buf` was absorbed, then one `write_tls`, which rustls turns into one `write_vectored` over both records (`rustls-0.23.45/src/vecbuf.rs`, `ChunkVecBuffer::write_to`).
- `H2Shell::flush_zero_to_socket` uses it when `ConnectionH2::zero_flush_closes_connection()` holds: `Position::Server`, `H2State::GoAway` (only `goaway()` sets it, after serialising the final GOAWAY), `expect_write == Some(Zero)` (the zero-buffer resume, not a GOAWAY deferred behind a half-written stream frame, nor a WINDOW_UPDATE/RST_STREAM batch), no stream, no pending WINDOW_UPDATE or RST_STREAM, `close_notify_sent` unset. The writable arm of `GoAway` then closes; `H2Shell::close` finds nothing left to drain. `close_notify_sent` is set once the whole buffer was taken, so neither `initiate_close_notify` nor `drain_tls_close_notify` queues a second alert.

The `close_notify` stays mandatory (RFC 8446 §6.1) and still follows the GOAWAY on the wire; only the number of writes changes. rustls encrypts application data straight into its send buffer once the handshake is over, which it always is on a connection the mux drives, so the alert queued after the plaintext is the next record.

HAProxy (`0ceb8c65f`) keeps two writes on this path: `h2c_send_goaway_error` (`src/mux_h2.c:2504`) puts the GOAWAY in the mux buffer, the timeout path flushes it with `xprt->snd_buf` (`src/mux_h2.c:5540-5548`), and `h2_release` (`src/mux_h2.c:1607`) then calls `conn_xprt_shutw` (`src/mux_h2.c:1658`), whose `ssl_sock_shutw` (`src/ssl_sock.c:8001`) issues its own `SSL_shutdown` (`src/ssl_sock.c:8041`). There is no `h2_shutw` in that tree: `h2_do_shutw` (`src/mux_h2.c:5963`) and `h2_shut` (`src/mux_h2.c:6090`) handle a stream, not the connection.

## Measurements

Release build, one worker, python `http.server` backend, 20 sequential `curl --http2` requests each on its own TLS connection, LOAD1 < 8, `b19d94f8` before, this branch after. fdtrace = `LD_PRELOAD` fd tracer; intentrace = `intentrace -p`, ANSI stripped, anchored on the syscall name.

Initial measurement on `b19d94f8`: fdtrace `writev` 6.90/conn, `epoll_wait` 8.00/conn, total 33.80/conn; intentrace `writev` 6.00, `epoll_wait` 5.00, total 42.10.

| per 20 connections / per connection | before (4 fdtrace runs) | after (3 fdtrace runs) |
|---|---|---|
| close writes (`len=39`, `len=24`, `len=63`) | 35–40 | 20 |
| merged `len=63` writes | 0 | 17–19 |
| `writev` / conn | 6.85–7.15 | 6.05–6.30 |
| `epoll_wait` / conn | 8.00–8.30 | 8.00–8.40 |
| intentrace `writev` / conn | 6.00 (2 runs) | 6.00 |

The connections without a merged write closed on the client's HUP (`ev=5:2005`) before any GOAWAY was read: sozu sends the 24-byte alert alone there, before and after. Under `intentrace -p` every connection takes that path (`wrote 39 Bytes`: 0 on all three runs, `wrote 24 Bytes`: 20), because ptrace slows the worker enough for curl's GOAWAY, `close_notify` and FIN to all be queued when it wakes; so intentrace cannot see this change. `writev` also varies with how the response split (181 + 70 against 229, on 0 to 6 connections per run).

## H2 backends: nothing done for the EOF-as-HUP of #1605

#1605 records a backend EOF read with the last bytes as HUP for H1 backends. For H2 backends there is nothing measurable to gain, with or without #1606:

- A graceful backend close (GOAWAY, then FIN) never reads the EOF: `handle_goaway_frame` calls `goaway()`, which clears `expect_read`, and `ConnectionH2::force_disconnect`'s `Position::Client` arm sets `readiness.event = Ready::HUP` itself, so the backend is closed in the same pass.
- H2 reads are exact-sized (`H2ReadTarget::Fill { amount }`: 9 header bytes, then the payload). #1606's `plain_socket_read` answers `Continue` when `sz == buf.len()`, so a complete frame is not a short read and the next header read meets `(0, Closed)` in the same pass, exactly as on `main`. #1606 moves nothing here.
- What remains is a FIN without GOAWAY landing between the `epoll_wait` and the `recv`: at most one `epoll_wait` per backend H2 connection, never per request, and not measurable with an H1 backend.

## Tests (seen red first)

`the_final_goaway_and_close_notify_leave_in_one_tls_write` (`h2.rs`): over a real `FrontRustls` on a loopback socket, drives `goaway(NoError)`, the `writable` pass (which must answer `CloseSession`) and `close`, and counts every `write_tls` holding a record (`crate::socket::tls_writes`, a `#[cfg(test)]` thread-local counter in the new `flush_tls` helper every `FrontRustls` write goes through). Then it reads the wire raw and checks the records in order (39 bytes, then 24), and decrypts them: the 17-byte GOAWAY with `NO_ERROR`, then a clean end of stream, which rustls reports only after `close_notify`.

- Red with the `zero_flush_closes_connection` branch dropped: `left: 2, right: 1` on the write count.
- Red with `send_close_notify` queued before `writer().write`: records `[24, 39]`.

## Checks

`cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd`, `cargo +nightly fmt --all -- --check`, clippy with the same features `--all-targets -- -D warnings`, tests for `sozu-lib` (1217 passed), `sozu`, `sozu-command-lib`, `sozu-e2e -- --skip tests::fuzz_tests::` (449 passed), `sozu-sim` test and clippy under `--cfg tokio_unstable`, `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked`, and `check_doc_citations.py` (`--self-test`, `--root .`, `--base b19d94f…`, `--audit --root .`): all exit 0. 14 line citations in `doc/` and `LIFECYCLE.md` re-anchored to the same text in the same function.

Rebase note for #1606: this branch touches `socket.rs` on the write side only (`flush_tls` at the five `write_tls` sites, the trait method, the `FrontRustls` override); its hunks start at old lines 65, 582, 931, 972, 1124, 1157, 1192 and 1249, none overlapping #1606's (192, 608–733 on the read path, 1263). `mux/mod.rs` is untouched.

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 27, 2026
…it record reads (#1611)

Closes #1609

## Causes (established, not guessed)

Every `recv` on the frontend socket was captured with backtraces (`LD_PRELOAD` fd tracer, release build of `b74d5d97`) and symbolized with `addr2line`. The EAGAIN `recv`s fall into three call sites, told apart by their frames:

| site | frames | H2, 20 connections (3 runs) | multiplexed, 20 requests (3 runs) |
|---|---|---|---|
| handshake loop | `rustls.rs:159` ← `TlsHandshake::readable` | 30–33 | 1–2 |
| read forced at upgrade | `socket.rs:857` ← `h2.rs:8354` ← `mux/mod.rs:2307` ← `https.rs:1128` (the `self.ready()` re-entered after `upgrade()`) | 20 (one per connection) | 1 |
| between two calls | same, but ← `https.rs:1122` (normal event path) | 5–9 | 19 |

1. **Handshake.** `read_tls` ran until `WouldBlock`. A TLS 1.3 server `wants_read()` again as soon as its flight is queued (`rustls-0.23.45/src/common_state.rs:674-684`), so both the ClientHello (1575 bytes) and the client `Finished` (80 bytes) were followed by an EAGAIN.
2. **Upgrade.** `upgrade_handshake` inserted `READABLE | WRITABLE` into the new mux frontend without looking at the socket, right after the handshake got EAGAIN on it. That is a read with no event.
3. **Between two calls.** This is the one #1606 kept on purpose. The H2 path reads a 9-byte header, then its payload, one `socket_read` per call. Take an 88-byte record: call 1 reads it with a short `recv` and returns `Continue`, because its buffer is full and plaintext remains. Call 2 is served from plaintext. Call 3 finds the plaintext empty, and since `drained` was a local, it issues another `recv`, which answers EAGAIN. The trace shows no `epoll_wait` between the short `recv` and the EAGAIN.

## Changes

- `handshake_read` (`lib/src/protocol/rustls.rs`) is generic over `Read`. It wraps the stream in the **existing** `ShortReadProbe` (now `pub(crate)`, with `new`/`was_short`, not duplicated) and stops on a short read, dropping READABLE, the same way EAGAIN does.
- `upgraded_frontend_events` (`lib/src/https.rs`):
  - WRITABLE is always set.
  - READABLE is set only if the handshake still held a READABLE edge, or if `!wants_read()`, meaning rustls holds plaintext (an H2 preface that shared a segment with the `Finished`) or a `close_notify`.
  - The `event.insert(READABLE)` in the handshake's `Upgrade` branch is removed, because it defeated this check.
- `RecvMemory` in `FrontRustls` (`lib/src/socket.rs`):
  - It records "a `recv` answered short or EAGAIN, and no event has been delivered since". It seeds `drained` in `rustls_socket_read`, so a later call serves the plaintext and then answers `WouldBlock` without a `recv`.
  - `HttpsSession::update_readiness` clears it for every event on the frontend token, in every state (Mux and WebSocket/Pipe). That is the only path events take into a session (`server.rs:3943`).
  - HUP or ERROR turns it off for good.
  - At the upgrade it is seeded from what the handshake proved.
  - Two short accessors are added: `Connection::socket_handler_mut` and `Pipe::front_socket_handler_mut`.

## Why it is safe

- **Same contract as #1606.** mio is edge-triggered (`EPOLLET`), and "an event will be generated upon each receipt of a chunk of data" (`man 7 epoll`). A byte that arrives after the proof raises an event. Either that event is still pending in epoll, and the next `epoll_wait` delivers it and re-arms READABLE, or it has already been delivered, which cleared the memory. The memory is cleared on delivery rather than inferred from READABLE: a delivery that lands while the mux still holds READABLE is invisible to the mux.
- **HUP already seen ⇒ read to EOF.** A FIN that came with the data is delivered as HUP, which turns the memory off, so the next call reads the EOF (`update_readiness_after_read`). The handshake closes on HUP before reading anything (`TlsHandshake::ready`), so it needs no exception.
- **The handshake never blocks.** A ClientHello split across several segments completes. Each short read drops READABLE, no event is left pending, and the next segment raises the edge. This is pinned on a real loopback socket with mio.
- **OOB caveat (unchanged).** `recv` stops before a TCP urgent mark even when bytes are queued behind it. A peer that sends OOB data stalls until its next send, in the handshake as in the established session since #1606. TLS never uses urgent data, and HAProxy and tokio behave the same way.

## Prior art

- HAProxy: `ssl_sock_handshake` (`src/ssl_sock.c:6462`) returns on `SSL_ERROR_WANT_READ` and subscribes for the next receive (`src/ssl_sock.c:6676-6682`). Its BIO (`ha_ssl_read`, `src/ssl_sock.c:372`) reads through `raw_sock_to_buf`, which stops on `ret < try` (`src/raw_sock.c:315-317`).
- tokio-rustls: `MidHandshake::poll` (`tokio-rustls-0.26.4/src/common/handshake.rs:89-91`) loops `handshake()`, which calls `read_tls` until `Pending` (`src/common/mod.rs:161-170`). That `Pending` costs no `recv` after a short read, because tokio clears readiness when `0 < n < len` (`tokio-1.53.1/src/io/poll_evented.rs:211-213`).

## Measurement

Release builds of `b74d5d97` and this branch, `crypto-ring,opentelemetry,splice,simd`, one worker, loopback python backend, 20 requests per pass, three passes per cell, LOAD1 < 3.

| scenario | tool | total per conn/req | `recv` | EAGAIN (per 20) | `epoll_wait` |
|---|---|---|---|---|---|
| H2, 1 conn/request | fdtrace | 31.75–32.90 → 29.45–30.15 | 8.65–9.35 → 5.65–6.05 | 56–60 → **0** | 8.05–8.20 → 8.60–8.85 |
| H2, 1 conn/request | intentrace | 41.00–41.05 → 41.00–41.10 | 5.00 → 4.00 | n/a | 4.90–4.95 → 5.90–6.00 |
| H2 multiplexed | fdtrace | 14.85–15.00 → 13.70–14.30 | 3.95–4.15 → 2.90–3.15 | 21–22 → **0** | 4.05–4.25 → 4.10–4.30 |
| H2 multiplexed | intentrace | 15.45 → 14.50 | 3.10 → 2.10 | n/a | 3.10 → 3.15 |

`intentrace` output is stripped of ANSI codes and counted on the syscall name. The intentrace total for one connection per request does not move. Under ptrace the worker is slow enough that the client's next flight lands during the pass. The removed `recv` then found data instead of EAGAIN, and an `epoll_wait` now collects it: this is the same trade #1606 made. With the lighter fd tracer the saving is about 2.5 syscalls per connection. Without a tracer, and on a real network where the round trip is far longer than one pass, the removed `recv` answers EAGAIN.

## Tests (each seen red, then green)

- `a_short_handshake_read_stops_without_an_eagain`, `a_full_handshake_read_reads_again` (ClientHello padded past 4096 bytes: one full read, then one short) and `a_client_hello_in_three_segments_completes_on_a_loopback_socket` (real socket + mio). All three are red with the probe check disabled and the forced `event.insert(READABLE)` restored.
- `the_upgraded_frontend_reads_only_when_a_read_is_due`: red against an unconditional `READABLE | WRITABLE`.
- `frames_sharing_one_record_cost_one_recv` (formerly `…_plus_the_final_eagain`, 2 → 1 reads, 0 EAGAIN), `an_event_after_a_short_read_lets_the_next_call_read` and `a_hup_delivered_after_a_short_read_lets_the_next_call_read_the_eof`. Each guard was removed in turn:
  - memory seed off: 3 red;
  - clear-on-event off: 3 red;
  - HUP guard off: 2 red;
  - `event_delivered` emptied: 6 red.
- Existing socket tests that add bytes, or a FIN, between two calls now deliver the event those bytes raise, which is what the event loop does. `a_large_body_over_tls_arrives_intact` now pins 0 EAGAIN instead of 1. No assertion was loosened.

## Docs

- `CHANGELOG.md`.
- `doc/lifetime_of_a_session.md` §2.2 and §4.
- `doc/h2_mux_internals.md`.
- Citations shifted by the `https.rs` additions are re-anchored to the same text: `doc/configure_admin_ops.md`, `doc/lifetime_of_a_session.md`, `lib/src/protocol/kawa_h1/LIFECYCLE.md`.

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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(socket): stop reading on a short read instead of reading until EAGAIN

1 participant