Skip to content

refactor(udp): move backend selection into the manager (#1340, Q6) - #1529

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/udp-select-in-core
Sep 25, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/udp-select-in-core

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Answers Question 6 of #1340 for the UDP datapath, the last place this repository routed
outside the core. H2 routes inside it as of the same issue; leaving UDP doing it the other way
would have left the repository with two architectures and no rule.

Forked off 7208c74a.

The shape

UdpManager picks the backend itself, from a BackendSource view the embedder supplies. The
shell's on_select_backend (39 lines) is gone.

Two observations reframe this as a simplification rather than a demolition, and they are the
reason the change is as small as it is:

  • on_backend_resolved set Established before emitting Output::OpenUpstream. So
    Established never meant "socket open" — it has always meant "backend chosen". Once the core
    chooses, the waiting state has nothing left to wait for.
  • Output::OpenUpstream was already the Q6 shape: the core decides, the embedder fulfils. The
    inversion collapses a two-step into the one-step H2 already has.

The view rides on ManagerInput::ClientDatagram rather than on handle_input. Three of the four
inputs cannot select, and a signature demanding a backend set from all of them would say
otherwise. A bespoke handle_client_datagram method would have kept ManagerInput's derived
Debug, but the UDP core's design is a uniform message vocabulary and splitting one message out to
dodge a hand-written Debug trades an architectural property for a cosmetic one. The hand-written
Debug elides the view and renders payload_len — what the mux's Position already does for its
backend handle.

BREAKING (library API)

Removed from sozu_lib::protocol::udp: Output::SelectBackend, ManagerInput::BackendResolved,
FlowPhase::AwaitingBackend, UdpFlow::pending_payload. ManagerInput::ClientDatagram gains
backends: &mut dyn BackendSource.

A downstream crate driving UdpManager supplies a BackendSource at the datagram and deletes its
resolve round-trip. impl BackendSource for BackendMap is the in-tree one; it delegates to
BackendMap::backend_from_cluster_id_with_key, the connection-free selector the UDP datapath
already used. Nothing on the wire, no metric, no log line, no configuration key, no CLI flag.

lib/Cargo.toml is not touched: git log -- lib/Cargo.toml shows version bumps come from
dedicated release: commits, never feature PRs.

The behaviour change, stated plainly

Every datagram of an opening burst now reaches the backend.

AwaitingBackend existed for the window between asking the shell for a backend and being told
which. The one-slot newest-wins buffer existed to hold a datagram across that window — its own
comment said it was there "so the first datagram is not lost between admission and upstream
open"
. Selection is synchronous now, so neither has anything left to do.

Before: a client sending three datagrams before the shell replied had the first two discarded and
only the third forwarded. After: all three are forwarded, and requests counts each, so a cluster
with a requests cap reaches it on the datagram it should.

Documented as behaviour in CHANGELOG.md, lib/src/protocol/udp/LIFECYCLE.md's phase diagram and
doc/testing.md's worked example. Pinned by
every_datagram_of_an_opening_burst_is_forwarded_and_counted_once, whose first half sends a
three-datagram burst and asserts all three arrive in order.

Unobservability of the removed phase — a proof, not a survey

UdpManager has 13 public entry points and every one takes &self or &mut self.
handle_input holds &mut self for its entire duration and makes no callback out of the manager
— admission only pushes to self.outputs, which the shell drains after the call returns. So no
entry point can be invoked mid-admission, and a flow cannot be observed between birth and
resolution. That is an aliasing guarantee rather than a claim about call order, and it does not
rot when someone adds a fourteenth entry point.

Enumerating the inputs confirms it: ClientDatagram, BackendDatagram and Config each need a
separate handle_input that cannot begin until the first returns; BackendResolved was the one
input delivered in that window, which is precisely why the phase existed.

Assertion accounting

No test deleted. lib/src/protocol/udp/manager.rs keeps 24 of 24 #[test] functions.

asserts label
21 tests, including the eight plumbing ones through establish() unchanged retargeted, nothing lost
abort_flow_closes_awaiting_backend_flow → a_flow_that_cannot_get_a_backend_frees_its_slot_immediately 7 → 5 subject deleted — the phase assertion and its partner
new_flow_requests_backend_then_forwards_buffered_datagram → a_new_flow_opens_an_upstream_and_forwards_its_admission_datagram 6 → 4 subject deleted — "no SendToBackend yet"; there is no yet
requests_counts_forwards_not_buffered_during_await → every_datagram_of_an_opening_burst_is_forwarded_and_counted_once 9 → 6 subject deleted — the newest-wins buffer's
check_invariants 13 → 12 subject deleted — the phase↔address negative half

92 → 85. The line worth reading is 21 tests unchanged in assertion count: that is evidence
retargeting through establish() cost nothing, not a claim that it did not.

The Guard-2 retarget has a live subject because BackendMap::backend_from_cluster_id_with_key has
three NoBackendForCluster returns, so selection can still fail — it just fails inside the
admitting call now.

The legality table's two AwaitingBackend arms were deleted rather than rewritten, so they
fall through to the existing _ => false and any transition out of that phase trips the guard
already there. A dead => true became a live check with no new assertion.

The simulator loses seed→interleaving identity, and that is expected

ACTION_TABLE index 1 is now Action::ChangeBackendSet at the same weight 16, so the
distribution over kinds of interleaving does not shrink: mutating the backend set between one
admission and the next is the interleaving BackendResolved injected, in the shape the inverted
architecture has for it. Drawing an empty set is deliberate — it is the cluster-has-nothing path.

But identity was never recoverable by re-weighting. Retiring Output::SelectBackend removes a
random_bool(0.6) draw per select from the RNG stream whatever the table says. A differing
result for a given seed across this boundary is expected and is not a regression.

The comment claiming the table stayed "draw-identical to the pre-swarm harness" was true and is now
false. It is corrected in the same changeset to say what still holds — weights sum to 100, dispatch
order matches the table, a replayed seed is byte-identical to itself — and what does not.

Every assertion in the harness survives unchanged. Model::check's four never referred to the
retired machinery: they are about flow count, drain-to-empty, the created/evicted balance and timer
coherence.

fuzz/fuzz_targets/fuzz_udp_flow.rs keeps its seven-way dispatch: arm 1 churns the backend set
instead of replying to a resolve request.

Recommendation, measured but deliberately NOT implemented

A major boundary is the natural moment to add #[non_exhaustive] to lib/src/protocol/udp/'s
public types. 11 public enums/structs there carry none today. It is not free, and the split
matters:

  • Safe candidates: Output and MetricEvent. Produced by the core and only matched outside
    it, so #[non_exhaustive] costs nothing.
  • Blocked without constructors: ManagerInput, ConfigEvent, ClusterConfig, FlowKey.
    sim/tests/udp_simulation.rs and fuzz/fuzz_targets/fuzz_udp_flow.rs construct these directly,
    and #[non_exhaustive] forbids out-of-crate construction.

So the useful form is #[non_exhaustive] on the two produced-only types now, and a builder or
#[doc(hidden)] constructor for the rest if it is wanted later. For the maintainer to decide; out
of scope here.

Verification

Feature set --no-default-features --features crypto-ring,opentelemetry,splice,simd. Every exit
code read directly, never through a pipe.

Command Exit
cargo build --locked --all-targets <flags> 0
cargo +nightly fmt --all -- --check 0
cargo clippy --all-targets --locked <flags> -- -D warnings 0
cargo test -p sozu-lib --locked <flags> 0 — 1126 passed
cargo test -p sozu --locked <flags> 0
cargo test -p sozu-e2e --locked <flags> -- --skip tests::fuzz_tests:: 0 — 447 passed
RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked 0 — 30 passed
RUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets --locked -- -D warnings 0
cargo +nightly check in fuzz/ 0
check_doc_citations.py --root . 0
check_doc_citations.py --base 7208c74a… 0 — 0 declined
check_doc_citations.py --audit --root . 0 — 7 findings, all 7 identical at base
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked 0
cargo bench -p sozu-lib --bench h2_stream_table -- --test 0

Citations remapped by content. udp/LIFECYCLE.md's sequence differs from base because this branch
deletes six citations that pointed at removed code, so the usual "sequence identical beforehand"
proof does not apply; instead I verified that none of the 22 surviving citations carried a number
absent from base
, which is what would indicate a prior manual renumber and make a remap a
double-shift. All 11 exempt spans (20 endpoints) audited on three keys — byte-identical over
the span's entire length, the base→head map from each source file's own content diff, and the
enclosing fn with an enclosing-type fallback. All 11 hold.

Two citations were symbol-ised rather than renumbered, both the #1447 reused-number class where
the prose already named the symbol.

e2e ran in a quiet window with the check and the launch made atomic: PROCS_BEFORE=0, 1-minute
loadavg 3.21 → 7.67, PROCS_AFTER=0.

Answers Question 6 of #1340 for the UDP datapath. H2 routes inside the
core as of the same issue; leaving UDP doing it the other way would have
left the repository with two architectures and no rule.

`UdpManager` picks the backend itself, from a `BackendSource` view the
embedder supplies with the datagram that needs it — three of the four
inputs cannot select, so the view rides on `ManagerInput::ClientDatagram`
rather than on every entry point. `Output::OpenUpstream` was already the
returned request the embedder fulfils, so the inversion collapses a
two-step into the one-step H2 has.

BREAKING (library API). Removed from `sozu_lib::protocol::udp`:
`Output::SelectBackend`, `ManagerInput::BackendResolved`,
`FlowPhase::AwaitingBackend`, `UdpFlow::pending_payload`;
`ManagerInput::ClientDatagram` gains a `backends` field. The maintainer
took the major rather than carry five deprecated never-constructed items.

Behaviour change: every datagram of an opening burst now reaches the
backend. `AwaitingBackend` existed for the window between asking the
shell for a backend and being told which; the one-slot newest-wins buffer
existed to hold a datagram across that window. Selection is synchronous
now, so neither has anything left to do — previously a three-datagram
burst had its first two discarded.

No test deleted: `manager.rs` keeps 24 of 24, 21 of them unchanged in
assertion count. Assertions 92 -> 85, every loss a subject that no longer
exists. `ACTION_TABLE` index 1 becomes `Action::ChangeBackendSet` at the
same weight 16; seed->interleaving identity with pre-change runs of
`udp_simulation.rs` is lost, which was never recoverable by re-weighting
because retiring the output removes a `random_bool(0.6)` draw per select
from the RNG stream. The comment claiming otherwise is corrected in the
same changeset. The fuzz target keeps its seven-way dispatch.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 747128e into main Sep 25, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the refactor/udp-select-in-core branch September 25, 2026 13:48
FlorentinDUBOIS added a commit that referenced this pull request Sep 25, 2026
…1537)

