Repository navigation
refactor(mux): give Router::backends a total order, closing 8 determinism leaks - #1500
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 24, 2026 07:24
`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
force-pushed
the
refactor/h2-ordered-backends
branch
from
September 24, 2026 08:27
f6fff0e to
91fd08c
Compare
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]>
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.
Refs #1338. Closes 8 of the 15 hash-order determinism leaks with a three-line production change.
Router::backends: HashMap<Token, Connection<SessionTcpStream>>→BTreeMap.TokenisOrdover ausize.This is not a new design decision.
mainalready made exactly this call twice, each with a written rationale:H2FlowControl::pending_window_updates, andH2StreamTable's threestream_*maps. Both modules argueBTreeMapover 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, thestd::collectionsimport.mod.rsis 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.backendsuse, not by grepping for iterator methods.Functional (5 sites, 7 decisions):
Router::connect×3 (below),Mux::reschedule's wheel-insertion order,Mux::ready'sbackends.iter_mut()whosebreakonCloseSessionlets the first dead backend in map order decide the pass,Mux::ready'stry_resume_readingsweep, andMux::close'sderegister_socket+shutdown(Write)+remove_sessionorder.Diagnostic (3):
Mux::print_state's loop and twoBACKENDS: {:#?}traces —HashMap's ownDebugwalksself.iter(), so a dump leaked the seed exactly as aforloop did.Router::connectholds three decisions, and they disagree on directionThis is the part worth reading before writing any further test here:
(true, Connected)<onbest_h2_stream_countToken(true, Connecting)reuse_token = Some(*token), nobreak, no guardToken(false, KeepAlive)breaksTokenBTreeMapmakes 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
Connectingfallback is last-wins, not first-wins.best_h2_stream_countstaysusize::MAXfor as long as no connected backend matches, so everyConnectingmatch overwrites its predecessor. #1497's description said "picks the first one seen"; that has been corrected there.The H1
KeepAlivearm 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 parksKeepAlivefor 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:RandomStateis seeded per instantiation, not per iteration — two walks of one live map always agree, but separately constructed maps in one thread do not, becauseRandomState::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 realRouter::connectthrough real routing — realHttpProxy, real frontend, real cluster withhttp2: 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: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
nis 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 advertisedmax_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) — andMux::readydoes oneget_mutper backend event. Every iteration site already walks allnand keeps its O(n).At
n ≤ 100that is ~7usizecomparisons 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::streamsnot converted — genuinely contested between a seeded hasher andBTreeMap, and the maintainer's call. The three functional leaks behind it stay open; none is behindrouter.backends.Connectingfallback's last-wins shape is pinned, not corrected. Preferring a different backend is a routing change, not a determinism one.Context::backend_streamsswept and clean — point access only.Mux::timeoutsleft aHashMap; itsretainpredicate is pure, so no observable order.Verification
The 4 exempt spans were audited, and the audit caught a real miss: a later correction commit shifted
router.rsagain and the three renumbered citations silently drifted a second time while--basestill 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_complexityon the fixture's 3-tuple return became aRoutingFixturestruct, andRUSTDOCFLAGS="-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 —
BTreeMapis std.