Skip to content

refactor(mux): give Router::backends a total order, closing 8 determinism leaks - #1500

Merged
FlorentinDUBOIS merged 2 commits into
mainfrom
refactor/h2-ordered-backends
Sep 24, 2026
Merged

FlorentinDUBOIS merged 2 commits into
mainfrom
refactor/h2-ordered-backends

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Refs #1338. Closes 8 of the 15 hash-order determinism leaks with a three-line production change.

Router::backends: HashMap<Token, Connection<SessionTcpStream>> → BTreeMap. Token is Ord over a usize.

This is not a new design decision. main already made exactly this call twice, each with a written rationale: H2FlowControl::pending_window_updates, and H2StreamTable's three stream_* maps. Both modules argue BTreeMap over a seeded hasher for a small integer-keyed map — total order, no sort step, no seed to thread through construction. This follows them.

Production code is three lines: the field type, Router::new's initialiser, the std::collections import. mod.rs is untouched — every use there (&map, iter_mut, values_mut, get/get_mut, insert/remove, contains_key, len, {:#?}) is API-identical, so nothing spread.

What it closes: 8 sites, 10 decisions

Enumerated by reading every router.backends use, not by grepping for iterator methods.

Functional (5 sites, 7 decisions): Router::connect ×3 (below), Mux::reschedule's wheel-insertion order, Mux::ready's backends.iter_mut() whose break on CloseSession lets the first dead backend in map order decide the pass, Mux::ready's try_resume_reading sweep, and Mux::close's deregister_socket + shutdown(Write) + remove_session order.

Diagnostic (3): Mux::print_state's loop and two BACKENDS: {:#?} traces — HashMap's own Debug walks self.iter(), so a dump leaked the seed exactly as a for loop did.

Router::connect holds three decisions, and they disagree on direction

This is the part worth reading before writing any further test here:

arm shape picks
(true, Connected) strict < on best_h2_stream_count first at the minimum → lowest Token
(true, Connecting) reuse_token = Some(*token), no break, no guard last match → highest Token
(false, KeepAlive) assigns then breaks first match → lowest Token

BTreeMap makes all three deterministic. It does not make them agree — so the natural "asserts the lowest token" assertion is correct for two of the three and wrong for the middle one.

Two corrections to the leak table as previously published:

The Connecting fallback is last-wins, not first-wins. best_h2_stream_count stays usize::MAX for as long as no connected backend matches, so every Connecting match overwrites its predecessor. #1497's description said "picks the first one seen"; that has been corrected there.

The H1 KeepAlive arm appears in no enumeration at all — not the issue, not the 7-, 11- or 15-count. It is live: the (false, Connected) and (false, Connecting) arms are explicitly empty under the comment "can't bundle H1 streams together", so each H2 stream dials its own H1 socket, every socket parks KeepAlive for that cluster, and the next request picks among equivalents by map order.

How the red is genuine

A test that runs twice and compares can pass by luck on a HashMap. Measured rather than assumed: RandomState is seeded per instantiation, not per iteration — two walks of one live map always agree, but separately constructed maps in one thread do not, because RandomState::default() bumps a thread-local key each time.

So each round builds a fresh Router, stages four backends under deliberately unordered non-contiguous tokens [23, 7, 41, 13], and drives a real Router::connect through real routing — real HttpProxy, real frontend, real cluster with http2: Some(true) — asserting the specific token total order selects. 24 rounds × 4 backends: the pre-image survives with probability ~4^-24, about one run in 2.8e14. No separate processes needed.

Three guards, one per decision, including Token(41) for the last-wins fallback.

Red proof re-run on the final committed test code, since a clippy fix had restructured the fixture after the first proof — three production lines reverted by hand, guards untouched, three consecutive runs at 0 passed; 3 failed:

round 0: a stream-count tie must resolve to the lowest token
  left: Token(23)   right: Token(7)
round 1: the connecting-backend fallback assigns last-wins
  left: Token(7)    right: Token(41)

Restored → 3 passed; 0 failed.

Test-shaping: the production code diff carries zero numeric and zero string literals, so it cannot be shaped to the test.

O(log n), stated rather than waved past

n is the backend connections of one frontend session, not a worker- or cluster-wide count. H2→H2 is ~1 multiplex slot per cluster touched; H2→H1 cannot bundle, so it is bounded by the advertised max_concurrent_streams — 100 by default, clamped to 10 000.

