Skip to content

fix(tcp): connect-timeout accounting, expect-proxy timer, SNI preread, PROXY half-close and relay source fixes - #1934

Merged
FlorentinDUBOIS merged 8 commits into
mainfrom
fix/tcp-proxy-session
Nov 20, 2026
Merged

FlorentinDUBOIS merged 8 commits into
mainfrom
fix/tcp-proxy-session

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Six defects in the TCP proxy session, one commit each, plus one commit that repairs a test's red recipe. The listener-removal socket leak is fixed separately in #1931.

A backend connect that timed out was never charged to its backend (accounting drift). The backend arm of TcpSession::timeout closed the session on connect_timeout but never reached TcpSession::fail_backend_connection, the only place that bumps Backend::failures, arms the retry policy and emits backend.connections.error and backend.down. A blackholed TCP backend never entered its back-off window, so every client routed to it waited the full connect_timeout. The timeout of a still-Connecting dial is now charged like a refused connection; a timer firing on an established backend is still an idle timeout and charges nothing.

A hang-up during the backend connect replayed the SNI route (race replay). After a ClientHello routed a session, a frontend HUP while the dial was still Connecting fed Input::FrontClosed into the already-decided preread core, which replayed Output::Routed: tcp.sni_preread.routed counted twice in release builds and a debug build aborted the worker on a debug_assert!. SniPreread::front_gone now closes the session without routing it a second time once a route has latched.

An expect-proxy pipe kept a clone of the session's frontend timer (resource leak, timer leak). The clone shared the wheel handle but not its entry, so the pipe could arm a second entry under the session token; when it fired first, the session's own entry could no longer be cancelled and later closed an unrelated TCP session that reused the slab key. The session now owns the only frontend timer and the pipe is built without one, as on every other TCP path.

A ClientHello and FIN in one event were metered as a silent health check (misleading signal). TcpSession::ready_inner honoured the HUP before reading, so a session whose hello was still queued in the kernel was closed with no routed or rejected.* count, and a last fragment arriving with the FIN was counted as rejected.front_closed. The pre-HUP drain that already ran for expect_proxy now also runs for an undecided SNI preread.

A request half-closed before the backend connect was dropped on PROXY clusters (teardown loss). On a relay or send (send_proxy = true) cluster, a client's request and FIN reported in one event closed the session in the PROXY state before anything was written to the backend. A relay session's pending header is now read first, and the HUP of a send session, or of a relay session with a parsed header, waits for the upgrade so the Pipe forwards the request and then closes.

A relay session was charged to the load balancer instead of the client its PROXY header names (accounting drift). A relay session dialed its backend on its first readiness event, before its inbound PROXY header was parsed, so TcpSession::effective_session_address fell back to the accepted peer: the per-IP and per-subnet slots, and the HRW, MAGLEV and shard_percent affinity keys, were derived from the upstream load balancer for every client behind it. A relay session now dials only once its header is parsed, through the attempt that follows the read that parses it, and the pre-HUP drain gives a header coalesced with the client's FIN its one dial attempt.

The TO SEE THIS RED recipe of a_backend_connect_timeout_is_charged_to_the_backend now names the statement to delete and the failure it produces, which was executed (comments only).

Each fix is recorded in CHANGELOG.md (Unreleased, Fixed); doc/configure.md, doc/lifetime_of_a_session.md, doc/rate-limit-design.md, bin/config.toml and the tcp_preread and proxy_protocol LIFECYCLE.md files follow the changes.

Behaviour changes

  • TCP connect timeouts now increment backend.connections.error and can mark a backend down (backend.down, a BackendDown event), with its back-off window.
  • On an SNI preread listener, hello-plus-FIN connections are now counted as routed or rejected.front_closed instead of closing silently; the session still closes and no backend is dialed.
  • On a send_proxy cluster, a bare connect and FIN (typically an L4 health check) now waits for the backend connect and sends that backend a PROXY header before closing, instead of closing a dialed connection with nothing written. The wait is bounded by connect_timeout and the frontend timeout.
  • On a relay cluster (send_proxy = true behind an expect_proxy listener), clients behind one load balancer are now counted and pinned per client, by their PROXY header's source address. The backend connect no longer overlaps the wait for the header, which can add up to one connect time to the start of each relayed session, and a relay connection that never completes a header (a bare health check, a slow or garbage client) no longer opens a backend connection. A LOCAL / AF_UNSPEC header still falls back to the peer.

Tests added

