Skip to content

refactor(mux): select and dial through a BackendDialer lent for one call - #1550

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/mux-backend-dialer
Sep 26, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/mux-backend-dialer

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Question 12, second part, of #1340: backend selection stops reaching the proxy handle.

#1340 reste ouverte — L7Proxy::backends still has to be decided (see below), so this PR references the issue and does not close it.

What changes

Router::backend_from_request took Rc<RefCell<dyn L7Proxy>> for exactly one purpose: reaching L7Proxy::backends to pick a backend. It now takes &mut dyn BackendDialer, a capability lent for one call, whose single method select_and_dial selects a backend and dials it, and returns the opaque BackendId together with its socket. Mux::dial_backend implements it (RegistryDialer, lib/src/protocol/mux/mod.rs) over the worker's BackendMap and the session's BackendRegistry, so the id is minted on the embedder's side. Router::get_backend_for_sticky_session is gone: it and backend_from_request read no Router field at all.

Production references in lib/src/protocol/mux/router.rs:

before after
L7Proxy 3 (import, backend_from_request, get_backend_for_sticky_session) 0
Rc<RefCell<Backend>> 2 (the two return types of that chain) 0
.backends() call sites in lib/ + bin/ 2 (both in get_backend_for_sticky_session) 0

The remaining L7Proxy mentions in the file are doc comments and the #[cfg(test)] fixtures of Router::plan_connect, which never called backend_from_request.

This contradicts the letter of the 2026-09-24 decision, deliberately

The decision recorded on #1340 asks for a read-only view of backend load state supplied at each selection point, and the follow-up comment of 2026-09-25 asked for "the same shape" RoutingView (#1525) gave cluster configuration. That shape cannot select:

  • RoutingView is an immutable borrow of immutable data. Selection mutates: the RoundRobin cursor, BackendList::fail_open_warned, PeakEWMA::observe under LoadMetric::ConnectionTime, the Maglev table, and the availability latch BackendMap::record_cluster_availability keeps.
  • A read-only snapshot of the load counters cannot be lent without allocating: each backend sits behind its own RefCell, so handing the core N backends at once needs a container of N Refs.

#1529 already settled this in practice for UDP: BackendSource (lib/src/protocol/udp/mod.rs) is a &mut dyn the core calls and the embedder implements, and its doc says why it is &mut self. BackendDialer follows #1529, not #1525.

Why there is no staleness to bound

The question left open on #1340 was what staleness is acceptable between borrowing the view and the dial. Measured, the answer is that there is no window: BackendMap::backend_from_cluster_id selects and calls Backend::try_connect under one borrow_mut, the worker is single-threaded, mio::net::TcpStream::connect is non-blocking, and nothing between the two yields (push_event is a thread-local queue push). The guarantee is already written down as LIFECYCLE §9 invariant 14, "Drain before any read".

It holds only while selection and dial are one step, because Backend::try_connect raises active_connections directly, not through a BackendDelta, so no drain point covers it. A dialer that returned a chosen backend for the caller to dial later would open a window the code has never had, and would then need a freshness policy, a BackendChange::ConnectionOpened, and a way back for retry_policy.fail() / failures += 1. So the signature couples the two: DialedBackend carries the BackendId and the socket, and a selection that has not been dialled is not a value that can exist.

Router has no lifetime parameter, so it cannot keep the &mut it is lent. The Rc<RefCell<dyn L7Proxy>> it replaces was 'static and Clone, and nothing stopped it being stored.

Why a trait rather than &mut BackendMap

A bare &mut BackendMap would be smaller, and AGENTS.md asks for the smallest change. But it would leave backend_from_request handing back an Rc<RefCell<Backend>>: turning that handle into a BackendId takes the session's BackendRegistry too, and only an adapter holding both can do it on the embedder's side. So the trait is required by the property that Rc<RefCell<Backend>> leaves router.rs, not added for taste. It is also the seam a simulator would plug into: sim/tests/h2_simulation.rs does not reach backend selection today (SimListener::frontend_from_request answers an error). The justification is written at the trait.

The sticky cookie is resolved by the dialer, not carried on BackendId