Only the point lookups change class — get/get_mut/insert/remove/contains_key, amortized O(1) → O(log n) — and Mux::ready does one get_mut per backend event. Every iteration site already walks all n and keeps its O(n).

At n ≤ 100 that is ~7 usize comparisons against one SipHash-1-3 plus a bucket probe: not worth shipping quietly, and not worth blocking on. At a listener near 10 000 (~14 comparisons) it stops being self-evidently negligible. Unmeasured — no bombardier run was produced, and the module doc says so.

Left at the boundary

  • H2StreamTable::streams not converted — genuinely contested between a seeded hasher and BTreeMap, and the maintainer's call. The three functional leaks behind it stay open; none is behind router.backends.
  • The Connecting fallback's last-wins shape is pinned, not corrected. Preferring a different backend is a routing change, not a determinism one.
  • Context::backend_streams swept and clean — point access only. Mux::timeouts left a HashMap; its retain predicate is pure, so no observable order.

Verification

cargo +nightly fmt --all -- --check                     exit 0
cargo build  --locked --no-default-features --features crypto-ring,…   exit 0
cargo clippy --all-targets --locked … -- -D warnings    exit 0, 0 diagnostics
cargo test -p sozu-lib --locked …    ok. 1110 passed; 0 failed    (baseline measured at 1107, +3)
cargo test -p sozu     --locked …    ok. 113 passed; 0 failed
cargo test -p sozu-e2e --locked … -- --skip tests::fuzz_tests::   ok. 447 passed; 0 failed
RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked   10 / 6 / 6 / 6, 0 failed
RUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets -- -D warnings   exit 0
check_doc_citations.py --root .      208 citations, 551 test names, 16 pinned, rule 5 clean
check_doc_citations.py --base        319 compared unchanged; 4 exempt spans, all audited
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked   exit 0

The 4 exempt spans were audited, and the audit caught a real miss: a later correction commit shifted router.rs again and the three renumbered citations silently drifted a second time while --base still passed — because a re-anchored span is exempt from comparison. Re-fixed and re-audited; 4/4 byte-identical, 0 pointing at new code.

Two failures were fixed properly rather than silenced: clippy::type_complexity on the fixture's 3-tuple return became a RoutingFixture struct, and RUSTDOCFLAGS="-D warnings" rejected five intra-doc links to private items, which were demoted to plain code spans. No #[allow], no -A.

No test deleted or newly ignored, no assertion loosened, no production dependency added — BTreeMap is std.

`Router::backends` was a `HashMap<Token, _>`, so `RandomState`'s per-process
seed decided which backend served a request whenever two candidates tied.
`Token` is `Ord` over a `usize`; the map is now a `BTreeMap`. Three lines of
production code, no new dependency.

Three decisions inside `Router::connect`'s single scan read the iteration
order, and not the same way: the H2 least-loaded arm compares stream counts
with a strict `<` (first-at-minimum), the connecting-backend fallback assigns
with neither a `break` nor an "already chosen" guard (last-wins), and the H1
keep-alive arm assigns and breaks (first-seen). The total order resolves them
to the lowest, the highest and the lowest token. The fallback's last-wins
shape is pinned, not corrected: preferring a different backend is a routing
change, not a determinism one.

The same container closes `Mux::reschedule`'s wheel-insertion order,
`Mux::ready`'s backend sweep whose `break` on `CloseSession` lets the first
dead backend decide the pass, `Mux::ready`'s `try_resume_reading` order,
`Mux::close`'s deregister/shutdown/remove order, and three debug dumps —
`HashMap`'s own `Debug` walks `self.iter()`. `Mux::cancel_timeouts` and
`Mux::reschedule`'s `retain` were refuted by reading, not converted.

Each guard builds a fresh `Router` per round, because `RandomState` is seeded
per map and two walks of one live map agree: the pre-image survives 24 rounds
over four backends with probability 4^-24. `H2StreamTable::streams` is left a
`HashMap` deliberately.

Refs #1338

Signed-off-by: Florentin Dubois <[email protected]>
…rement

Three corrections to the prose of the preceding commit; no code changes.

