Repository navigation
refactor(mux): hold backends as an opaque id and return accounting deltas (#1340, Q12) - #1517
Merged
Merged
Conversation
…ltas Answers Question 12 of #1340: `Position::Client` carried an `Rc<RefCell<Backend>>` so six datapath sites could reach the worker's backend registry and mutate its load counters in place. It now carries a `BackendId` — an opaque session-scoped slot plus the two identity fields the datapath reads, `backend_id` and `address`, both immutable for the life of a registry entry. No `Rc<RefCell<Backend>>` is reachable from `Position`, `Connection`, `ConnectionH1`, `ConnectionH2` or `Context`. Each of the six sites records a `BackendChange` on `Context::backend_deltas`, and `Mux::apply_backend_deltas` is the single writer that performs them against `Mux::backend_registry`. The three embedder-side accounting sites in `Mux` emit onto the same list: a fresh dial's first streams are charged at the `Connecting` -> `Connected` transition, not by `Connection::start_stream`, whose `Connected` guard skips them, so a core-only ledger could not balance. The health and latency writes stay immediate — they are not invariant 14, and the load balancer reads `retry_policy`. `Router::backend_from_request`'s load balancer is the only reader of the counters involved; application is FIFO and the queue drains immediately before each `Router::connect` and on the way out of `Mux::ready`, `timeout`, `close` and `shutting_down`, so every read point sees what mutating in place left there, saturation included. A slot rather than the backend's name keeps a reload that replaces a registry entry mid-session charging the handle each connection was dialled against. `Connection::start_stream` no longer charges a stream it has not started: the charge is recorded only after the inner start returns true, so the rollback that used to follow a refusal has no path left. That reordering is the one behaviour change here, and it fixes a standing violation of invariant 14 on the H1 keep-alive path. The charge is guarded on `BackendStatus::Connected`, and a connection coming back out of the pool is `BackendStatus::KeepAlive` until `ConnectionH1::start_stream` flips it, so charging beforehand skipped the reuse while the matching `Connection::end_stream` still released one. Every keep-alive reuse cycle net -1'd the backend, `saturating_sub` floored it at zero, and a reused H1 connection reported no in-flight request while it served one, biasing least-loaded and PeakEWMA balancing toward backends already busy. The two before/after pair-assertions move to `BackendRegistry::apply`, where both halves are observable; the refusal-path assertion and the `backend_active_requests` helper it needed are removed with the path they guarded. LIFECYCLE §9 invariant 14 is now a property of one observable list. Six tests reconcile it across the nominal, refused-start, RST_STREAM, GOAWAY, idle-reap and H1 keep-alive paths, then apply the ledger and assert the counter returns to zero. `cargo test -p sozu-lib` goes 1120 -> 1126. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 25, 2026 08:52
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.
Answers Question 12 of #1340, and the first of two stages for that issue's decision.
Branched from
5355cec0.Staging, and why
Q6 (routing inside the core,
Router::connect's two trait objects dissolved) and Q12(opaque backend id, borrowed view in, accounting deltas out) were scoped together, and
together they are not one reviewable changeset:
Positionis destructured at ~80 sites,both
Connection::new_h*_clientconstructors change, every datapath accounting sitemoves,
Router::connectis a ~300-line function that dials, registers an epoll socket,adds a slab session and inserts into its own map, and
Mux::ready_inner's connect armcarries a 100-line error map behind it.
The split falls on a real seam rather than an arbitrary line count. Q12 has three parts:
an opaque backend id, a borrowed view in, and accounting deltas out. The first
and third are independent of where routing lives. The second only means anything once
selection happens inside the core, which is Q6. So:
What changed
Position::Clientcarried anRc<RefCell<Backend>>so six datapath sites could reachthe worker's backend registry and mutate its load counters in place. It now carries a
BackendId: an opaque session-scoped slot, plus the two identity fields the datapathactually reads (
backend_id,address), both immutable for the life of a registryentry. No
Rc<RefCell<Backend>>is reachable fromPosition,Connection,ConnectionH1,ConnectionH2orContext.Each of the six sites —
Connection::close,Connection::end_stream,Connection::start_stream,ConnectionH2::cancel_timed_out_streams,ConnectionH2::handle_rst_stream_frame,ConnectionH2::handle_goaway_frame— records aBackendChangeonContext::backend_deltas.Mux::apply_backend_deltasis the singlewriter that performs them against
Mux::backend_registry.The three embedder-side accounting sites in
Muxemit onto the same list. They have to:a fresh dial's first streams are charged at the
Connecting→Connectedtransition,not by
Connection::start_stream, whoseConnectedguard skips them, so a core-onlyledger could never balance. The health and latency writes (
failures,retry_policy,set_connection_time) are not part of invariant 14 and stay immediate, because theload balancer reads
retry_policy.Ordering, which is the load-bearing part
Router::backend_from_request's load balancer is the only reader of the countersinvolved. Application is FIFO, and the queue is drained immediately before each
Router::connectas well as on the way out ofMux::ready,timeout,closeandshutting_down— the same four wrappers that already owe the timer wheel areschedule. FIFO plus drain-before-read leaves the counters at every read point exactlywhere mutating in place left them, saturation included.
mem::takeempties the queuebefore the first change is performed, so a second drain is idempotent (not type-level
unrepresentable — the S7 claim was stronger and this one should not borrow it).
Why a slot and not the backend's name
A reload that replaces a registry entry mid-session builds a new
Rc, which takes a newslot, so connections dialled before it keep charging the handle they were dialled
against — what holding the
RcinsidePosition::Clientused to do. Keying on(cluster, backend_id)would split a balanced start/end pair across twoBackendvalues: the superseded one keeps a charge forever, the fresh one saturates at zero.
One behaviour change, and it is a fix
Connection::start_streamrecords the charge after the inner start returns trueinstead of before with a rollback behind it. S5's discipline: the refusal path has no
charge to undo rather than undoing one correctly, and no binding is in scope a later edit
could reuse for the wrong question.
That reordering fixes a standing violation of invariant 14 on the H1 keep-alive path.
The charge is guarded on
BackendStatus::Connected, and an H1 connection taken back outof the pool is
BackendStatus::KeepAliveuntilConnectionH1::start_streamflips it. Socharging beforehand skipped the reuse entirely, while the matching
Connection::end_streamstill released one (it runs beforeConnectionH1::end_streamflips the status back, so its own guard passes). Every keep-alive reuse cycle net
-1dthe backend,
saturating_subfloored it at zero, and a reused H1 connection reported noin-flight request while it served one — biasing least-loaded and PeakEWMA balancing
toward backends that are already busy.
Assertions
The two before/after pair-assertions move to
BackendRegistry::apply, where bothhalves are observable and one copy covers every emitter. Only the refusal-path assertion
and the
#[cfg(debug_assertions)] fn backend_active_requestshelper it needed areremoved, because the rollback path they guarded no longer exists.
Tests
Invariant 14 is a balance, and it is now a property of one observable list rather than of
six scattered mutations. Six tests reconcile that list and then apply it and assert the
counter returns to zero:
invariant_14_start_and_end_stream_balanceinvariant_14_a_refused_start_stream_charges_nothing+1/-1pair also reconciles to zeroinvariant_14_an_inbound_rst_stream_releases_its_chargeRST_STREAMinvariant_14_an_inbound_goaway_releases_every_retired_chargeGOAWAYinvariant_14_a_timed_out_stream_releases_its_chargeinvariant_14_an_h1_keep_alive_reuse_is_chargedSeen red, three of them, by reverting the production change and restoring it:
GOAWAYarm's emit →left: (3, 0), right: (0, 0)on..._an_inbound_goaway_releases_every_retired_charge..._a_refused_start_stream_charges_nothingprints the[StreamsStarted(1), StreamsEnded(1)]pair it refusesleft: (0, 0), right: (1, 0)on..._an_h1_keep_alive_reuse_is_chargedThe production diff and the test block share no string literal, so the fix is not
test-shaped.
cargo test -p sozu-libgoes1120 → 1126 passed, the six new tests and nothing else.Every
sozu-simscenario and assertion is untouched — no file undersim/is in thisdiff.
Verification
Measured on this worktree; baseline measured separately at
5355cec0. Feature set is--no-default-features --features crypto-ring,opentelemetry,splice,simdthroughoutexcept where noted.
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 5355cec0185c07c81e2334fca73ec290749d1daecheck_doc_citations.py --audit --root .5355cec0RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --lockedcargo bench -p sozu-lib --bench h2_stream_table -- --testCitations were remapped by content (
SequenceMatcher(autojunk=False)equal opcodesfrom
5355cec0, keyed on the full repo-relative path). All 66 spans the drift ruleexempts as re-anchored were audited on two keys — byte-identical line text and
identically-named enclosing
fn— and all 66 hold. Three citations whose numbers thischangeset reused for different code were converted to symbol citations instead of
renumbered, which is the class #1447 named.
Next stage — Q6 plus Q12's borrowed view
Router::connectsplits into a pure decision and an embedder-performed effect, the sameshape as
dispatch_writable_state→ effect →dispatch_writable_state_after_flush:the core answers
Reuse { token } | Dial { cluster_id, backend, h2 } | Err, andMux—which holds
proxyandsession— performs the dial,add_session,register_socketand the gauge block, then calls back. That is what dissolves
Rc<RefCell<dyn ProxySession>>andRc<RefCell<dyn L7Proxy>>rather than threadingthem. Two things found while doing this stage that stage 2 has to answer:
(cluster, source-IP)gate (sessions_rc.borrow_mut().track_cluster_ip) is aregistry mutation sitting between two in-core steps — cluster resolution and backend
selection. It becomes either a second returned step or part of the view;
Backend::try_connectboth dials andinc_connections(). The view-in/request-outsplit has to separate them, or the view is stale by one for the very selection that
caused the dial.
A note on
L7Proxycounts, so a non-drop is not read as failure:mux/mod.rsholds 6grep lines today — 1 import, 3 code, 2 comment — and this PR leaves that at 6. After
stage 2 it does not go to zero and may go up, because those are
ProxySessiontrait-impl signatures and
Muxis the embedder the dial block lands in. The count thatreaches zero is
router.rs's production one, 9 code lines today.