backend_from_request needs the chosen backend's sticky_id to answer with a Set-Cookie. Carrying it on BackendId would have been the obvious move, and it is wrong: BackendList::add_backend (lib/src/backends.rs), on re-adding an existing backend, rewrites sticky_id in place on the live Rc<RefCell<Backend>>. BackendId's own doc limits it to fields that cannot change for the life of a registry entry; sticky_id would be exactly the cached copy of mutable state it rules out, and it would pass every test and break on the first configuration update. The dialer reads the cookie under the selection's borrow and returns it, only on the sticky path — the same one String the old code built there.

frontend_should_stick is mapped explicitly at the caller

The old code matched on (frontend_should_stick, cookie) and sent (false, Some(_)) to the load balancer. backend_from_request now writes if frontend_should_stick { Affinity::Sticky(cookie) } else { Affinity::Unpinned } explicitly. The dialer takes an Affinity rather than a bare Option<&str> because it must know whether to resolve a cookie even when the request carried none; with the enum, a cookie on a non-sticky frontend has no variant to travel in.

Allocation: neutral, not zero

No allocation is added or removed on the selection path. &mut dyn is a fat pointer and the adapter is two &mut on the stack. The path was not allocation-free before this change and is not after: BackendList::available_backends builds a fresh Vec<Rc<RefCell<Backend>>> of the candidates on every selection (up to three on the degraded paths), plus one Rc bump per candidate — PowerOfTwo's doc already records it. Removing that means changing LoadBalancingAlgorithm::next_available_backend for six implementations; it is separate work and deliberately not widened into here.

L7Proxy::backends — candidate for a separate removal

It now has no caller. Removing it touches lib/src/lib.rs and the HttpProxy / HttpsProxy impls, so it is not in this PR. The TCP proxy is unaffected either way: lib/src/tcp.rs reaches the map through the TcpProxy::backends field, not the trait method, and TcpProxy does not implement L7Proxy.

Tests

Router::backend_from_request had no test before this change — its only references were its definition and its one call site. Two are added in router.rs (backend_dialer_tests), each owning its BackendMap and BackendRegistry and driving the production RegistryDialer:

  • a_second_selection_observes_the_first_dials_connection — two backends on bound loopback listeners, LeastLoaded { metric: Connections }, two dials; they must land on different backends, one connection each. LeastLoaded is required: under the default round-robin the test would pass without reading any load. It discriminates the capability from a snapshot view without implementing the rejected form: a view frozen before the first selection would send both to backend-a.
    • Seen red: removing self.inc_connections() from Backend::try_connect first trips that function's own pair debug_assert!, so the test's assertion is not what fired. Removing the pair assertion as well, as a refactor moving the increment out of the dial would, makes the test's own assertion fire: (first=backend-a active=0, second=backend-a active=0). Restored: green.
  • a_cookie_pins_only_a_frontend_that_sticks — a non-sticky frontend ignores a cookie naming backend-b and answers with no cookie; a sticky one follows it; a sticky one with no cookie answers with the chosen backend's id.
    • Seen red: mapping every request to Affinity::Sticky first trips the new pair debug_assert! in backend_from_request; with that neutralised too, the test's own assertion fires: a frontend that does not stick must ignore the client's cookie, left: "backend-b", right: "backend-a". Restored: green.

sozu-lib goes from 1129 to 1131 unit tests.

Docs

  • LIFECYCLE.md: the §3.2 paragraph that named this as "Question 12's second part" now describes the dialer, and §9 invariant 14's "Drain before any read" names active_connections as the counter outside the ledger and why selection and dial stay one call.
  • doc/benchmark.md: the connect is reached through select_and_dial → Backend::try_connect.
  • doc/lifetime_of_a_session.md: step 3 no longer says the connect happens in Router::plan_connect, which performs no syscall.
  • 17 line citations in LIFECYCLE.md and doc/testing.md (22 spans counting both ends of ranges) moved by +5 in mod.rs and −1 in router.rs. To keep the shift small — another change to mod.rs is in flight — the new code sits after the cited regions. Each span was re-anchored from an exact base→head line mapping and audited on both keys: the new number resolves, and the text at every line of the span, range interiors included, is identical to the base (0 mismatches over 103 lines; the audit was first shown to flag a deliberately wrong anchor). check_doc_citations.py --audit reports the same 7 findings on this branch as on main, none of them on a re-anchored span.
  • CHANGELOG.md: entry at the end of 🔄 Changed.

Commands run

