Skip to content

refactor(mux): read cluster configuration from a borrowed routing view (#1340, Q6) - #1525

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-router-cluster-view
Sep 25, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-router-cluster-view

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Continues Question 6 of #1340. Stacked on #1519; retarget to main when that lands.

What moved

Router::plan_connect made three reads through Rc<RefCell<dyn L7Proxy>>. Two of them —
L7Proxy::clusters and L7Proxy::kind — are pure, and now arrive as RoutingView, built once
per decision by Mux::ready_inner from a single proxy.borrow(). Router::route_from_request no
longer takes the handle at all.

Same mechanism as Q12's backend view, applied a second time rather than reinvented: a view in with
a defined staleness, a result out.

The staleness is one routing decision. Every read inside a plan_connect call sees the same
cluster map. That is marginally stronger than what it replaces, and deliberately so: the two
sites used to take separate proxy.borrow()s — one in plan_connect, one in route_from_request
— so a cluster update landing between them would have been half-observed. None can interleave
(clusters() is owned by the worker's command loop, and a stream is drained from pending_links
inside the very ready() pass that queued it), so this closes a window that was never open
rather than changing a behaviour that was.

Counts — and a prediction of mine that was wrong

I told the reviewer this PR would leave L7Proxy flat at 5 because proxy stays in the signature
for the limit gate. That was wrong, and in the useful direction: route_from_request's proxy
parameter disappears outright, so the count drops.

Comment lines filtered, production and test split:

Measure, in lib/src/protocol/mux/router.rs before after
proxy.borrow() reads inside Router::plan_connect 3 1
Rc<RefCell<dyn L7Proxy>> production code references 5 4

The four that remain are the import, the plan_connect parameter (for the gate), and
Router::backend_from_request / Router::get_backend_for_sticky_session.

A second correction, so the next step is not mis-predicted either. I previously said 2a-ii-b
would take router.rs from 5 to 0. It will not. Removing the gate takes the plan_connect
parameter, leaving 3: the import and the two selection helpers, which Mux::dial_backend calls
and which still reach L7Proxy::backends. Getting those to zero means giving selection a
borrowed view of backend load state — that is Q12 part 2, a further step, not 2a-ii-b.

What is deliberately still on the handle

The per-(cluster, source-IP) limit gate. It is not a read: it calls cluster_ip_at_limit and
track_cluster_ip, which mutates SessionManager::connections_per_cluster_ip — worker-global
state keyed on (cluster, ip) across every session, read again by lib/src/tcp.rs's own gate for
the TCP proxy. A read-only view cannot carry it, so it becomes a returned step of its own in the
next PR.

That is also why a_dial_plan_performs_no_effect_of_its_own (from #1519) keeps its scoped doc
comment: plan_connect is not pure yet, and that test's Context uses session_address: None,
which skips the gate.

Test

the_routing_decision_reads_cluster_config_from_the_view hands the decision a view that
disagrees with the proxy about cluster.http2 — the fixture registers H2_CLUSTER with
http2: Some(true), the view says Some(false) — and asserts the plan follows the view. A
premise assertion pins the disagreement first, so the test cannot silently degrade into tautology
if the fixture changes.

Seen red by restoring the cluster read to the handle:

the plan must carry the view's `http2`, not the proxy's — `h2: true` means the decision read
`L7Proxy::clusters` behind the view

The production diff and the test share no string literal, so the fix is not test-shaped.
cargo test -p sozu-lib goes 1127 → 1128 passed, this test and nothing else.

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 <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 — 1128 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, unchanged
RUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets --locked -- -D warnings 0
check_doc_citations.py --root . 0
check_doc_citations.py --base <2a-i head> 0
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. All 13 exempt spans (17 endpoints) audited on three keys:
byte-identical over the span's entire length rather than only its endpoints, the base→head line
map taken from each source file's own content diff, and the enclosing fn matched by name with an
enclosing-type fallback. All 13 hold; 0 spans lacked an enclosing fn.

e2e was run in a quiet window — 1-minute loadavg and pgrep sozu_e2e | wc -l recorded before and
after.

No sozu-sim scenario, workload weight or assertion is touched; this PR does not modify any file
under sim/.

`Router::plan_connect` made three reads through
`Rc<RefCell<dyn L7Proxy>>`. Two of them — `L7Proxy::clusters` and
`L7Proxy::kind` — are pure, and now arrive as `RoutingView`, built once
per decision by `Mux::ready_inner` from a single `proxy.borrow()`.
`Router::route_from_request` no longer takes the handle at all.

Same mechanism as #1340 Question 12's backend view, applied a second time
rather than reinvented: a view in with a defined staleness, a result out.
The staleness is one routing decision — every read inside a
`plan_connect` call sees the same cluster map. That is marginally
stronger than what it replaces: the two sites used to take separate
`proxy.borrow()`s, so a cluster update landing between them would have
been half-observed. None can interleave, because `clusters()` is owned by
the worker's command loop and a stream is drained from `pending_links`
inside the very `ready()` pass that queued it, so this closes a window
that was never open rather than changing a behaviour that was.

Measured with comment lines filtered: `proxy.borrow()` reads inside
`Router::plan_connect` go 3 -> 1, and `Rc<RefCell<dyn L7Proxy>>`
production code references in `mux/router.rs` go 5 -> 4 — the import, the
`plan_connect` parameter, and the two selection helpers.

The read still taken through the handle is the per-(cluster, source-IP)
limit gate, deliberately not in this change: it calls
`cluster_ip_at_limit` AND `track_cluster_ip`, a mutation of worker-global
state, so it cannot become a read-only view. It becomes a returned step
of its own.

No behaviour change.
`the_routing_decision_reads_cluster_config_from_the_view` hands the
decision a view that disagrees with the proxy about `cluster.http2` and
asserts the plan follows the view; seen red by restoring the read to the
handle, which reports `h2: true`. The production diff and the test share
no string literal. `cargo test -p sozu-lib` goes 1127 -> 1128.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the refactor/h2-router-cluster-view branch from 2e02720 to b9f56c1 Compare September 25, 2026 12:42
@FlorentinDUBOIS
FlorentinDUBOIS changed the base branch from refactor/h2-router-connect-plan to main September 25, 2026 12:42
@FlorentinDUBOIS
FlorentinDUBOIS merged commit d6a7d10 into main Sep 25, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the refactor/h2-router-cluster-view branch September 25, 2026 14:07
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