Repository navigation
refactor(mux): selection reserves, a failed dial releases - #1709
Merged
Merged
Conversation
The backend-set capability Router::backend_from_request borrows used to select and dial in one call: Backend::try_connect counted the connection outside the delta ledger, and only a single synchronous step kept the next selection seeing it. That tied the core's seam to mio's TcpStream, so no simulator could implement it. Selection now takes the count itself. BackendMap::reserve_backend and reserve_sticky_backend raise the chosen backend's active_connections under the same borrow as the choice, and Mux::dial_backend connects to BackendId::address afterwards. A connect(2) that fails pushes the new BackendChange::DialFailed(Instant), which releases the reservation and records the failure (failures += 1, retry_policy.fail with the map's jitter); the drain before each selection applies it, so the next selection sees the backend exactly where a failed try_connect left it. A dial that connects keeps the reservation as its connection's count. BackendDialer becomes BackendSelector (select_and_dial -> select, DialedBackend -> SelectedBackend without a socket, RegistryDialer -> RegistrySelector), backend_from_request returns the BackendId, and BackendId::new lets a simulator's selector mint ids without mio. The TCP proxy keeps backend_from_cluster_id and try_connect unchanged. No allocation is added on the dial path (6 per dial before and after, 0 per steady-state selection) and BackendChange stays 16 bytes. The three exits past a successful connect that never released try_connect's count still do not release the reservation; LIFECYCLE section 9 names them. Refs #1684 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 30, 2026 00:28
This was referenced Sep 30, 2026
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 30, 2026
#1706) Refs #524 (PR 1 of 2: the affinity key; shuffle sharding follows in PR 2). ## Problem Only the UDP datapath handed `HRW` / `MAGLEV` a key. HTTP, HTTPS and TCP selected with `None`, so a cluster configured with either policy silently fell back to round-robin: a client's requests visited every backend in turn, contrary to the documentation. ## Design - **Key derivation.** `affinity_key_from_ip` and `affinity_key_from_value` (`lib/src/load_balancing.rs`) use the `DEFAULT_HASH_SEED`-seeded FNV-1a + splitmix64 hash the policies already use, with distinct domain tags for addresses and values. - Deterministic across workers and restarts; the values are pinned by a unit test. - `::ffff:a.b.c.d` keys as `a.b.c.d`. - **HTTP/HTTPS (H1 and H2).** `Router::plan_connect` derives the key right after routing (`affinity_key` in `router.rs`), for `HRW`/`MAGLEV` clusters only; every other policy derives none and selects exactly as before. - Source: the cluster's `affinity_header` value (case-insensitive name, first occurrence) or `affinity_cookie` value (exact name), else the source IP after the PROXY protocol. - Header blocks and the cookie jar are read in place and hashed without copying. Values are hashed raw: a quoted cookie and its unquoted spelling are two keys. - An `affinity_cookie` named like the listener's sticky cookie reads the value captured before that cookie is elided. - Stored in `HttpContext::affinity_key`, so a replay reuses it like the routed cluster. - **TCP.** `TcpSession::connect_to_backend` keys on `effective_session_address`, which is the PROXY-v2 source when the cluster expects one. - **Where the key enters selection** (on top of #1709's shapes): - HTTP: `BackendSelector::select(cluster, affinity, key)` → `BackendMap::reserve_backend(cluster, key, now)` / `reserve_sticky_backend(cluster, cookie, key, now)` → `select_backend` → `next_available_backend_with_key`. - TCP: `BackendMap::backend_from_cluster_id(cluster, key, now)`. - **Precedence.** - A sticky cookie naming a live backend still wins over the key. - **Connection reuse keeps priority** (owner decision): the key applies only when a new backend connection is dialled. A request reusing a backend connection its session holds (H1 keep-alive, H2 multiplexed) follows that connection. Behind an upstream proxy or CDN multiplexing tenants over warm keep-alive/H2 connections, tenants follow the connection's backend. Documented and pinned by e2e tests. - **Config plumbing.** - Proto `Cluster.affinity_header = 18`, `affinity_cookie = 19`. - TOML keys, `--affinity-header` / `--affinity-cookie` on `sozu cluster add`, an `affinity_key` column in the cluster table, lengths-only `Debug`. - `validate_affinity_key` runs at config load and on every `AddCluster`: at most one of the two, each an RFC 9110 token. `Host` and `Cookie` are refused case-insensitively, since Sōzu never keeps them as headers. - The main state refuses a cluster that names a key and serves a TCP frontend, in both orders (`AddCluster` after `AddTcpFrontend`, and the reverse). The TOML loader refuses the keys on a `tcp` cluster. - Hot-updatable. Protocol/security impact: a header/cookie key is client-chosen, so a client can pick its backend. That is the same property as a sticky cookie, and it is documented. No parser, framing or TLS change. ## Check before upgrading HTTP, HTTPS and TCP clusters already configured with `HRW` or `MAGLEV` ran round-robin and now pin each client by its source IP. Clusters whose clients arrive from few addresses — behind a NAT, or an L4 balancer without the PROXY protocol — concentrate on few backends. Switch policy, enable the PROXY protocol, or key on a header or cookie. The note is in both `CHANGELOG.md` and `doc/configure.md`. ## Allocations - `deriving_an_affinity_key_allocates_nothing`: 256 derivations make 0 allocations. - `stamping_a_dialled_backend_allocates_nothing` is unchanged at 0. ## Red / green Each case was run with the fix reverted, then restored. - **e2e** (`e2e/src/tests/affinity_key_tests.rs`). Each test predicts every key's backend with the library's `Rendezvous`: provable outcomes, not statistical ones. - Key dropped in `RegistrySelector::select` (after the #1709 rebase): HTTP, HTTP header, HTTPS, H2 header/cookie and H2-reuse all fail. For example: `source 127.0.0.2: predicted pong0 …, reached ["pong0","pong1","pong2","pong3"]`. - Key dropped in `TcpSession::connect_to_backend`: `source 10.0.0.1: predicted backend-0 for every session, reached [backend-0 … backend-3]`. - Header/cookie keying disabled: `h2 X-Tenant: tenant-0: predicted pong0 …, reached ["pong3" ×4]`. - Reuse pinning, with reuse disabled in `Router::decide_after_gate` (`reuse_token.filter(|_| false)`): - `one keep-alive connection: predicted Some("pong1") for both … reached [Some("pong1"), Some("pong0")]` - `one H2 connection: predicted Some("pong2") for both … reached [Some("pong2"), Some("pong3")]` - Green: 7/7 (HTTP IP, HTTP header, HTTPS IP+cookie, H2 header+cookie, TCP PROXY-v2, H1 keep-alive reuse, H2 reuse), 3 consecutive runs. - **Unit.** - `key 0 must stay on one backend under HRW` → green. - `256 derivations made 128 heap allocations, expected none` → green. - Sticky-named cookie: `left: Some(1686…) right: Some(1733…)` with the capture arm removed → green. - Also added: pinned hash values, derivation rules, `Host`/`Cookie` refusal, the TCP-frontend/key refusal in both orders. ## Validation (head c70f65a, rebased on main 4420d13 = #1709) - `cargo +nightly fmt --all -- --check`: 0. - `cargo clippy --all-features --all-targets --locked -- -D warnings`: 0. - `cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings`: 0. - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked`: 0. - `cargo test -p sozu-lib`: 1407 passed. `-p sozu-command-lib`: 212. `-p sozu`: passed. - `cargo test -p sozu-e2e -- affinity_key_tests cluster_ip_limit`: 11/11. - `cd fuzz && cargo +nightly fuzz build`: 0. - `check_doc_citations.py` `--self-test`, `--root .`, `--root . --base origin/main`, `--audit --root .`: all 0. ## Docs `doc/configure.md` ("Client affinity", reuse behaviour, upgrade check, raw values, refused names, forwarding-policy interactions), `doc/configure_cli.md`, `doc/architecture.md`, `doc/lifetime_of_a_session.md`, `lib/src/protocol/mux/LIFECYCLE.md`, `bin/config.toml`, `doc/testing.md`, `CHANGELOG.md` (Fixed with the upgrade check, Added). Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 30, 2026
…1710) Closes #1684 This is the fourth and last PR of the sequence the maintainer set in #1684 (comment): a deterministic simulation that drives backend selection through a selector the simulator owns. It builds on: - #1698, which removed `L7Proxy::backends`; - #1700, which injects the clock and the RNG into selection; - #1709, where selection reserves a connection and a failed dial releases it. It is based on `origin/main` `4420d132`. ## Design `sim/tests/backend_selection_sim.rs` runs under moonpool-sim, gated on `--cfg tokio_unstable` like every other simulator in `sozu-sim`. - **The simulator owns the selector.** `SimSelector` implements `router::BackendSelector`: - It wraps a real `BackendMap::with_seed`, seeded from moonpool's RNG, and calls `reserve_backend` / `reserve_sticky_backend`. - It numbers slots in minting order and mints ids with `BackendId::new`. - The harness calls `Router::backend_from_request` with it, exactly as `Mux::dial_backend` calls it with `RegistrySelector`. - **It plays the embedding proxy's side.** A dial either connects or fails, as the seeded RNG decides: - On a connect: `set_connection_time` and `retry_policy.succeed`. - On a failure: `Backend::release_failed_dial`, with the map's `rng()`. - Open connections close at random. - **Its clock is its own.** One base `Instant` is captured per run, and every call receives `base + offset`. The offset advances only by seeded draws, sometimes past the longest backoff window. - `Workload::run` never awaits, for the same reason as `h2_simulation.rs`: `BackendMap` holds `Rc`s, and moonpool's `Workload` future must be `Send`. - **Each seed picks a policy for each of the two clusters.** The seven choices are RoundRobin; Random; LeastLoaded on Connections or ConnectionTime; PowerOfTwo on Connections or ConnectionTime; and HRW. So `PeakEWMA` runs on the injected clock. - **Invariant, checked after every step:** each backend's `active_connections` equals a shadow count the harness keeps (+1 per reservation, −1 per failed-dial release and per close). This is LIFECYCLE §9 invariant 14's "selection reserves, failure releases", observed from outside the core. After the final drain every count is 0. - **`backend_selection_simulation_seed_sweep`** runs at least 64 seeds (default 64, 400 steps each) and asserts `successful_runs == seeds`. - **`backend_selection_simulation_is_deterministic`** runs 8 seeds twice each and requires byte-identical traces and equal counts. - It also checks absolute values: at least 100 selections, and some failed dials, closes and sticky answers. - It requires at least one Random or PowerOfTwo cluster, so the map's own generator is exercised. - A fresh backoff window must close exactly one second later on the harness's clock, which a leaked wall-clock read fails. - The 8 traces must all differ from each other. - **The trace records decisions only:** - the policy per cluster; - per selection: cluster, stick flag, cookie, `BackendId` slot, backend, and sticky answer; - each dial outcome (reservation kept, or released); - each close and each clock advance, in whole milliseconds of the harness's virtual offset. It never holds an `Instant`. - `git grep -q mio -- sim/Cargo.toml` exits 1: a selector holds no socket, so the simulator needs no `mio`. - CI: the new sweep is a step of the per-PR `udp-simulation` job, next to the UDP, TCP-preread and H2 sweeps. Two nits from the #1709 review are folded in: - The duplicated doc line on `BackendMap::backend_from_cluster_id` is removed. - `BackendMap::backend_from_sticky_session` is removed. Since #1709 its only callers were its own three tests, which now exercise `reserve_sticky_backend`. The test that finds a recorded backend used to accept any connected result; it now asserts that it reached `mycluster-2` and that the reservation was taken. This is a library API removal (CHANGELOG ➖ Removed), with no runtime change. ## Determinism evidence I replayed seed `0x1684` twice with `SOZU_BACKEND_SELECTION_SIM_SEED=0x1684 RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked --test backend_selection_sim backend_selection_simulation_seed_sweep -- --nocapture`, then kept the trace lines: ``` $ wc -l trace-1 trace-2 572 trace-1 572 trace-2 $ cmp trace-1 trace-2 && echo TRACES_IDENTICAL TRACES_IDENTICAL $ sha256sum trace-1 trace-2 416db0603f4a010027e427f19f7d28196e5c1769c6997d47f393417b538cf55b trace-1 416db0603f4a010027e427f19f7d28196e5c1769c6997d47f393417b538cf55b trace-2 ``` The trace holds 243 selections, 43 failed-and-released dials, 104 closes and 75 sticky answers. It opens with: ``` cluster cluster-a policy=LeastLoaded metric=ConnectionTime cluster cluster-b policy=Hrw metric=Connections select cluster-a stick=true cookie=Some("cluster-a-sticky-2") -> slot=0 backend=cluster-a-2 sticky=Some("cluster-a-sticky-2") dial slot=0 -> failed, released select cluster-b stick=false cookie=None -> slot=1 backend=cluster-b-0 sticky=None dial slot=1 -> connected in 98ms select cluster-b stick=false cookie=None -> slot=2 backend=cluster-b-1 sticky=None dial slot=2 -> connected in 198ms select cluster-b stick=false cookie=Some("no-such-backend") -> slot=3 backend=cluster-b-2 sticky=None dial slot=3 -> failed, released ``` ## Red, then green For each mutation below I changed the code, quoted the failing assertion, then restored it. Both tests pass afterwards. - **The harness's `now()` returns `Instant::now()`** (a leaked wall clock): - Both tests fail with `seed=0x1684: the window must close one second later on the harness's clock` (and `seed=0x0: …` in the sweep). - Two runs that both read the wall clock would still agree with each other, which is why the absolute clock check exists. - **`BackendMap::new()` replaces the seeded `BackendMap::with_seed`**, with the draw still consumed so every other draw stays aligned: - The determinism test fails with `seed=0x1684: one seed must yield one byte-identical trace`. - My first version checked one seed only and stayed green under this mutation. That seed drew LeastLoaded/HRW, so only backoff jitter consumed the map's generator. The test now covers eight seeds and requires a map-seeded policy. - **`Backend::reserve_connection` without its increment** (in `lib/src/backends.rs`): - Both tests fail with `seed=0x1684 step=2: slot 1 (cluster-b-0) holds 0 connections, the reservations, releases and closes this harness made add up to 1` (and `seed=0x0 step=0` in the sweep). ## Allocations This PR changes no code on the dial path. I measured with a throwaway probe (`test_allocations::allocations()` around `Mux::dial_backend`, plus `size_of`), not committed: | | `origin/main` `4420d132` (as measured for #1709) | this branch | |---|---|---| | heap allocations per `Mux::dial_backend`, 3 runs | 6, 6, 6 | 6, 6, 6 | | steady-state selection (`backend_selection_allocates_nothing_in_steady_state`) | 0 | 0 | | router stamping (`stamping_a_dialled_backend_allocates_nothing`) | 0 | 0 | | `Backend` / `BackendList` / `BackendMap` / `BackendChange` / `BackendDelta` / `MuxClear` | 208 / 72 / 472 / 16 / 24 / 4984 B | unchanged | ## Proposed follow-up: the three reservation-leak exits LIFECYCLE §9 invariant 14 names three exits of `Mux::dial_backend` past a successful `connect(2)` that drop the connection without releasing its reservation: 1. `Connection::new_h2_client` returning `None`, when the buffer pool is exhausted (`BackendConnectionError::MaxBuffers`). 2. A refused `Connection::start_stream`, when the backend's maximum concurrent streams is reached. 3. The `register_socket` rollback, which releases `active_requests` and the gauges but not `active_connections`. Before #1709 they leaked the count `Backend::try_connect` took; now they leak the reservation, the same `+1`. **Proposal: one small PR.** - On each of the three exits, push `BackendDelta { slot: backend.slot(), change: BackendChange::ConnectionClosed }` before returning. This is the same release a closing connection emits, applied by the drain before the next selection. - Add one test per exit, each asserting `active_connections == 0` after `apply_all`: - pool exhaustion: a pool too small for an H2 client; - stream refusal: a connection whose stream limit is already reached; - registration failure: a registry that refuses `register_socket`. - Every test must be seen red before the fix. - The shadow check of this simulator can then be extended to those exits, once the harness can drive them. ## Validation Run on head `ac4160e8`, based on `4420d132`. Each exit code was checked directly, never through a pipe: - `cargo +nightly fmt --all -- --check` -> exit 0 - `cargo clippy --all-targets --locked -- -D warnings` -> exit 0 - `cargo clippy --all-targets --all-features --locked -- -D warnings` -> exit 0 - `cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings` -> exit 0 - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` -> exit 0 - `cargo test --workspace --locked --exclude sozu-e2e` -> exit 0 (1869 passed, 0 failed, 17 ignored, all ignores already on main) - `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked` -> exit 0 (33 passed, both new tests included) - `cargo test -p sozu-e2e --locked -- --skip tests::fuzz_tests::` -> exit 0 (522 passed) - `cd fuzz && cargo +nightly fuzz build` -> exit 0 - `python3 .github/scripts/check_doc_citations.py` -> exit 0 - `python3 .github/scripts/check_doc_citations.py --base origin/main` -> exit 0 - `python3 .github/scripts/check_doc_citations.py --self-test` -> exit 0 - `python3 .github/scripts/check_doc_citations.py --root .github/scripts/testdata/citations` -> exit 1 (the broken fixture must fail) - The repository's pre-push hook (`cargo build --all-features`, then `cargo clippy --all-features --all-targets -- -D warnings`) passed on push. Docs: `doc/testing.md` §5 gains the simulator recipe, a taxonomy row and the run command. The sim-harness list in the `sim/Cargo.toml` comment is updated. CHANGELOG has ✨ Added for the simulation and ➖ Removed for `backend_from_sticky_session`. Signed-off-by: Florentin Dubois <[email protected]>
This was referenced Sep 30, 2026
Closed
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 30, 2026
…1717) Closes #1713 ## What Backend selection reserves a connection (`active_connections += 1`) before `Mux::dial_backend` connects (#1684/#1709). Before this change, only a failed `connect(2)` released that reservation (`BackendChange::DialFailed`). Three exits after a successful connect dropped the connection and kept the reservation: - (a) `Connection::new_h2_client` returns `None` because the buffer pool is exhausted; - (b) `Connection::start_stream` refuses the stream; - (c) the `register_socket` rollback. `Connection` has no `Drop`, so each hit left the backend one connection too high for the rest of the worker's life. That skews least-loaded, power-of-two and PeakEWMA selection, and it keeps a removed backend from ever draining to `Closed`. ## Fix - Every step after the connect moves unchanged into the new `Mux::attach_dialed`. - `Mux::dial_backend` pushes one `BackendChange::ConnectionClosed` for whichever exit returns `Err`. This single release point also covers any exit added later. - The release is `ConnectionClosed` (`dec_connections` only), not `DialFailed`. These failures are local to the proxy, so recording them in the backend's `failures` and backoff would steer traffic away from a healthy backend. Protocol/security impact: none on the wire. Counters stay correct on local-failure paths (CWE-400 hygiene). ## Tests `lib/src/protocol/mux/router.rs`: the `dial_one` harness is now `dial_with(address, DialFault)`. It calls the real `Mux::dial_backend` against a listening loopback backend with each fault staged: - `an_h2_client_the_pool_cannot_build_releases_its_reservation`: every pool buffer is checked out → `MaxBuffers`; - `a_refused_stream_start_releases_its_reservation`: the request already holds encoded output (#1632 guard) → `MaxSessionsMemory`; - `a_socket_the_poller_refuses_releases_its_reservation`: a proxy wrapper whose `register_socket` returns `EMFILE` → `MaxSessionsMemory`. Each test asserts that the dial failed at its exit and left no router entry. After the ledger drains, `active_connections == 0`, `failures == 0` and the retry policy is still `OKAY`. All three were seen red, both on unmodified `main` and with the release disabled (`left: 1, right: 0`), and green with the fix. ## Commands run - `cargo +nightly fmt --all --check` → 0 - `cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings` → 0 - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` → 0 - `cargo test -p sozu-lib -p sozu-command-lib --locked` → 0 (sozu-lib: 1423 passed) - `RUSTFLAGS='--cfg tokio_unstable' cargo test -p sozu-sim --locked` → 0 - `cargo test -p sozu-e2e --locked -- e2e_session_router_connect_failure_no_leak mux_tests protocol_pair_matrix` → 0 (67 passed) - `cd fuzz && cargo +nightly fuzz build` → 0 - `check_doc_citations.py` with `--self-test`, `--root .`, `--root . --base origin/main` and `--audit --root .` → 0 for all four. The audit's two advisories are in `proxy_protocol/LIFECYCLE.md`, which this change does not touch. ## Docs - `lib/src/protocol/mux/LIFECYCLE.md` (invariant 14): replaced the "three exits … still do" paragraph and added the new tests to the "Pinned by" list. - Doc comments on `BackendChange::ConnectionClosed`, `Mux::dial_backend` / `Mux::attach_dialed` and `BackendSelector`. - `CHANGELOG.md`: Unreleased / Fixed. 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.
Refs #1684. This is the third PR of the sequence the maintainer set in #1684 (comment): G2 = (a), the UDP shape with reservation at selection.
It is based on
origin/main4918ad4f, which includes #1698 (G1), #1700 (G3), #1704 and #1705.Design
BackendMap::reserve_backend(cluster, now)andreserve_sticky_backend(cluster, cookie, now)choose a backend, then raise itsactive_connectionsby one (Backend::reserve_connection). The raise happens under the same borrow as the choice.Backend::try_connecttook at the dial.backend_from_cluster_idhad moved into a privateBackendMap::select_backend, which both paths share.Mux::dial_backendconnects toBackendId::addressafter the selection borrow is released. The address travels insideBackendId, which is the(BackendId, SocketAddr)shape the maintainer asked for.connect(2)error pushes the newBackendChange::DialFailed(Instant)and returnsBackendError::ConnectionFailures.DialFailedcallsBackend::release_failed_dial, which doesdec_connections,failures += 1andretry_policy.fail(at, rng).BackendRegistry::apply_allnow takes the worker's&RefCell<BackendMap>. It borrows it only in theDialFailedarm, to draw the backoff jitter from the map's generator; every other change leaves the map alone.Router::plan_connectapplies the release before the next selection reads the counters. The backend then sits exactly where a failedBackend::try_connectleft it.ConnectionClosedreleases it, as before.sim/can reach:pub fn BackendId::new(slot, backend_id, address).BackendRegistry::id_for.mio.git grep -q mio -- sim/Cargo.tomlstill exits 1.tcp.rs) still callsBackendMap::backend_from_cluster_idandBackend::try_connect.Renames, for #1706 (#524,
feat/lb-affinity-key-l7-tcp)#1706 adds an affinity
keytoselect_and_dialandbackend_from_cluster_id. Whichever PR merges second rebases onto the other:router::BackendDialer→router::BackendSelectorBackendDialer::select_and_dial→BackendSelector::select, same(cluster_id, affinity)parametersrouter::DialedBackend→router::SelectedBackend, which drops itssocketfieldRegistryDialer→RegistrySelectorRouter::backend_from_requestnow returnsBackendId, where it returned(TcpStream, BackendId)BackendMap::backend_from_cluster_idkeeps its signature. The mux now calls the newreserve_backendandreserve_sticky_backend, so #1706'skeybelongs on those as well.Pre-existing
active_connectionsleak, not fixed hereThree exits of
Mux::dial_backendafter a successfulconnect(2)drop the new connection without releasing its connection count:Connection::new_h2_clientreturningNone, when the buffer pool is exhausted (BackendConnectionError::MaxBuffers).Connection::start_stream, when the backend's maximum concurrent streams is reached.register_socketrollback. It releases theactive_requestscharge and the gauges, but notactive_connections.On
maineach of these already leaked the+1thatBackend::try_connecttook on success. Now each leaks the reservation, which is the same+1taken earlier. This change does not make it worse: on each of these paths the count is the same before and after. So I did not fix it here, and LIFECYCLE §9 names the three exits.Proposed follow-up: push
BackendChange::ConnectionClosedfor the reserved slot on all three exits, the same release a closing connection emits. Pin it with one test per exit, assertingactive_connections == 0after the drain.Behaviour
active_connections,failures, backoff), applied at the next drain.backend_selection_pick_sequences_are_pinned) are unchanged.Measurements
Measured with a throwaway probe (
size_of, plustest_allocations::allocations()aroundMux::dial_backend), not committed.080351ba)Mux::dial_backend, selection to linked stream (3 runs)backend_selection_allocates_nothing_in_steady_state)stamping_a_dialled_backend_allocates_nothing)size_of::<BackendChange>()/BackendDeltaInstantfits the niche)Backend/BackendList/BackendMap/MuxClearNo new allocation, syscall or dynamic dispatch is added on the dial path.
connect(2)moved fromBackend::try_connecttoMux::dial_backend; it is the same single syscall.BackendMapborrow happens only on a failed dial.Tests: red, then green
For each mutation below, I changed the production code, quoted the failing assertion, then restored it. All pass green afterwards.
Backend::reserve_connectionreturnsOk(())withoutinc_connections.a_second_selection_observes_the_first_selections_reservation:the second selection landed on the first one's backend: the first selection did not reserve its connection (first=backend-a active=0, second=backend-a active=0)power_of_two_weighs_every_reservation:2 selections must hold 2 reservations, got [0, 0]a_failed_dial_releases_its_reservation_and_records_the_failure:selection reserves,left: 0 right: 1release_failed_dialwithoutdec_connections.a_failed_dial_releases_its_reservation_and_records_the_failureanda_synchronously_failed_dial_releases_its_reservationboth fail witha failed dial must release exactly its one reservation (saturating at 0),left: 1 right: 0Mux::dial_backendreturns the connect error without pushingDialFailed.a_synchronously_failed_dial_releases_its_reservation:the failed dial must release the reservation selection took,left: 1 right: 0inc_connectionsafter a successful connect.a_successful_dial_counts_its_connection_once:one dial must hold exactly one connection on its backend,left: 2 right: 1Notes on the new and changed tests:
a_second_selection_observes_the_first_selections_reservationreplacesa_second_selection_observes_the_first_dials_connection. It now selects twice with no dial and no drain in between. ARENAMED_TESTSentry keeps the refactor(mux): select and dial through a BackendDialer lent for one call #1550 CHANGELOG citation resolving.a_synchronously_failed_dial_releases_its_reservationdials255.255.255.255:80, which fails before any packet leaves (ENETUNREACH, orEACCESwith a default route). It asserts theErr, so a host where that connect succeeds fails the test instead of passing it.invariant_14_*inh2.rs: all 6 pass, and every assertion is unchanged. Only two things changed:reconcilehelper gains anunreachable!arm forDialFailed, since no invariant-14 scenario dials;registry.apply(delta)calls now pass a localBackendMap.stamping_a_dialled_backend_allocates_nothingnow uses a socket-freeStubSelectorwhose id comes fromBackendId::new. That is the shape a simulator will use.Docs
lib/src/protocol/mux/LIFECYCLE.md: §3.2 and §9 invariant 14.router.rs: theBackendSelectordoc, rewritten. The old doc argued that selection and dial had to be one call; it now describes reservation and release.doc/lifetime_of_a_session.mdanddoc/benchmark.md: the dial path.doc/rate-limit-design.mdandlib/src/server.rs: they now say where the non-blocking dial lives,Mux::dial_backendfor HTTP andBackend::try_connectfor TCP.e2e/src/tests/tests.rs: a TO SEE THIS RED note now points at the dial's new site and says its measurement was taken at the old one.doc/testing.md§5: how a simulator's selector mints ids, and the reservation rule it must keep.CHANGELOG.md: a BREAKING (library API) entry, listing the renames.Validation
Run on head
208ed9eb, rebased onto4918ad4f. Each exit code was checked directly, never through a pipe:cargo +nightly fmt --all -- --check-> exit 0cargo clippy --all-targets --locked -- -D warnings-> exit 0cargo clippy --all-targets --all-features --locked -- -D warnings-> exit 0cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings-> exit 0RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked-> exit 0cargo test --workspace --locked --exclude sozu-e2e-> exit 0 (1865 passed, 0 failed, 17 ignored, all ignores already on main)RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked-> exit 0 (31 passed)cargo test -p sozu-e2e --locked -- --skip tests::fuzz_tests::-> exit 0 (515 passed)cd fuzz && cargo +nightly fuzz build-> exit 0python3 .github/scripts/check_doc_citations.py-> exit 0python3 .github/scripts/check_doc_citations.py --base origin/main-> exit 0python3 .github/scripts/check_doc_citations.py --self-test-> exit 0python3 .github/scripts/check_doc_citations.py --root .github/scripts/testdata/citations-> exit 1 (the broken fixture must fail)