All on the final head 67df0274, toolchain anchored on the pinned ~/.rustup/toolchains/1.93.1-x86_64-unknown-linux-gnu/bin/cargo unless marked (the workstation's cargo shim resolves to 1.98.1). Each step is judged on its own exit code, never through a pipe.

  • cargo +nightly fmt --all -- --check → exit 0
  • RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked → exit 0 on 1.93.1, and exit 0 on the 1.98.1 shim. The first push missed this step and CI's msrv-full job caught it: BackendDialer's public doc linked to the private RoutingView. The link is now a plain code span; no lint was allowed and nothing was made public. The command was seen red first on both toolchains with the link put back (error: public documentation for BackendDialer links to private item RoutingView, exit 101).
  • cargo clippy --all-targets --locked -- -D warnings → exit 0 (-v shows the 1.93.1 clippy-driver)
  • cargo clippy --all-targets --all-features --locked -- -D warnings → exit 0
  • cargo build --all-features --locked → exit 0 in a fresh target directory. In the worktree's own target/ it fails in aws-lc-fips-sys's build script (aws-lc/util/go_tests.txt missing), before any Sōzu crate compiles. That failure comes from stale build-script state, not from this change: the same command on this tree in a fresh target passes, origin/main in a fresh target passes, and the diff touches no manifest or lockfile. The 1.93.1 cargo doc above also ran in the fresh target.
  • cargo test --workspace --locked --exclude sozu-e2e → exit 0, 1541 passed, 0 failed
  • RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked → exit 0, 30 passed
  • cargo test -p sozu-e2e --locked -- --skip tests::fuzz_tests:: → exit 0, 449 passed, 0 failed, 4 filtered (the fuzz_tests wrappers, skipped as in CI). The tree was the same before and after. The run started only after a guard found no concurrent test … sozu-e2e run of a real rustup/toolchains/*/bin/cargo, and the guard was first shown to detect one.
  • python3 .github/scripts/check_doc_citations.py --base origin/main → exit 0; --self-test → exit 0; broken fixture → exit 1

Impact

No protocol, security, configuration, metric or behaviour change. The per-(cluster, source-IP) gate, the dial order, the gauge block and the CWE-400 rollback in Mux::dial_backend are untouched.

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

Router::backend_from_request took Rc<RefCell<dyn L7Proxy>> for one
purpose: reaching L7Proxy::backends to pick a backend. It now takes
&mut dyn BackendDialer, whose single method selects a backend and dials
it, and returns the opaque BackendId with its socket. Mux::dial_backend
implements it over the worker's BackendMap and the session's
BackendRegistry, so the id is minted on the embedder's side.
Router::get_backend_for_sticky_session read no Router state and is gone.
Production references in lib/src/protocol/mux/router.rs: L7Proxy 3 -> 0,
Rc<RefCell<Backend>> 2 -> 0.

The shape is the UDP core's BackendSource, not RoutingView. Selection
mutates (round-robin cursor, fail-open latch, PeakEWMA, Maglev table,
availability latch), so an immutable view cannot select, and a snapshot
of N backends each behind its own RefCell needs a container of Refs.

Selection and dial stay one call. Backend::try_connect raises
active_connections at the dial, outside the delta ledger, so invariant
14's drain-before-read rule holds only while nothing separates reading
the counters from the dial. Returning the backend and its socket
together makes an undialled selection unrepresentable, and Router has
no lifetime parameter, so it cannot keep the dialer it is lent.

The sticky cookie is resolved by the dialer under the selection's
borrow instead of being carried on BackendId: BackendList::add_backend
rewrites Backend::sticky_id in place on a live registry entry. The
caller maps frontend_should_stick to an Affinity explicitly, keeping the
old (false, Some(_)) arm: a frontend that does not stick ignores the
client's cookie.

No behaviour change and no allocation added or removed. The candidate
Vec that BackendList::available_backends builds per selection is
untouched and out of scope. L7Proxy::backends now has no caller;
removing it from the trait is left for separate work.

backend_from_request had no test. Two are added:
a_second_selection_observes_the_first_dials_connection and
a_cookie_pins_only_a_frontend_that_sticks, each seen red against a
sabotage of the property it holds.

Refs #1340 (Question 12, second part). #1340 stays open.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the refactor/mux-backend-dialer branch from 301b6fe to 67df027 Compare September 26, 2026 09:36
@FlorentinDUBOIS
FlorentinDUBOIS merged commit e2fd5f0 into main Sep 26, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the refactor/mux-backend-dialer branch September 26, 2026 10:54
FlorentinDUBOIS added a commit that referenced this pull request Sep 29, 2026
Refs #1684 (step 1 of the `/goal` prompt posted there: fix the record before the maintainer gate).

## What was wrong

`lib/src/protocol/mux/LIFECYCLE.md` §3.2 said `L7Proxy::backends` "has no caller left", the CHANGELOG entry for the `BackendDialer` refactor (#1340 Q12, second part) said it "now has no caller", and #1550's description counted `.backends()` in `lib/` + `bin/` as 2 → 0.

Measured on `origin/main` at `3ed6e8a6`:

```
$ git grep -n '\.backends()' -- lib bin
lib/src/protocol/mux/mod.rs:2322:            let backends = proxy.borrow().backends();   # Mux::dial_backend (production)
lib/src/protocol/mux/router.rs:3553:        fixture.proxy.borrow().backends().borrow_mut().add_backend(   # test fixture
```

`Mux::dial_backend` still calls it to reach the `BackendMap` its `RegistryDialer` lends to `Router::backend_from_request`. The refactor moved the call out of `router.rs`; it did not remove it. The claims that production references to `L7Proxy` and `Rc<RefCell<Backend>>` in `router.rs` went to zero still hold.

## Change

- `LIFECYCLE.md` §3.2 names `Mux::dial_backend` as the remaining production caller and points the removal question to #1684.
- `CHANGELOG.md`: the sentence in the original entry is amended, and a correction note under 🔄 Changed names the caller and the measured count.

Documentation only, no code change. Sweep: `git grep -n 'L7Proxy::backends' -- ':!CHANGELOG.md'` hits only the corrected §3.2 line; no other copy of the claim in `doc/` or any `LIFECYCLE.md`. `doc/testing.md` is unaffected (no simulator change).

## Validation

- `git grep -q 'has no caller left' -- lib/src/protocol/mux/LIFECYCLE.md` -> exit 1, prints nothing
- `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 (broken fixture fails, as required)
- `python3 .github/scripts/check_doc_citations.py --audit` -> exit 0; output byte-identical to the same run on an `origin/main` tree (same 3 advisory findings, none added)



Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 29, 2026
Refs #1684. This is the G1 = (a) step the maintainer chose in #1684 (comment).

Based on `origin/main` `05ac4f9c`, which includes the merged #1693. This PR replaces #1693's §3.2 wording and its sentence in the #1550 CHANGELOG entry now that the method is gone. #1693's own correction entry stays as the record. The code is byte-identical to the tree validated below (`d9ce2a02` + this change): rebasing onto #1693 changed only `CHANGELOG.md` and `LIFECYCLE.md`. After the rebase I re-ran the four citation modes, the grep criterion and `cargo +nightly fmt --all -- --check`: citations exit 0, 0, 0 and 1 (the broken fixture), the grep exits 1, and fmt exits 0.

## What changes

`L7Proxy::backends` had one production caller, `Mux::dial_backend`. On every dial it borrowed the proxy and cloned the `Rc<RefCell<BackendMap>>` to lend the map to `Router::backend_from_request`.

- `Mux` gains `pub(crate) backends: Rc<RefCell<BackendMap>>`, filled at construction, and `Mux::dial_backend` takes `&RefCell<BackendMap>` from it.
- `HttpSession::new` gains a `backends` parameter, and `HttpProxy::create_session` passes `Rc::clone(&self.backends)`. `create_session` runs under the proxy's `borrow_mut`, so the session cannot read the map through `proxy` at that point.
- The expect-proxy upgrade (`HttpSession::upgrade_expect`) and the TLS upgrade (`HttpsSession::upgrade_handshake`) read `self.proxy.borrow().backends` once. `HttpProxy` and `HttpsProxy` set that field only in their constructors and never reassign it, so each session sees the same map as before.
- Removed: the trait method (`lib/src/lib.rs`), its `HttpProxy` and `HttpsProxy` impls, and the `unreachable!` bodies in the `NoBackendProxy` and `RemoveOnlyProxy` test doubles (`mux/mod.rs`).
- The routing fixture in `router.rs` keeps its own handle on the map: `RoutingFixture::backends`.
- The 6 test `Mux` literals in `mux/mod.rs` and the one in `mux/h2.rs` get `backends: Rc::default()`.
- Docs: `LIFECYCLE.md` §3.2, a new CHANGELOG ➖ Removed entry shaped like #1615's, and the #1550 entry's sentence is amended.

No behaviour change and no new test: this moves a handle, and the existing dial tests cover the path.

## Measurements

Measured with a throwaway probe, not committed. Before is `origin/main` `d9ce2a02`; after is this change on `d9ce2a02` (`e563388b`, identical code to the current head).

| | before | after |
|---|---|---|
| `size_of::<MuxClear>()` | 4976 B | 4984 B |
| `size_of::<MuxTls>()` | 6152 B | 6160 B |
| heap allocations for one `Mux::dial_backend`, selection to linked stream (`test_allocations::allocations()` around the call in `a_dial_moves_the_planned_cluster_id_into_the_backend_connection`, 3 runs each) | 6, 6, 6 | 6, 6, 6 |

Each dial now skips one `RefCell` borrow of the proxy and one `Rc` clone and drop. Each session pays one clone at construction.

## Validation

All commands ran on the rebased head. Each exit code was checked directly, not through a pipe.

- `git grep -qE 'fn backends|\.backends\(\)' -- lib/src/lib.rs lib/src/protocol/mux` -> exit 1, prints nothing
- `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
- `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` -> exit 0
- `cargo test --workspace --locked --exclude sozu-e2e` -> exit 0 (1820 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 (502 passed)
- `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)
- `python3 .github/scripts/check_doc_citations.py --audit` -> output identical to the same run on an `origin/main` tree

Reference sweep: `git grep -nE 'L7Proxy::backends|\.backends\(\)|fn backends\b' -- ':!CHANGELOG.md'` finds nothing left in code or docs. `bin/`, `e2e/` and `sim/` never implemented or called the method.




Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 30, 2026
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/main` `4918ad4f`, which includes #1698 (G1), #1700 (G3), #1704 and #1705.

## Design

- **Selection reserves.**
  - `BackendMap::reserve_backend(cluster, now)` and `reserve_sticky_backend(cluster, cookie, now)` choose a backend, then raise its `active_connections` by one (`Backend::reserve_connection`). The raise happens under the same borrow as the choice.
  - The next selection weighs that reservation exactly as it weighed the count `Backend::try_connect` took at the dial.
  - Nothing connects during selection.
  - The empty and no-candidate handling that `backend_from_cluster_id` had moved into a private `BackendMap::select_backend`, which both paths share.
- **The embedder dials.**
  - The router's seam returns a backend and no socket.
  - `Mux::dial_backend` connects to `BackendId::address` after the selection borrow is released. The address travels inside `BackendId`, which is the `(BackendId, SocketAddr)` shape the maintainer asked for.
- **A failed dial releases, through the ledger.**
  - A `connect(2)` error pushes the new `BackendChange::DialFailed(Instant)` and returns `BackendError::ConnectionFailures`.
  - Applying `DialFailed` calls `Backend::release_failed_dial`, which does `dec_connections`, `failures += 1` and `retry_policy.fail(at, rng)`.
  - `BackendRegistry::apply_all` now takes the worker's `&RefCell<BackendMap>`. It borrows it only in the `DialFailed` arm, to draw the backoff jitter from the map's generator; every other change leaves the map alone.
  - The existing drain before each `Router::plan_connect` applies the release before the next selection reads the counters. The backend then sits exactly where a failed `Backend::try_connect` left it.
- **A successful dial keeps the reservation** as its connection's count. `ConnectionClosed` releases it, as before.
- **A factory `sim/` can reach:** `pub fn BackendId::new(slot, backend_id, address)`.
  - A slot means something only to the registry that issued it; the mux still mints through `BackendRegistry::id_for`.
  - A selector holds no socket, so a simulator implements one without `mio`. `git grep -q mio -- sim/Cargo.toml` still exits 1.
- **LIFECYCLE §9, invariant 14** gains the bullet "Selection reserves, failure releases". The "Drain before any read" bullet drops its argument for selecting and dialling in one call.
- **Unchanged:** the TCP proxy (`tcp.rs`) still calls `BackendMap::backend_from_cluster_id` and `Backend::try_connect`.

### Renames, for #1706 (#524, `feat/lb-affinity-key-l7-tcp`)

#1706 adds an affinity `key` to `select_and_dial` and `backend_from_cluster_id`. Whichever PR merges second rebases onto the other:
- `router::BackendDialer` → `router::BackendSelector`
- `BackendDialer::select_and_dial` → `BackendSelector::select`, same `(cluster_id, affinity)` parameters
- `router::DialedBackend` → `router::SelectedBackend`, which drops its `socket` field
- crate-private `RegistryDialer` → `RegistrySelector`
- `Router::backend_from_request` now returns `BackendId`, where it returned `(TcpStream, BackendId)`

`BackendMap::backend_from_cluster_id` keeps its signature. The mux now calls the new `reserve_backend` and `reserve_sticky_backend`, so #1706's `key` belongs on those as well.

### Pre-existing `active_connections` leak, not fixed here

Three exits of `Mux::dial_backend` after a successful `connect(2)` drop the new connection without releasing its connection count:
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. It releases the `active_requests` charge and the gauges, but not `active_connections`.

On `main` each of these already leaked the `+1` that `Backend::try_connect` took on success. Now each leaks the reservation, which is the same `+1` taken 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::ConnectionClosed` for the reserved slot on all three exits, the same release a closing connection emits. Pin it with one test per exit, asserting `active_connections == 0` after the drain.

### Behaviour

- A successful dial behaves the same.
- A failed synchronous dial leaves the same end state (`active_connections`, `failures`, backoff), applied at the next drain.
- The AllDown → Available availability event now fires after a successful selection rather than after a successful connect.
- The pinned pick sequences (`backend_selection_pick_sequences_are_pinned`) are unchanged.

## Measurements

Measured with a throwaway probe (`size_of`, plus `test_allocations::allocations()` around `Mux::dial_backend`), not committed.

| | before (`080351ba`) | after |
|---|---|---|
| heap allocations per `Mux::dial_backend`, selection to linked stream (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 |
| `size_of::<BackendChange>()` / `BackendDelta` | 16 / 24 B | 16 / 24 B (`Instant` fits the niche) |
| `Backend` / `BackendList` / `BackendMap` / `MuxClear` | 208 / 72 / 472 / 4984 B | unchanged |

No new allocation, syscall or dynamic dispatch is added on the dial path.
- The `connect(2)` moved from `Backend::try_connect` to `Mux::dial_backend`; it is the same single syscall.
- The `BackendMap` borrow 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.

- **Mutation:** `Backend::reserve_connection` returns `Ok(())` without `inc_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: 1`
- **Mutation:** `release_failed_dial` without `dec_connections`.
  - `a_failed_dial_releases_its_reservation_and_records_the_failure` and `a_synchronously_failed_dial_releases_its_reservation` both fail with `a failed dial must release exactly its one reservation (saturating at 0)`, `left: 1 right: 0`
- **Mutation:** `Mux::dial_backend` returns the connect error without pushing `DialFailed`.
  - `a_synchronously_failed_dial_releases_its_reservation`: `the failed dial must release the reservation selection took`, `left: 1 right: 0`
- **Mutation:** an extra `inc_connections` after a successful connect.
  - `a_successful_dial_counts_its_connection_once`: `one dial must hold exactly one connection on its backend`, `left: 2 right: 1`

Notes on the new and changed tests:
- `a_second_selection_observes_the_first_selections_reservation` replaces `a_second_selection_observes_the_first_dials_connection`. It now selects twice with no dial and no drain in between. A `RENAMED_TESTS` entry keeps the #1550 CHANGELOG citation resolving.
- `a_synchronously_failed_dial_releases_its_reservation` dials `255.255.255.255:80`, which fails before any packet leaves (`ENETUNREACH`, or `EACCES` with a default route). It asserts the `Err`, so a host where that connect succeeds fails the test instead of passing it.
- `invariant_14_*` in `h2.rs`: all 6 pass, and every assertion is unchanged. Only two things changed:
  - their `reconcile` helper gains an `unreachable!` arm for `DialFailed`, since no invariant-14 scenario dials;
  - two `registry.apply(delta)` calls now pass a local `BackendMap`.
- `stamping_a_dialled_backend_allocates_nothing` now uses a socket-free `StubSelector` whose id comes from `BackendId::new`. That is the shape a simulator will use.

## Docs

- `lib/src/protocol/mux/LIFECYCLE.md`: §3.2 and §9 invariant 14.
- `router.rs`: the `BackendSelector` doc, 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.md` and `doc/benchmark.md`: the dial path.
- `doc/rate-limit-design.md` and `lib/src/server.rs`: they now say where the non-blocking dial lives, `Mux::dial_backend` for HTTP and `Backend::try_connect` for 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 onto `4918ad4f`. 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 (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 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)



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.

1 participant