`slab::Slab` does not hand out its lowest free index: `try_remove` pushes the
freed key onto the head of its vacant list (`self.next = key`) and `insert`
pops that head, so a dial reuses the most recently released index. The
conclusion the sentence supported — a `Token` carries no fairness meaning of
its own — is unchanged; the mechanism claimed for it was wrong.

The "minimum came first in 8, 5 and 7 of 24 rounds" figures came from a
scratch `HashMap<usize, ()>`, not from `Router::backends` on the reverted
tree, and are replaced by what the reverted tree actually reported: three
consecutive runs failing all three guards at round 0 or round 1, handing the
least-loaded guard `Token(23)` and `Token(13)` and the last-wins fallback
`Token(7)`.

The changelog counted "8 sites plus a ninth" in one paragraph and "eight named
sites, ten decisions" in another. One basis now: eight named sites, ten
order-dependent decisions, two corrections to the issue's leak table. The
`Context::backend_streams` sweep is recorded with the other refutations.

Three `router.rs:NNN` citations follow the doc's new line count.

Refs #1338

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the refactor/h2-ordered-backends branch from f6fff0e to 91fd08c Compare September 24, 2026 08:27
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 8248c78 into main Sep 24, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the refactor/h2-ordered-backends branch September 24, 2026 09:13
FlorentinDUBOIS added a commit that referenced this pull request Sep 25, 2026
…1520) (#1522)

doc/architecture.md's "Module layout" block is the only place under doc/
that says what each file in lib/src/protocol/mux/ is for. It listed 13 of
the directory's 26 modules and hardcoded a size beside each one.
Re-measured at 5355cec with `wc -l`, twelve of the thirteen were wrong:
h2.rs stated 7562 against 15360, router.rs 678 against 2192, stream.rs 290
against 1274, shared.rs 93 against 646. debug.rs at 80 was right only
because that file has not changed. The closing "18 666 lines of Rust across
13 modules" reads 43 092 across 26 — a total off by 24 426 lines.

Take the first of the issue's two options: keep the module list and the
descriptions, which a reader cannot cheaply re-derive, and delete every
parenthesised count and the total. The block already told the reader to run
`wc -l lib/src/protocol/mux/*.rs`; that sentence now is the whole answer
rather than a footnote to a snapshot of it.

Making the counts checkable was the alternative. The only gate that reads
these documents is .github/scripts/check_doc_citations.py, so a count check
is a new gate whose sole job is to guard an ornament; it would fire on
nearly every changeset that touches this directory, with the fix always
"re-run wc -l and paste"; and it would not have caught what actually went
wrong, which is thirteen modules with no row at all. A membership check
would catch that and would fire only on an add, a remove or a rename — it
is worth its own changeset, and is deliberately not bundled here because it
is a CI change and #1447 is open on that script. Until then the obligation
is written into the block: adding a module means adding its row, and no
gate enforces that either.

All 26 modules are now listed, in the order the file had, with the
extracted h2_* siblings and hpack_state.rs grouped under h2.rs. Every
description is read off the module it names. The two stale ones the issue
called out are corrected — mod.rs no longer claims Router and Stream, which
live in router.rs and stream.rs, and h2.rs no longer claims flood detection
or shutdown handling, which are h2_flood_detector.rs and
h2_close.rs/h2_drain.rs. Two more clauses in that same h2.rs row were stale
for the same reason and go with them: flow control is h2_flow_control.rs
and the RFC 9218 priorities are h2_scheduler.rs. Four further rows were
re-earned rather than re-typed: shared.rs held no state at all (it is four
helper functions and an enum shared by the two write paths), serializer.rs
also emits PING and WINDOW_UPDATE, connection.rs names the Connection enum
and the two Endpoint adaptors, and debug.rs is a bounded event ring that
compiles to a no-op without debug_assertions.

One further correction, found sweeping doc/ for the same defect and checked
against router.rs's own declaration: the Mux session diagram above the block
declared `backends: HashMap<Token, Connection<TcpStream>>`. The field is a
BTreeMap over SessionTcpStream. It became a BTreeMap in #1500 precisely so
that which backend serves a request stops depending on per-HashMap
RandomState seeding, so naming a HashMap there contradicted the guarantee
that change exists to provide.

Documentation only; no production code, test, dependency or Cargo.lock
change.

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