Repository navigation
refactor(mux): read cluster configuration from a borrowed routing view (#1340, Q6) - #1525
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 25, 2026 10:30
FlorentinDUBOIS
force-pushed
the
refactor/h2-router-connect-plan
branch
from
September 25, 2026 11:28
a1f4f83 to
589dcb7
Compare
FlorentinDUBOIS
force-pushed
the
refactor/h2-router-cluster-view
branch
from
September 25, 2026 11:30
c1000da to
2e02720
Compare
`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
force-pushed
the
refactor/h2-router-cluster-view
branch
from
September 25, 2026 12:42
2e02720 to
b9f56c1
Compare
FlorentinDUBOIS
changed the base branch from
refactor/h2-router-connect-plan
to
main
September 25, 2026 12:42
This was referenced Sep 25, 2026
Closed
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]>
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.
Continues Question 6 of #1340. Stacked on #1519; retarget to
mainwhen that lands.What moved
Router::plan_connectmade three reads throughRc<RefCell<dyn L7Proxy>>. Two of them —L7Proxy::clustersandL7Proxy::kind— are pure, and now arrive asRoutingView, built onceper decision by
Mux::ready_innerfrom a singleproxy.borrow().Router::route_from_requestnolonger 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_connectcall sees the samecluster map. That is marginally stronger than what it replaces, and deliberately so: the two
sites used to take separate
proxy.borrow()s — one inplan_connect, one inroute_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 frompending_linksinside the very
ready()pass that queued it), so this closes a window that was never openrather than changing a behaviour that was.
Counts — and a prediction of mine that was wrong
I told the reviewer this PR would leave
L7Proxyflat at 5 becauseproxystays in the signaturefor the limit gate. That was wrong, and in the useful direction:
route_from_request'sproxyparameter disappears outright, so the count drops.
Comment lines filtered, production and test split:
lib/src/protocol/mux/router.rsproxy.borrow()reads insideRouter::plan_connectRc<RefCell<dyn L7Proxy>>production code referencesThe four that remain are the import, the
plan_connectparameter (for the gate), andRouter::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.rsfrom 5 to 0. It will not. Removing the gate takes theplan_connectparameter, leaving 3: the import and the two selection helpers, which
Mux::dial_backendcallsand which still reach
L7Proxy::backends. Getting those to zero means giving selection aborrowed 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 callscluster_ip_at_limitandtrack_cluster_ip, which mutatesSessionManager::connections_per_cluster_ip— worker-globalstate keyed on
(cluster, ip)across every session, read again bylib/src/tcp.rs's own gate forthe 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 doccomment:
plan_connectis not pure yet, and that test'sContextusessession_address: None,which skips the gate.
Test
the_routing_decision_reads_cluster_config_from_the_viewhands the decision a view thatdisagrees with the proxy about
cluster.http2— the fixture registersH2_CLUSTERwithhttp2: Some(true), the view saysSome(false)— and asserts the plan follows the view. Apremise 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 production diff and the test share no string literal, so the fix is not test-shaped.
cargo test -p sozu-libgoes 1127 → 1128 passed, this test and nothing else.Verification
Feature set
--no-default-features --features crypto-ring,opentelemetry,splice,simd. Every exitcode read directly, never through a pipe.
cargo build --locked <flags>cargo +nightly fmt --all -- --checkcargo clippy --all-targets --locked <flags> -- -D warningscargo test -p sozu-lib --locked <flags>cargo test -p sozu --locked <flags>cargo test -p sozu-e2e --locked <flags> -- --skip tests::fuzz_tests::RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --lockedRUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets --locked -- -D warningscheck_doc_citations.py --root .check_doc_citations.py --base <2a-i head>check_doc_citations.py --audit --root .RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --lockedcargo bench -p sozu-lib --bench h2_stream_table -- --testCitations 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
fnmatched by name with anenclosing-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 -lrecorded before andafter.
No
sozu-simscenario, workload weight or assertion is touched; this PR does not modify any fileunder
sim/.