Repository navigation
refactor(mux): split Router::connect into a plan and an embedder-performed dial (#1340, Q6 first half) - #1519
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 25, 2026 09:34
FlorentinDUBOIS
force-pushed
the
refactor/h2-router-connect-plan
branch
from
September 25, 2026 10:05
817cc0f to
a1f4f83
Compare
FlorentinDUBOIS
changed the base branch from
refactor/h2-core-routing-backend-id
to
main
September 25, 2026 10:05
…ormed dial Answers the first half of Question 6 of #1340: the core decides and the embedder performs. `Router::connect` routed, gated, scanned the pool, dialled a backend, set `TCP_NODELAY`, built the `Connection`, inserted a slab session, registered an epoll interest and rolled all of that back on failure — 511 lines, 309 of them code, holding `Rc<RefCell<dyn ProxySession>>` and `Rc<RefCell<dyn L7Proxy>>` to do it. It is now `Router::plan_connect`, which decides and returns a `ConnectPlan`: `Attached` when it completed the attach from the pool, `Dial { cluster_id, h2, frontend_should_stick }` when it needs a backend opened. `Mux::dial_backend` performs the dial, the `setsockopt`, the `Connection` construction, `add_session`, `register_socket` and the gauge block — in the order `Router::connect` used, unchanged, so the CWE-400 deferral of every stateful side effect until after the constructor and `start_stream` both succeed is preserved — and hands the result to `Router::commit_dialed`. Same protocol the socket-boundary extraction used four times: the core answers a step, the caller performs the effect, the caller calls back with the answer. `Rc<RefCell<dyn ProxySession>>` code references in `mux/router.rs` go from 4 to 0; its single use was `add_session`, which is the embedder's. `Rc<RefCell<dyn L7Proxy>>` is unchanged at 5 production code references there — the three reads `plan_connect` still makes (`clusters`, `kind`, `sessions`) plus selection — and the borrowed view takes those next. `ConnectPlan::Attached` carries no token on purpose: the attach is complete, so no binding is in scope that a later edit could reuse to ask a question the variant has already answered. A wrong comment is fixed rather than moved. The `register_socket` rollback claimed dropping the connection released the `active_requests` charge "via the regular session drop path". `Connection` has no `impl Drop`, so the drop ran no bookkeeping; the claim was harmless only because the charge is guarded on `BackendStatus::Connected` and a freshly-dialled connection is `Connecting`. The rollback now calls `Connection::release_start_stream_charge` explicitly, under the same guard the charge uses. No behaviour change. `a_dial_plan_performs_no_effect_of_its_own` pins what the split is about: a `Dial` that had already dialled would still be a `Dial`, so it asserts on the state the router, the stream, the reverse index and the accounting ledger are left in. `cargo test -p sozu-lib` goes 1126 -> 1127. `Router::connect` is named in 48 places outside CHANGELOG.md; all 48 are repointed at `Router::plan_connect`, or at `Mux::dial_backend` where the prose meant the dial or its rollback. CHANGELOG entries are left as the historical record this repository keeps them as — it already names SimSocket and PlaceholderPeer, neither of which exists in the tree. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
refactor/h2-router-connect-plan
branch
from
September 25, 2026 11:28
a1f4f83 to
589dcb7
Compare
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 25, 2026
…uster, IP) slot `Router::plan_connect` claims a `(cluster, source-IP)` slot after the `cluster_ip_at_limit` gate and before backend selection, and none of the six fallible exits that follow the claim releases it. Since #1519 split the connect path those exits sit in two functions — the two pool-reuse refusals stay in `Router::plan_connect`, the four on the fresh-dial path moved to `Mux::dial_backend` — but the ordering is unchanged and `Mux::ready_inner` joins both halves into one `Result` with `and_then`, so they still share one error arm. The only release is `SessionManager::untrack_all_cluster_ip`, from session teardown. The unpaired claim reads like an oversight, so state that it is a decision and what the decision rests on. Measured on the error path rather than assumed. Every post-claim exit reaches the `BackendConnectionError` arm of the pending-link loop in `Mux::ready_inner`, which answers the stream from the template registry instead of retrying, and every built-in answer template carries `Connection: close`. That clears `HttpContext::keep_alive_frontend`, and that one bit is what ends the frontend connection: H1 closes after the answer flushes instead of taking the keep-alive reset, H2 sends a final GOAWAY when the failed stream was the only one and the advisory GOAWAY of a graceful drain otherwise, and a draining connection refuses new peer streams so the client cannot extend the window. Raw TCP never reaches an answer — any error out of `TcpSession::connect_to_backend` closes the session in the same event-loop pass. So the slot comes back with the connection, and the "a failed dial leaks a slot until an unrelated timeout" reading does not hold in the shipped configuration. Two branches are written down beside it. A backend that is registered and healthy-status but down does not fail on the dial at all, because `Backend::try_connect` is non-blocking: the refusal arrives later as a backend HUP and the stream retries, holding one slot — not one per attempt, the re-track is idempotent — for at most `CONN_RETRIES` attempts. And a custom answer template that omits `Connection: close` — the keep-alive opt-in the 429 template already documents — holds the slot for the connection's whole lifetime. No behaviour change: `lib/src/server.rs` gains only `///` lines. The citation re-anchor in `doc/lifetime_of_a_session.md` is that insertion shifting the file by 69 lines; each cited line was re-resolved by its text at the base revision and its enclosing `fn`. Two citations to the `accept_queue.backpressure` gauge become symbol citations because the shift made this changeset reuse line 594 for different code. Refs: #1521 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 25, 2026
…uster, IP) slot (#1528) `Router::plan_connect` claims a `(cluster, source-IP)` slot after the `cluster_ip_at_limit` gate and before backend selection, and none of the six fallible exits that follow the claim releases it. Since #1519 split the connect path those exits sit in two functions — the two pool-reuse refusals stay in `Router::plan_connect`, the four on the fresh-dial path moved to `Mux::dial_backend` — but the ordering is unchanged and `Mux::ready_inner` joins both halves into one `Result` with `and_then`, so they still share one error arm. The only release is `SessionManager::untrack_all_cluster_ip`, from session teardown. The unpaired claim reads like an oversight, so state that it is a decision and what the decision rests on. Measured on the error path rather than assumed. Every post-claim exit reaches the `BackendConnectionError` arm of the pending-link loop in `Mux::ready_inner`, which answers the stream from the template registry instead of retrying, and every built-in answer template carries `Connection: close`. That clears `HttpContext::keep_alive_frontend`, and that one bit is what ends the frontend connection: H1 closes after the answer flushes instead of taking the keep-alive reset, H2 sends a final GOAWAY when the failed stream was the only one and the advisory GOAWAY of a graceful drain otherwise, and a draining connection refuses new peer streams so the client cannot extend the window. Raw TCP never reaches an answer — any error out of `TcpSession::connect_to_backend` closes the session in the same event-loop pass. So the slot comes back with the connection, and the "a failed dial leaks a slot until an unrelated timeout" reading does not hold in the shipped configuration. Two branches are written down beside it. A backend that is registered and healthy-status but down does not fail on the dial at all, because `Backend::try_connect` is non-blocking: the refusal arrives later as a backend HUP and the stream retries, holding one slot — not one per attempt, the re-track is idempotent — for at most `CONN_RETRIES` attempts. And a custom answer template that omits `Connection: close` — the keep-alive opt-in the 429 template already documents — holds the slot for the connection's whole lifetime. No behaviour change: `lib/src/server.rs` gains only `///` lines. The citation re-anchor in `doc/lifetime_of_a_session.md` is that insertion shifting the file by 69 lines; each cited line was re-resolved by its text at the base revision and its enclosing `fn`. Two citations to the `accept_queue.backpressure` gauge become symbol citations because the shift made this changeset reuse line 594 for different code. Refs: #1521 Signed-off-by: Florentin Dubois <[email protected]>
This was referenced Sep 25, 2026
Closed
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 28, 2026
…ts (#1667) Two comments in lib/src/protocol/mux/h2.rs, added with the #1631 ServerSettings fix after the #1519 split, still named `Router::connect`, which that split renamed `Router::plan_connect`: the write-readiness arm of `ConnectionH2::dispatch_writable_state` and the rustdoc of `a_backend_stream_ended_during_the_handshake_keeps_the_connection`. Both now name `Router::plan_connect`'s pool scan, which is where the stream is linked: the scan (the shared `decide_after_gate` body, reached from `plan_connect` directly or through `plan_connect_resume` after the per-IP gate) selects a `BackendStatus::Connected` H2 connection without consulting its `H2State`, then calls `start_stream` and `link_stream`. Comment-only; each paragraph is reflowed within its original line count, so no citation or pinned block moves. 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.
Answers the first half of Question 6 of #1340 — routing inside the core, backend selection
expressed as a returned request — following the maintainer's correction comment that the later
decision stands.
Stacked on #1517 (Q12's opaque backend id and accounting deltas), which is still open, so this
targets that branch. It retargets to
mainwhen #1517 lands.The split
Router::connectrouted, gated, scanned the pool, dialled a backend, setTCP_NODELAY, built theConnection, inserted a slab session, registered an epoll interest and rolled all of that back onfailure — 511 lines, 309 of them code — holding
Rc<RefCell<dyn ProxySession>>andRc<RefCell<dyn L7Proxy>>to do it.It is now
Router::plan_connect, which decides and returns aConnectPlan:AttachedDial { cluster_id, h2, frontend_should_stick }Mux::dial_backendperforms the dial, thesetsockopt, theConnectionconstruction,L7Proxy::add_session,L7Proxy::register_socketand the gauge block — in the orderRouter::connectused, unchanged — then hands the result toRouter::commit_dialed.That is the protocol the socket-boundary extraction used four times (
finalize_write/H2FinalizeTarget,flush_pending_control_frames/H2ControlFlushTarget,dispatch_writable_state/H2WritableStateTarget, andforce_disconnect's inversion): the coreanswers a step, the caller performs the effect, the caller calls back with the answer. No fifth
protocol.
ConnectPlan::Attachedcarries no token on purpose — the attach is complete, so no binding is inscope that a later edit could reuse to ask a question the variant has already answered. That is
H2WritableStateTarget::Flush's discipline of carrying nobool.What dissolved, measured with comment lines filtered
mux/router.rsproductionmux/router.rstestsRc<RefCell<dyn ProxySession>>Rc<RefCell<dyn L7Proxy>>The session handle is gone from the router entirely, production and tests. Its single use was
L7Proxy::add_session, which is the embedder's.L7Proxyis deliberately unchanged: it remains for the three readsplan_connectstill makes(
clusters,kind,sessions) and for backend selection. Those are the second half of Q6 —the borrowed view — and are not in this PR.
mux/mod.rsgains one reference of each, which is theembedder absorbing what the core put down; do not read that as a regression.
CWE-400 ordering is preserved, and a wrong comment is fixed
Every stateful side effect (the three gauges, the slab session, the mio registration, the
router-map entry,
stream.metrics.backend_start) is still deferred until after both theConnectionconstructor andstart_streamhave succeeded, and the rollback still runs in the sameplace. Moving the block did not reorder it.
The
register_socketrollback claimed that dropping the connection released theactive_requestscharge "via the regular session drop path (
pre_close_client_bookkeeping)".Connectionhasno
impl Drop, so the drop ran no bookkeeping at all. It was harmless only because the charge isguarded on
BackendStatus::Connectedand a freshly-dialled connection isConnecting, so there wasnever anything to release. The rollback now calls
Connection::release_start_stream_chargeexplicitly, under the same guard the charge uses, so the pair holds however the status is reached
rather than by accident. Flagged in #1517's report as out of scope there and carried here, as asked.
Test
a_dial_plan_performs_no_effect_of_its_ownpins what the split is actually about. Asserting on thereturn value would not catch the erosion this invites — a
Dialthat had already dialled is stilla
Dial— so it asserts on the state left behind: the router's backend map, the stream's linkstate, the backend-stream reverse index, and the invariant-14 accounting ledger.
Seen red by performing one effect inside
plan_connect:cargo test -p sozu-libgoes 1126 → 1127 passed, this test and nothing else.What that test does NOT claim, stated because it would be easy to over-read
plan_connectis not yet pure. It still performs exactly one registry mutation:SessionManager::track_cluster_ip, throughproxy.borrow().sessions(), in theper-
(cluster, source-IP)limit gate. That is the first wrinkle recorded on #1340 — a mutationsitting between two in-core steps, cluster resolution and backend selection — and this PR does
not resolve it. It is unchanged, in place, and it is 2a-ii's to move, as either a second returned
step or part of the borrowed view.
The test is scoped accordingly: it builds its
Contextwithsession_address: None, which skipsthat gate, and it asserts on the router's backend map, the stream's link state, the backend-stream
reverse index and the accounting ledger — not on the session manager. Read the assertion list,
not the test name.
Backend::try_connectfuses the dial withinc_connections()— deliberately left fusedThe second wrinkle recorded on #1340: selection reads a view of backend load state, and the dial it
causes increments
active_connectionsinsideBackend::try_connect, so the view that made thedecision is stale by one the moment the decision is acted on.
The new shape leaves the fusion alone, and that is the right answer rather than a deferral.
Three reasons, in order:
in which the fd exists and the counter does not. Splitting them creates that window.
lib/src/tcp.rsdepends on it. It holdsbackend: Option<Rc<RefCell<Backend>>>and pairs itsown
dec_connections()againsttry_connect's increment. Moving the increment out wouldsilently unbalance the TCP proxy, which has none of the
BackendDeltamachinery refactor(mux): hold backends as an opaque id and return accounting deltas (#1340, Q12) #1517 added,and would make
active_connectionsa third architecture.try_connectincrementssynchronously, inside the same
pending_linksloop iteration as the decision that caused it.The next iteration takes its view fresh, so it sees the increment — the same drain-before-read
ordering refactor(mux): hold backends as an opaque id and return accounting deltas (#1340, Q12) #1517 established for
active_requests. The comment at the drain point inMux::ready_innernow says so.What remains for 2a-ii is only that the view be taken fresh at each selection point rather than
hoisted, which is Q12 part 2's wording already.
Reference sweep
Router::connectwas named in 48 places outsideCHANGELOG.md. All 48 are dispositioned:repointed at
Router::plan_connect, or atMux::dial_backendwhere the prose meant the dial or itsrollback (
socket.rs,connection.rs's FIX-18 hook note, and the six FIX-18 sites ine2e/src/tests/h2_security_session.rs).CHANGELOG entries are left alone —
unaffected, historical record. This repository keeps them thatway and already names
SimSocketandPlaceholderPeer, neither of which exists anywhere in thetree.
sim/is one line, and it is a comment insideSimListener::frontend_from_requestnaming therenamed symbol. No
sozu-simscenario, workload weight or assertion is touched.Two descriptions my change made wrong were repaired rather than renamed:
doc/benchmark.mdsaid theconnectsyscall is reached throughRouter::connectcallingbackend_from_request(it is nowMux::dial_backend), anddoc/architecture.mddescribedrouter.rsas "Backend dial / pool"orchestration (the dial left). Not fixed, pre-existing and out of scope: every line count in
that
doc/architecture.mdtable is stale —router.rsis listed at 678 lines and is 2192,stream.rsat 290 and is 1274,connection.rsat 578 and is 699,parser.rsat 2246 and is 2481.Verification
Feature set
--no-default-features --features crypto-ring,opentelemetry,splice,simdthroughout.Every exit code 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 f7f06f39fd56ff02947f436137f9353f5183eda6check_doc_citations.py --audit --root .RUSTDOCFLAGS="-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 opcodes from thestage-1 base, keyed on the full repo-relative path, binding a cited path to the citing document's
own directory first). The in-place remap was proved equivalent to resetting every guarded doc to
the merge base: the citation sequence of all of them was byte-identical to the base before remapping.
23 citations drifted and were remapped; all 23 exempt spans were audited on two keys —
byte-identical line text AND identically-named enclosing
fn— and all 23 hold.Next
2a-ii (H2, second half): the three
L7Proxyreads and backend selection become the borrowedview Q12 part 2 describes, taken fresh at each selection point. That is what drops
L7Proxyfromrouter.rsand what buys Q6's determinism argument, since selection is the part a simulator mustcontrol. The first wrinkle recorded on #1340 —
track_cluster_ipbeing a registry mutationbetween two in-core steps — lands there.
2b (UDP): brought to the same shape, under a bounded relaxation of the "every sim scenario
survives unchanged" rule — seed→interleaving identity for
udp_simulation.rsmay change, everyassertion must not. Tracked separately.
Note for #1341 Q5: the
configured_peercaching site MOVED in this PR#1341 Q5 (peer-address snapshotting) builds on the site that caches the backend's configured
address into
SessionTcpStream::configured_peerso a SOCKET line fired on ECONNREFUSED stillrenders
peer=<backend>—getpeername(2)returns ENOTCONN in that state, so a live lookupshows
peer=Noneexactly when the operator needs the backend id.That site is no longer in
router.rs. It moved with the rest of the dial:66205685)Router::connectMux::dial_backendlib/src/protocol/mux/router.rslib/src/protocol/mux/mod.rsThe two lines and their comment are carried verbatim; only the enclosing function and file changed.
The remaining
SessionTcpStream::newinrouter.rsis a test helper, not the production cachingsite. Nothing else about the caching changed — same value, same construction, same position
relative to the dial.
No collision otherwise: this PR's only edits to
lib/src/protocol/mux/h2.rsare two comment-onlysymbol renames, at hunks
@@ -1569 +1569 @@and@@ -15668 +15668 @@. It does not touch thelog_context!macro near the top of that file.Rebase
Rebased from
refactor/h2-core-routing-backend-idontomainafter #1517 was squash-merged.git rebase --onto 66205685 f7f06f39replayed exactly one commit — the squash's tree isbyte-identical to
f7f06f39's (git diff --statbetween them is empty), so no line moved and thecitation remap derived against
f7f06f39is the remap against66205685. Demonstrated ratherthan assumed: resetting
doc/testing.mdto the new base and re-deriving reproduces the branch filebyte-for-byte, and for
lib/src/protocol/mux/LIFECYCLE.md— which this PR also edits as prose —the re-derived citation sequence is identical to the branch's, so the file difference is purely
that prose.
All 18 exempt spans (23 endpoints) were 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 an enclosing-type fallback forspans that have none. All 18 hold; 0 spans lacked an enclosing fn.
mainhas since moved toa3a03b66(#1518, two ARC runner YAMLs). The file intersection betweenthat and this branch is empty, so the
--base 66205685gating above stays correct.e2e: the result quoted in the table is the uncontended run at
817cc0fe(1-minute loadavg2.79 before, 6.36 after, 447 passed, exit 0). The post-rebase tree is byte-identical to that commit,
so the run stands. A confirmation run after the rebase also passed 447/0, but it started at loadavg
15.60 and is therefore not quoted as a result.