tcp::sni_routing_tests:

  • a_backend_connect_timeout_is_charged_to_the_backend
  • a_backend_idle_timeout_is_not_charged_to_the_backend
  • frontend_hup_after_route_with_pending_dial_does_not_replay_the_route
  • expect_proxy_pipe_leaves_no_orphan_frontend_timer_after_a_timeout
  • sni_preread_hello_and_fin_in_one_event_is_routed_not_a_silent_health_check
  • sni_preread_last_fragment_and_fin_in_one_event_is_routed_not_rejected
  • relay_proxy_protocol_half_close_before_backend_connect_forwards_the_request
  • send_proxy_protocol_half_close_before_backend_connect_forwards_the_request
  • relay_proxy_protocol_front_hup_while_connecting_waits_for_the_backend
  • send_proxy_protocol_front_hup_while_connecting_waits_for_the_backend
  • relay_proxy_protocol_half_close_without_any_byte_closes_at_once
  • relay_proxy_protocol_half_close_inside_the_header_closes_at_once
  • send_proxy_protocol_bare_half_close_delivers_only_the_header_then_closes
  • send_proxy_protocol_reset_while_connecting_closes_at_once
  • a_relay_proxy_protocol_session_is_charged_to_the_header_source_not_the_lb_peer

Each proving test fails without its fix and passes with it; the pair and guard tests pin the cases a fix must leave alone.

Validation

