Skip to content

refactor(mux): hold backends as an opaque id and return accounting deltas (#1340, Q12) - #1517

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-core-routing-backend-id
Sep 25, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-core-routing-backend-id

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

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: Position is destructured at ~80 sites,
both Connection::new_h*_client constructors change, every datapath accounting site
moves, Router::connect is 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 arm
carries 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:

  • This PR — Q12's opaque id and accounting deltas. Self-contained, tree green.
  • Next — Q6 plus Q12's borrowed view. Sketched at the bottom.

What changed

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
actually reads (backend_id, 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 — Connection::close, Connection::end_stream,
Connection::start_stream, ConnectionH2::cancel_timed_out_streams,
ConnectionH2::handle_rst_stream_frame, ConnectionH2::handle_goaway_frame — records a
BackendChange on Context::backend_deltas. 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. They have to:
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 never balance. The health and latency writes (failures, retry_policy,
set_connection_time) are not part of invariant 14 and stay immediate, because the
load balancer reads retry_policy.

Ordering, which is the load-bearing part

Router::backend_from_request's load balancer is the only reader of the counters
involved. Application is FIFO, and the queue is drained immediately before each
Router::connect as well as on the way out of Mux::ready, timeout, close and
shutting_down — the same four wrappers that already owe the timer wheel a
reschedule. FIFO plus drain-before-read leaves the counters at every read point exactly
where mutating in place left them, saturation included. mem::take empties the queue
before 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 new
slot, so connections dialled before it keep charging the handle they were dialled
against — what holding the Rc inside Position::Client used to do. Keying on
(cluster, backend_id) would split a balanced start/end pair across two Backend
values: the superseded one keeps a charge forever, the fresh one saturates at zero.

One behaviour change, and it is a fix

Connection::start_stream records the charge after the inner start returns true
instead 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 out
of the pool is BackendStatus::KeepAlive until ConnectionH1::start_stream flips it. So
charging beforehand skipped the reuse entirely, while the matching
Connection::end_stream still released one (it runs before ConnectionH1::end_stream
flips the status back, so its own guard passes). Every keep-alive reuse cycle net -1d
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 that are already busy.

Assertions

The two before/after pair-assertions move to BackendRegistry::apply, where both
halves are observable and one copy covers every emitter. Only the refusal-path assertion
and the #[cfg(debug_assertions)] fn backend_active_requests helper it needed are
removed, 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:

Test Path
invariant_14_start_and_end_stream_balance nominal
invariant_14_a_refused_start_stream_charges_nothing refused start — asserts the ledger is EMPTY, since a +1/-1 pair also reconciles to zero
invariant_14_an_inbound_rst_stream_releases_its_charge RST_STREAM
invariant_14_an_inbound_goaway_releases_every_retired_charge GOAWAY
invariant_14_a_timed_out_stream_releases_its_charge idle reap
invariant_14_an_h1_keep_alive_reuse_is_charged H1 keep-alive reuse

Seen red, three of them, by reverting the production change and restoring it:

  • removing the GOAWAY arm's emit → left: (3, 0), right: (0, 0) on
    ..._an_inbound_goaway_releases_every_retired_charge
  • restoring the charge-then-undo shape →
    ..._a_refused_start_stream_charges_nothing prints the
    [StreamsStarted(1), StreamsEnded(1)] pair it refuses
  • the same revert → left: (0, 0), right: (1, 0) on
    ..._an_h1_keep_alive_reuse_is_charged

The production diff and the test block share no string literal, so the fix is not
test-shaped.

cargo test -p sozu-lib goes 1120 → 1126 passed, the six new tests and nothing else.
Every sozu-sim scenario and assertion is untouched — no file under sim/ is in this
diff.

Verification

Measured on this worktree; baseline measured separately at 5355cec0. Feature set is
--no-default-features --features crypto-ring,opentelemetry,splice,simd throughout
except where noted.

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 — 1126 passed (baseline 1120)
cargo test -p sozu --locked <flags> 0 — 113 passed
cargo test -p sozu-e2e --locked <flags> -- --skip tests::fuzz_tests:: 0 — 447 passed, loadavg 5.94 → 6.36
RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked 0 — 30 passed
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 5355cec0185c07c81e2334fca73ec290749d1dae 0
check_doc_citations.py --audit --root . 0 — 7 findings, all 7 present identically at 5355cec0
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 5355cec0, keyed on the full repo-relative path). All 66 spans the drift rule
exempts 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 this
changeset 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::connect splits into a pure decision and an embedder-performed effect, the same
shape as dispatch_writable_state → effect → dispatch_writable_state_after_flush:
the core answers Reuse { token } | Dial { cluster_id, backend, h2 } | Err, and Mux —
which holds proxy and session — performs the dial, add_session, register_socket
and the gauge block, then calls back. That is what dissolves
Rc<RefCell<dyn ProxySession>> and Rc<RefCell<dyn L7Proxy>> rather than threading
them. Two things found while doing this stage that stage 2 has to answer:

  • the per-(cluster, source-IP) gate (sessions_rc.borrow_mut().track_cluster_ip) is a
    registry 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_connect both dials and inc_connections(). The view-in/request-out
    split has to separate them, or the view is stale by one for the very selection that
    caused the dial.

A note on L7Proxy counts, so a non-drop is not read as failure: mux/mod.rs holds 6
grep 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 ProxySession
trait-impl signatures and Mux is the embedder the dial block lands in. The count that
reaches zero is router.rs's production one, 9 code lines today.

…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]>
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