Skip to content

refactor(mux): split Router::connect into a plan and an embedder-performed dial (#1340, Q6 first half) - #1519

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

FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-router-connect-plan

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

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 main when #1517 lands.

The split

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:

Variant Meaning
Attached The attach completed from the pool. Nothing left to perform.
Dial { cluster_id, h2, frontend_should_stick } A backend must be opened.

Mux::dial_backend performs the dial, the setsockopt, the Connection construction,
L7Proxy::add_session, L7Proxy::register_socket and the gauge block — in the order
Router::connect used, unchanged
— then hands the result to Router::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, and force_disconnect's inversion): the core
answers a step, the caller performs the effect, the caller calls back with the answer. No fifth
protocol.

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. That is
H2WritableStateTarget::Flush's discipline of carrying no bool.

What dissolved, measured with comment lines filtered

Symbol mux/router.rs production mux/router.rs tests
Rc<RefCell<dyn ProxySession>> 2 → 0 2 → 0
Rc<RefCell<dyn L7Proxy>> 5 → 5 4 → 4

The session handle is gone from the router entirely, production and tests. Its single use was
L7Proxy::add_session, which is the embedder's.

L7Proxy is deliberately unchanged: it remains for the three reads plan_connect still 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.rs gains one reference of each, which is the
embedder 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 the
Connection constructor and start_stream have succeeded, and the rollback still runs in the same
place. Moving the block did not reorder it.

The register_socket rollback claimed that dropping the connection released the active_requests
charge "via the regular session drop path (pre_close_client_bookkeeping)". Connection has
no impl Drop
, so the drop ran no bookkeeping at all. It was harmless only because the charge is
guarded on BackendStatus::Connected and a freshly-dialled connection is Connecting, so there was
never anything to release. The rollback now calls Connection::release_start_stream_charge
explicitly, 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_own pins what the split is actually about. Asserting on the
return value would not catch the erosion this invites — a Dial that had already dialled is still
a Dial
— so it asserts on the state left behind: the router's backend map, the stream's link
state, the backend-stream reverse index, and the invariant-14 accounting ledger.

Seen red by performing one effect inside plan_connect:

assertion `left == right` failed: a plan must not have linked the stream — the embedder has not dialled yet
  left: Linked(Token(4242))
 right: Link

cargo test -p sozu-lib goes 1126 → 1127 passed, this test and nothing else.

What that test does NOT claim, stated because it would be easy to over-read

plan_connect is not yet pure. It still performs exactly one registry mutation:
SessionManager::track_cluster_ip, through proxy.borrow().sessions(), in the
per-(cluster, source-IP) limit gate. That is the first wrinkle recorded on #1340 — a mutation
sitting 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 Context with session_address: None, which skips
that 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_connect fuses the dial with inc_connections() — deliberately left fused

The second wrinkle recorded on #1340: selection reads a view of backend load state, and the dial it
causes increments active_connections inside Backend::try_connect, so the view that made the
decision 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:

  1. The fusion is correct. A connection opened is a connection counted, atomically, with no window
    in which the fd exists and the counter does not. Splitting them creates that window.
  2. lib/src/tcp.rs depends on it. It holds backend: Option<Rc<RefCell<Backend>>> and pairs its
    own dec_connections() against try_connect's increment. Moving the increment out would
    silently unbalance the TCP proxy, which has none of the BackendDelta machinery refactor(mux): hold backends as an opaque id and return accounting deltas (#1340, Q12) #1517 added,
    and would make active_connections a third architecture.
  3. The staleness is a view question, not a restructuring one. try_connect increments
    synchronously, inside the same pending_links loop 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 in
    Mux::ready_inner now 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::connect was named in 48 places outside CHANGELOG.md. All 48 are dispositioned:
repointed at Router::plan_connect, or at Mux::dial_backend where the prose meant the dial or its
rollback (socket.rs, connection.rs's FIX-18 hook note, and the six FIX-18 sites in
e2e/src/tests/h2_security_session.rs).

CHANGELOG entries are left alone — unaffected, historical record. This repository keeps them that
way and already names SimSocket and PlaceholderPeer, neither of which exists anywhere in the
tree.

sim/ is one line, and it is a comment inside SimListener::frontend_from_request naming the
renamed symbol. No sozu-sim scenario, workload weight or assertion is touched.

Two descriptions my change made wrong were repaired rather than renamed: doc/benchmark.md said the
connect syscall is reached through Router::connect calling backend_from_request (it is now
Mux::dial_backend), and doc/architecture.md described router.rs as "Backend dial / pool"
orchestration (the dial left). Not fixed, pre-existing and out of scope: every line count in
that doc/architecture.md table is stale — router.rs is listed at 678 lines and is 2192,
stream.rs at 290 and is 1274, connection.rs at 578 and is 699, parser.rs at 2246 and is 2481.

Verification

Feature set --no-default-features --features crypto-ring,opentelemetry,splice,simd throughout.
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 — 1127 passed
cargo test -p sozu --locked <flags> 0
cargo test -p sozu-e2e --locked <flags> -- --skip tests::fuzz_tests:: 0 — 447 passed, loadavg 2.79 → 6.63
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 f7f06f39fd56ff02947f436137f9353f5183eda6 0
check_doc_citations.py --audit --root . 0 — 7 findings, all 7 identical at the base
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked 0
cargo bench -p sozu-lib --bench h2_stream_table -- --test 0

Citations were remapped by content (SequenceMatcher(autojunk=False) equal opcodes from the
stage-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 L7Proxy reads and backend selection become the borrowed
view Q12 part 2 describes, taken fresh at each selection point. That is what drops L7Proxy from
router.rs and what buys Q6's determinism argument, since selection is the part a simulator must
control. The first wrinkle recorded on #1340 — track_cluster_ip being a registry mutation
between 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.rs may change, every
assertion must not. Tracked separately.

Note for #1341 Q5: the configured_peer caching site MOVED in this PR

#1341 Q5 (peer-address snapshotting) builds on the site that caches the backend's configured
address into SessionTcpStream::configured_peer so a SOCKET line fired on ECONNREFUSED still
renders peer=<backend> — getpeername(2) returns ENOTCONN in that state, so a live lookup
shows peer=None exactly when the operator needs the backend id.

That site is no longer in router.rs. It moved with the rest of the dial:

before (merge base 66205685) after (this PR)
enclosing fn Router::connect Mux::dial_backend
file lib/src/protocol/mux/router.rs lib/src/protocol/mux/mod.rs

The two lines and their comment are carried verbatim; only the enclosing function and file changed.
The remaining SessionTcpStream::new in router.rs is a test helper, not the production caching
site. 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.rs are two comment-only
symbol renames, at hunks @@ -1569 +1569 @@ and @@ -15668 +15668 @@. It does not touch the
log_context! macro near the top of that file.

Rebase

Rebased from refactor/h2-core-routing-backend-id onto main after #1517 was squash-merged.
git rebase --onto 66205685 f7f06f39 replayed exactly one commit — the squash's tree is
byte-identical to f7f06f39's (git diff --stat between them is empty), so no line moved and the
citation remap derived against f7f06f39 is the remap against 66205685. Demonstrated rather
than assumed: resetting doc/testing.md to the new base and re-deriving reproduces the branch file
byte-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 fn matched by name with an enclosing-type fallback for
spans that have none. All 18 hold; 0 spans lacked an enclosing fn.

main has since moved to a3a03b66 (#1518, two ARC runner YAMLs). The file intersection between
that and this branch is empty, so the --base 66205685 gating above stays correct.

e2e: the result quoted in the table is the uncontended run at 817cc0fe (1-minute loadavg
2.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.

…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
FlorentinDUBOIS force-pushed the refactor/h2-router-connect-plan branch from a1f4f83 to 589dcb7 Compare September 25, 2026 11:28
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 339f794 into main Sep 25, 2026
28 checks passed
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
FlorentinDUBOIS deleted the refactor/h2-router-connect-plan branch September 25, 2026 13:03
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]>
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]>
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