Run locally on the final tree with the pinned toolchain (Rust 1.93.1, rustfmt from nightly), with CARGO_PROFILE_DEV_DEBUG=0:

  • cargo +nightly fmt --all -- --check: exit 0, no output.
  • cargo clippy --all-targets --locked -- -D warnings: exit 0, Finished dev profile, no warning.
  • cargo clippy --all-targets --release --locked --features opentelemetry,splice,simd -- -D warnings: exit 0, Finished release profile, no warning.
  • RUSTDOCFLAGS='-D warnings' cargo doc --no-deps --all-features --locked: exit 0.
  • cargo test --workspace --locked --no-fail-fast -- --skip tests::fuzz_tests::: exit 0. sozu-lib 1745 passed; 0 failed, sozu-e2e 693 passed; 0 failed, sozu-command-lib 416 passed; 0 failed, sozu lib and bin 273 passed; 0 failed each, every other integration and doc-test target ok.
  • cargo test -p sozu-lib --locked --features opentelemetry,splice,simd: 1772 passed; 0 failed, every integration and doc-test target ok.
  • The nine process-level suites of the CI step "Test sozu (process-level e2e)", each cargo test -p sozu --locked --test <suite> -- --ignored: all ok.
  • cargo test -p sozu-e2e --locked --features grpc-e2e tests::grpc_tests::: 2 passed; 0 failed.
  • RUSTFLAGS='--cfg tokio_unstable' cargo test -p sozu-sim --locked --test tcp_preread_sim -- --nocapture with the CI step's SOZU_TCP_PREREAD_SIM_SEEDS=512 and SOZU_TCP_PREREAD_SIM_STEPS=64: 6 passed; 0 failed.
  • Test hygiene (no bare #[ignore]): ok.
  • python3 .github/scripts/check_doc_citations.py --base c6098095d3a2c1738a90cfbc17865f718d648276, with the self-test and the broken-fixture check: exit 0, every rule OK.
  • The relay test's own TO SEE THIS RED recipe was executed on the final tree: with the RelayProxyProtocol / header_size.is_none() early return of TcpSession::attempt_backend_connect_if_needed deleted, the test fails on "the per-IP slot must not be charged to the load balancer's peer address before its PROXY header is read"; the code was then restored.

Not run

The other crypto-provider cells (crypto-aws-lc-rs, crypto-openssl, fips) and the stable, beta and nightly cells; dev-profile clippy with opentelemetry,splice,simd; the cargo-fuzz targets; the benches; the /proc observer suites (they need a user namespace); the real-service protocol suites, including the TCP ones (they pull container images); the UDP, H2, backend selection and mutable-commands simulation sweeps. No test asserts the affinity-key half of the relay fix (HRW, MAGLEV, shard): it follows from the same dial-time address, by reading. Cargo.lock is unchanged, so the RUSTSEC advisory job sees the base lockfile.

A TCP backend connection still not established when `connect_timeout`
expires closed the session, as the documented TCP exception requires (a
TCP session is not failed over), but the timeout never reached the
accounting a refused connection goes through. The backend timer is
armed for `connect_timeout` in `connect_to_backend` and only switches to
`back_timeout` in `set_back_connected`, and the backend arm of
`TcpSession::timeout` only called `container_backend_timeout.triggered()`.
`Server::timeout` runs no `ready` pass for TCP
(`ProxySession::needs_ready_pass` is `false`), and
`TcpSession::fail_backend_connection`, the only place that bumps
`Backend::failures`, arms the retry policy and emits
`backend.connections.error`, `backend.down` and `backend.available`,
was called only from the HUP branch of `ready_inner`. A blackholed TCP
backend (SYN dropped, accept queue full) therefore never entered its
back-off window, the load balancer kept selecting it, and every client
routed to it waited the full `connect_timeout` before being closed.

The backend arm of `TcpSession::timeout` now calls
`fail_backend_connection` when the dial is still `Connecting`, then
still closes the session. A timer firing on a `Connected` backend is an
idle `back_timeout` and charges nothing. Nothing is released twice:
`fail_backend_connection` touches only the failure count, the retry
policy and the error and down metrics, and the connection release in
`TcpSession::close` runs once as before.

`CHANGELOG.md`, the `connect_timeout` row and the TCP failover paragraph
of `doc/configure.md`, `doc/lifetime_of_a_session.md` and the
`max_connection_attempts` comment of `bin/config.toml` describe the new
accounting.

Tests:
- `tcp::sni_routing_tests::a_backend_connect_timeout_is_charged_to_the_backend`
  fires the backend timer of a still-`Connecting` dial and asserts the
  session closes with `failures == 1` and one retry-policy try (unfixed:
  `left: 0 right: 1`).
- `tcp::sni_routing_tests::a_backend_idle_timeout_is_not_charged_to_the_backend`
  is its pair: the same timer on a `Connected` backend closes the
  session and charges nothing.

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

Once a ClientHello routes a TCP SNI-preread session, the route latches
in `SniPreread::outcome`, and frontend HUP interest stays armed while
the backend dial is still `Connecting`. A client FIN or RST then reached
`TcpSession::front_hup`, `SniPreread::on_front_closed` and `front_gone`.
The accumulator still held the ClientHello, so `Input::FrontClosed` went
into the already-decided core, which replayed the latched
`Output::Routed` through `handle_output` a second time: release builds
counted `tcp.sni_preread.routed` twice and logged the route twice, and
debug builds aborted the worker on
`debug_assert!(self.outcome.is_none(), ...)`.

`SniPreread::front_gone` now returns `SessionResult::Close`, with a
`debug!` line, before it looks at the accumulator whenever a route has
already latched, as the route-aware front timeout in
`TcpSession::timeout` already does (#1290). The guard sits in the
shared helper, so the read-error path is covered as well as the HUP
path. The session still closes through the existing teardown, exactly
once. The doc comment of `SniPreread::on_front_closed` no longer claims
it only runs before a routing decision.

`CHANGELOG.md` and the tcp_preread `LIFECYCLE.md` describe the new
behaviour.

Test:
- `tcp::sni_routing_tests::frontend_hup_after_route_with_pending_dial_does_not_replay_the_route`
  routes a session, leaves its dial `Connecting`, delivers a frontend
  HUP and runs one `ready()` pass: the pass must not panic, must still
  close the session, and `routed` must move by exactly one. Unfixed, it
  panics with "a route must be captured at most once per SniPreread
  lifetime", and with debug assertions off it fails with `left: 2 right: 1`.

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

On an `expect_proxy` TCP listener, `TcpSession::new` gave
`ExpectProxyProtocol` a clone of the session's frontend
`TimeoutContainer`, and `ExpectProxyProtocol::into_pipe` passed that
clone on to the `Pipe`. A clone shares the timer wheel handle but not
the entry it names, so a reset only the session performed
(`TcpSession::set_back_connected`, or `TcpSession::readable` ahead of
the pipe's own reset) left the pipe with a stale handle, and the pipe
re-armed a second entry under the same token. When that second entry
fired first, `TcpSession::timeout` discarded the session's own live
entry with `triggered()`. Nothing could cancel that entry any more: it
later fired under a slab key reused by an unrelated TCP session, which
was closed with no deadline check. It takes two frontend reads while the
backend connect is pending, a connect that completes on a later wheel
tick, both peers going quiet, and a `front_timeout` exceeding
`back_timeout` by less than the time the connect took; the 60 s and
30 s defaults are never affected.

`TcpSession::new` now hands `ExpectProxyProtocol` an empty container
(`TimeoutContainer::new_empty`), and `ExpectProxyProtocol::into_pipe`
builds the `Pipe` with no frontend timer, so the session keeps the only
frontend deadline, as the plain, send-proxy, relay and SNI-preread
pipes already do. The session resets that entry wherever the pipe reset
its clone, so no session closes earlier than before, and the
`Could not reset front timeout (pipe)` error log disappears on this
path. HTTP and HTTPS never call `into_pipe` and are unchanged.

`CHANGELOG.md`, `doc/lifetime_of_a_session.md` and the proxy_protocol
`LIFECYCLE.md` describe the new wiring.

Test:
- `tcp::sni_routing_tests::expect_proxy_pipe_leaves_no_orphan_frontend_timer_after_a_timeout`
  drives an expect-proxy session through the stale-clone sequence and
  asserts that no orphan frontend entry fires after the timeout, that
  the expect stage holds no armed entry, and that the pipe carries no
  frontend timer. Unfixed, it fails with `entries fired at +[30, 34]s`;
  each half of the fix alone fails one of the two structural assertions.

Signed-off-by: Florentin Dubois <[email protected]>
On an SNI-routed TCP listener a client can send its ClientHello and
half-close right behind it, and Linux then reports both as one
`READABLE | HUP` event. `TcpSession::ready_inner` honoured the HUP
before reading. `SniPreread::front_gone` looks at the accumulator, not
at the kernel queue, so a session whose hello was still unread was
closed as a silent bare-TCP health check: `trace!` only, no
`tcp.sni_preread.routed` or `tcp.sni_preread.rejected.*` count. A hello
whose last fragment arrived together with the FIN was counted as
`rejected.front_closed`, although the rest of it was already queued.

The pre-HUP drain in `TcpSession::ready_inner`, which ran only for
`ExpectProxyProtocol` (#1823), now also runs for an `SniPreread` that
has not routed yet, so the pending bytes reach the core before the HUP
is acted on. A complete hello is routed and counted once, then the
still-set HUP closes the session through the route-latched arm of
`SniPreread::front_gone` without dialing the backend; a malformed one
is rejected with the reason it earns; a hello the FIN cut short is
metered `rejected.front_closed`; and a connect that sent nothing stays
silent. Teardown reuses the existing `front_hup` path and releases
nothing new. The comments of `SniPreread::front_gone` and
`on_front_closed` and the tcp_preread `LIFECYCLE.md` §9 now describe a
route latched in that drain as well as during a pending dial.

`CHANGELOG.md`, `doc/lifetime_of_a_session.md` and the tcp_preread
`LIFECYCLE.md` describe the new behaviour.

Tests:
- `tcp::sni_routing_tests::sni_preread_hello_and_fin_in_one_event_is_routed_not_a_silent_health_check`
  delivers a complete hello and a FIN in one real epoll event.
- `tcp::sni_routing_tests::sni_preread_last_fragment_and_fin_in_one_event_is_routed_not_rejected`
  reads the first half of the hello in an earlier pass, then delivers
  the second half and the FIN in one event.

Both fail on the unfixed tree at their final routed-count assertion
(`left: 0 right: 1`).

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

On a TCP cluster that sends a PROXY header to its backend
(`send_proxy = true`), a relay cluster when the listener has
`expect_proxy = true` and a send cluster otherwise, a client may write
its request and FIN before the worker services the socket. The first
`TcpSession::ready_inner` pass only dials, so the coalesced
`READABLE | HUP` was still pending on the next pass, which handed it to
the wildcard arm of `TcpSession::front_hup`. That closed the session
before `RelayProxyProtocol::back_writable` or
`SendProxyProtocol::back_writable` had written anything: the backend saw
a connection dialed and then closed with nothing written, without even
its PROXY header on a send cluster, and the client's own header and
request were dropped on a relay one. An `expect_proxy` listener without
`send_proxy` was not affected: it already reads the queued bytes before
acting on the HUP.

`TcpSession::ready_inner` now drains a relay session's readable bytes
before its HUP check, and a new `TcpSession::defers_frontend_hup` keeps
the HUP of a send session, and of a relay session once its header is
parsed, in the readiness event while masking it out of the dispatch
loop's frontend interest. The HUP then reaches the existing teardown,
`Pipe::frontend_hup`, through the existing upgrade: the header and the
request are forwarded, and the pipe closes the session once nothing is
left in flight. A relay client that half-closes inside its PROXY header
still closes at once, ERROR still closes at once, and no new release
path is added. A send session reads nothing before the upgrade, so a
bare connect and FIN, typically an L4 health check, now waits for the
backend connect and costs the backend one connection that carries only
the PROXY header; the wait is bounded by the connect, `connect_timeout`
and the frontend timeout.

`CHANGELOG.md`, `doc/lifetime_of_a_session.md` and the proxy_protocol
`LIFECYCLE.md` describe the new behaviour.

Tests (in `tcp::sni_routing_tests`):
- `relay_proxy_protocol_half_close_before_backend_connect_forwards_the_request`
- `send_proxy_protocol_half_close_before_backend_connect_forwards_the_request`

Both fail on the unfixed tree on the delivery assertion ("the backend
must receive it, got []"). Guards for each arm of the new predicates:
- `relay_proxy_protocol_front_hup_while_connecting_waits_for_the_backend`
- `send_proxy_protocol_front_hup_while_connecting_waits_for_the_backend`
- `relay_proxy_protocol_half_close_without_any_byte_closes_at_once`
- `relay_proxy_protocol_half_close_inside_the_header_closes_at_once`
- `send_proxy_protocol_bare_half_close_delivers_only_the_header_then_closes`
- `send_proxy_protocol_reset_while_connecting_closes_at_once`

Signed-off-by: Florentin Dubois <[email protected]>
The recipe of tcp::sni_routing_tests::a_backend_connect_timeout_is_charged_to_the_backend
said "run it unmodified" and named no statement to mutate. It now names
the statement and the failure it produces: delete the
`self.fail_backend_connection();` call from the `is_connecting()` block
in the backend arm of `TcpSession::timeout`, and the `failures` assertion
fails with "a connect timed out on connect_timeout must be counted
against its backend".

The mutation was applied and the test seen failing on its own assertion,
then the code was restored. Comments only.

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

A `RelayHeader` TCP session (a cluster with `send_proxy = true` behind a
listener with `expect_proxy = true`) dialed its backend on its first
readiness event, before `RelayProxyProtocol::readable` had parsed the
inbound PROXY-v2 header. `TcpSession::attempt_backend_connect_if_needed`
excluded only `ExpectProxyProtocol` and an unrouted `SniPreread`. With
nothing parsed, `TcpSession::effective_session_address` fell back to
the accepted peer, which is the upstream load balancer, so the
per-(cluster, source-IP) and per-subnet slots
(`max_connections_per_ip`, `max_connections_per_subnet`) were charged
to the load balancer for every client behind it, and the affinity key
of `HRW`, `MAGLEV` and `shard_percent` was derived from it too.

`attempt_backend_connect_if_needed` now returns early for a
`RelayProxyProtocol` whose `header_size` is still `None`, so a relay
session dials through the attempt that follows the `readable()` call
that parses its header, and is charged to the header's source address.
The pre-HUP drain in `TcpSession::ready_inner` also gets one dial
attempt, restricted to a relay session, so a header coalesced with the
client's FIN does not leave the session undialed until the frontend
timeout. The dial and the release are the existing `connect_to_backend`
and close paths. A `LOCAL` / `AF_UNSPEC` header still falls back to the
peer, as documented.

A relay session no longer overlaps its backend connect with the wait
for the header, and a relay connection that never completes a header
(a bare health check, a slow or garbage client) opens no backend
connection at all.

The comments of `ready_inner` and of the half-close test helper now
describe the parse-then-dial order, and the relay front-HUP test sends
only its payload, since its fixture now writes and parses the header
before dialing. `CHANGELOG.md`, `doc/lifetime_of_a_session.md`,
`doc/rate-limit-design.md` and the proxy_protocol `LIFECYCLE.md`
describe the new behaviour.

Test:
- `tcp::sni_routing_tests::a_relay_proxy_protocol_session_is_charged_to_the_header_source_not_the_lb_peer`
  connects from 127.0.0.1 (the load balancer) and relays a header whose
  source is 192.0.2.7, and asserts that no slot is held before the
  header, that the slot is charged to 192.0.2.7 after it, and that
  127.0.0.1 holds none. On the unfixed tree it fails with "the per-IP
  slot must not be charged to the load balancer's peer address before
  its PROXY header is read".

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS FlorentinDUBOIS changed the title fix(tcp): connect-timeout accounting, expect-proxy timer, SNI preread and PROXY half-close fixes fix(tcp): connect-timeout accounting, expect-proxy timer, SNI preread, PROXY half-close and relay source fixes Nov 20, 2026
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 60b6502 into main Nov 20, 2026
46 checks passed
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.

1 participant