Addresses **#1341 question 4** — the shared leaf helpers the H2 core reaches through, after the
gauges (#1530), the counters (#1532) and the H2-only helpers (#1534). **#1341 reste ouverte** /
**#1341 stays open**: what Q4 still leaves is listed at the bottom.

## What changed

`Position::count_bytes_{in,out}_counter` and `Stream::generate_access_log` are leaf helpers reached
from the split H2 core **and** from `ConnectionH1`, `Mux` and `Router`, which are shells by
construction — `Router` holds `BTreeMap<Token, Connection<SessionTcpStream>>`, i.e. concrete
sockets. Both now **return** their events; each caller handles them. A core caller queues them; a
shell records them at once, because `METRICS` is legitimately a shell's.

**`impl ConnectionH2` holds one metric-macro site**, down from 41 at the start of this series.
`impl Position` holds none.

### The return is bounded and lives on the stack — no container at all

`bytes_in_event` / `bytes_out_event` return exactly one `MetricEvent`: both arms of their match emit
one, never zero, never two. `generate_access_log` returns `[Option<MetricEvent>; 2]`.

That shape was chosen over a `Vec` on a measurement: **`generate_access_log` is allocation-free
today** — zero `to_owned`, `to_string`, `format!`, `String::`, `Vec::`, `vec!`, `collect`, `clone`
or `Box::` across its 164-line body. A `Vec` return would not have added an allocation to a path
that already had some; it would have introduced the **first**, per request. A fixed array also needs
no queue on the caller, which matters because **four of the eight callers are shells and have none**
— giving `ConnectionH1` and `Mux` a queue would have been inventing core machinery for types that
do not need it.

Slots are filled **by explicit index, never through a `push` helper**. A `push` overflowing a fixed
array would silently drop an event, and a dropped `-1` drifts the aggregate upward forever — an
aggregate that only drifts up never underflows, so nothing logs and nothing saturates. The bound is
documented at the site with the two events that saturate it; a third is a compile error at every
call site rather than a truncation.

### `#[must_use]` makes the eight callers a compiler obligation

It found **all ten call sites at once** (8 production, 2 tests). None was found by hand. This is the
first `#[must_use]` under `lib/src/protocol/mux/`, and it is deliberately **not** applied
retroactively to the `MetricEvent` returns of #1530, #1532 or #1534.

`ConnectionH2::complete_server_stream` is **static** — its `stream` borrows `context.streams`, so it
can hold neither `&mut self` nor a queue — and therefore propagates through its own return, which
becomes `(Option<mio::Token>, [Option<MetricEvent>; 2])`.

### Three sites stay macros, with the measurement on the line

`names::http::ERRORS` and the two computed status-bucket keys carry `cluster_id`/`backend_id`
labels. Carrying those in an event means owned `Option<String>`s: measured,
`size_of::<MetricEvent>()` goes **24 → 48 bytes** for every queued event, and the enum loses `Copy`
— for sites that fire on **every access log**. Same trade as `names::backend::RETRY_STALE_UPSTREAM`,
and worse, because that one fires only on a stale-upstream retry. **Eight sites moved, three
documented.**

`names::http::REQUESTS` folds into `MetricEvent::RequestStarted` with the in-flight gauge's `+1`
because the two are adjacent and unconditional in the same `if`, **with nothing fallible between
them** — the criterion that allowed `RstStreamSent` to fold and forbade folding the GOAWAY pair,
where `gen_goaway` intervenes and the second `incr!` lives in its `Ok` arm.

## BREAKING: three publicly reachable items change or leave the public surface

`lib.rs` declares `pub mod protocol`, `protocol/mod.rs` declares `pub mod mux`, `mux/mod.rs`
declares `pub mod stream`, and `Position` is a `pub enum` — so all three were reachable from outside
the crate. This is declared as a break in `CHANGELOG.md`'s `Removed` section, in the same form #1529
used for its five removed `sozu_lib::protocol::udp` items.

- **Removed:** `Position::count_bytes_in_counter`, `Position::count_bytes_out_counter`.
  `Position::count_bytes_in` / `count_bytes_out` — different methods, taking `&mut SessionMetrics` —
  are untouched and stay public.
- **No longer public:** `Stream::generate_access_log` becomes `pub(super)`, and its signature gains
  a `#[must_use]` return. A downstream caller was recording nothing; there is no public replacement,
  because the returned type is not public either.
- **Additive, called out separately so it is not read as a third removal:**
  `protocol::mux::h2::record_metric` widens from module-private to `pub(super)`.

Nothing on the wire, no metric key, no log line, no configuration key, no CLI flag.

## `http.active_requests` is deliberately split across two mechanisms

H2's `+1` is an event; H1's two `+1` stay macros where they already correctly sit; the single `-1`
is an event that both record. The pair no longer travels together — and that is safe **because each
path balances**, not because the rule stopped applying. Two e2e tests pin it, one per path, and both
were seen red.

### Why the tests sample in flight rather than at the end

`AggregatedMetric::update` **saturates a gauge at zero**, so a test that only checked the value
returned to its starting point could not see a missing increment: the unpaired decrement takes 0 to
0 and reads exactly like a balanced request. Both tests hold the response at the backend and sample
twice:

```
correct            0 -> 1 -> 0
`+1` missing       0 -> 0 -> 0   (the in-flight assertion fails)
`-1` missing       0 -> 1 -> 1   (the post-completion assertion fails)
```

### Five reds, and the contrast between them is the argument

**Before this changeset**, only three were constructible, because the `-1` was a single shared site:

```
A  remove the H1 `+1`   -> H1 "in flight: wanted 1, last sample None"   H1 FAILED, H2 ok
B  remove the H2 `+1`   -> H2 "in flight: wanted 1, last sample None"   H2 FAILED, H1 ok
C  remove the `-1`      -> H1 "after completion: wanted 0, last sample Some(1)"
                           H2 "after completion: wanted 0, last sample Some(1)"   BOTH FAILED
```

**After it**, the two that only the separation makes possible:

```
D  drop the H1 shell's recording   -> "after completion: wanted 0, last sample Some(1)"  H1 FAILED, H2 ok
E  drop the H2 core's drain        -> "after completion: wanted 0, last sample Some(1)"  H2 FAILED, H1 ok
```

C, D and E fail the **same assertion with the same diagnostic**. What differs is that C takes both
paths down together and D/E take them down separately. That is the demonstration, in one line, that
the separation is real and not merely compilable.

Source files were restored byte-for-byte after every red (`cmp` verified) and the suite re-run green,
so each red came from its mutation and not from environment drift.

`last sample None` rather than `Some(0)` is not a detail: with no `+1` the key is never created, so
the gauge is **absent**, not zero. The poller returns `Option<u64>` and does not fold one into the
other.

### What these tests do NOT cover, and why that is acceptable

They exercise **one H1 caller and one H2 caller of the eight**, and the H1 one exercises
`ConnectionH1::readable`, not the pipelined `writable` site. Both limits are written in the test
headers. The other six callers have **no step of their own to forget**: `#[must_use]` obliges every
caller to handle the return, and on the core side the events are drained at a single point rather
than recorded per caller.

Eleven occurrences of `active_requests` exist under `e2e/`: ten in `mux_tests.rs`, all `//` comments
or test-title strings, and one in `h2_correctness_tests.rs` referring to `Backend::active_requests`,
the load-balancer field rather than the gauge. None of them reads the gauge — these two tests are
the first that do. The three hollow H1 tests in `mux_tests.rs` remain to be repaired; that is #1535,
a separate changeset and not this one.

## Citations

Re-measured against the new base after the rebase, not carried over: 58 citation spans re-anchored,
83 line endpoints among them, 74 distinct. Audited on both keys — byte-identical line text and
identically-named enclosing `fn`.

- **Span audit** (every citation whose number my diff moved): 1 text mismatch, 0 enclosing-`fn`
  changes. The one mismatch is the pinned block in `doc/h2_mux_internals.md` that quotes code this
  changeset **changed** (`stream.generate_access_log(` became `let events =
  stream.generate_access_log(`). It was re-quoted by hand rather than renumbered, its prose updated
  to say the method is now `#[must_use]` and that `complete_server_stream` propagates through its
  return, and its range corrected from 8 lines to the 7 the block shows.
- **Full audit** (every citation pointing into any `.rs` this changeset touches, moved or not):
  110 endpoints, **0 mismatches**, 2 no-inverse — and both no-inverse hits are that same re-quoted
  block, which by construction has no counterpart line in the base.

## Still left in Q4

- `names::backend::RETRY_STALE_UPSTREAM` — the last macro site in the core, with its 24 → 48
  measurement on the line.
- The three labelled sites in `generate_access_log`, for the same reason.
- `ReplayCapture`'s `Drop` and `Stream::arm_upstream_replay` are **already correct**: their only
  production caller is `ConnectionH1::start_stream`, which is its own shell. #1341's claim that
  `ConnectionH2`'s was the only metrics `Drop` in `lib/src/` is inaccurate — there are two — but the
  one it missed sits where a metrics `Drop` belongs. That should be recorded as closed, not open.

`mux/mod.rs`'s two `log_context!` / `log_context_lite!` peer reads were on this list until #1536
landed; they are no longer open and the item is struck from it.

## Rebased onto `aaf2a6aa` (#1536)

This branch was rebased from `fa11f549` onto `aaf2a6aa` after #1536 merged, and every number below
was re-measured there — a result obtained on the old base is not a result on the new one.

#1536 changed five files. Measured with `comm -12` over the two file lists rather than assumed,
exactly three of them are also changed here — `lib/src/protocol/mux/h2.rs`,
`lib/src/protocol/mux/mod.rs` and `CHANGELOG.md` — and the rebase resolved with no conflict in any
of the three. In `h2.rs` it widened `ConnectionH2::peer_address` to `pub(super)` on a single line,
which shifts nothing. In `mod.rs` it rewrote the two log macros and added tests, in regions my diff
does not enter. In `CHANGELOG.md` its entry went to the head of `### 🐛 Fixed` while mine sit at the
tails of `### 🔄 Changed` and `### ➖ Removed`. Its other two files are untouched here:
`connection.rs`, which gains the `Connection::peer_address` accessor that is the whole reason
`ConnectionH2::peer_address` had to widen, and `doc/observability.md`.

The reference sweep was re-run on the new base and found one hit it had missed: a comment in
`e2e/src/tests/h2_tests.rs` naming `Position::count_bytes_in_counter`, a method this changeset
removes. It now names `Position::bytes_in_event` and says the event is queued on the core and
recorded by the shell. The edit is line-count-neutral, and nothing cites a line in that file. Every
other surviving reference names `generate_access_log` as a symbol without asserting its return type,
its visibility, or that it emits the metric itself — `lib/src/http.rs`, `lib/src/https.rs`,
`lib/src/metrics/mod.rs`, `lib/src/metrics/local_drain.rs`, `doc/observability.md`,
`doc/lifetime_of_a_session.md`, `kawa_h1/{answers,editor}.rs` and two `LIFECYCLE.md` — so each is
unaffected: the three labelled `incr!` sites those comments describe are exactly the three that stay
macros.

## Validation

All re-run at `0d7986b8b494d2a9af28efdca406b6dbbfc4d229` on the new base, not carried over from the
old one. Exit codes read directly, never through a pipe.

- `cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd` — 0
- `cargo +nightly fmt --all -- --check` — 0
- `cargo clippy --all-targets --locked --no-default-features --features … -- -D warnings` — 0
- `cargo test -p sozu-lib …` — **1148 passed, 0 failed, 5 ignored**; no test deleted, no `#[ignore]`
  added, and the `#[test]` count is unchanged in all five `lib/src/protocol/mux/` files touched
  (`h1.rs` 5, `h2.rs` 105, `mod.rs` 24, `stream.rs` 6, `router.rs` 29 — identical to `aaf2a6aa`)
- `cargo test -p sozu …` — 226 passed, 0 failed
- `cargo test -p sozu-e2e … -- --skip tests::fuzz_tests::` — **449 passed, 0 failed** (447 + the two
  new balance tests), run under a three-criterion guard evaluated and launched in ONE statement: no
  `sozu_e2e` child, no `cargo test -p sozu-e2e` parent, 1-minute load average **3.94** at launch.
  The guard is a start condition: load rose to 21.9 mid-run under a concurrent `cargo` build in a
  different checkout, while the `sozu_e2e` child count stayed at 1 throughout, so the port-sensitive
  criterion held for the whole run and the pass is not a pass under port contention
- `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked` — 30 passed, 0 failed
- `RUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets --locked -- -D warnings` — 0
- `check_doc_citations.py` `--self-test` / `--root .` / `--base aaf2a6a` / `--audit --root .` — all 0.
  The advisory audit reports 7 of 80 on this branch; a detached checkout of `aaf2a6aa` reports the
  same 7 of 80, at the same citing lines, differing only in the four `h2.rs` numbers my diff moved
  (2324→2364, 3302→3343, 3909→3951, 5114→5160) — each verified to land on a byte-identical line.
- `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` — 0
- `cargo bench -p sozu-lib --bench h2_stream_table -- --test` — 0

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 26, 2026
…all (#1550)

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 `Ref`s.

#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]>
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