Repository navigation
refactor(mux-h2): make the H2 wire stream map a BTreeMap - #1506
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 24, 2026 13:34
`H2StreamTable::streams` was the last of the five maps in the H2 core still walked in `RandomState` order, and the last open question in #1338. The module doc argued it was not a determinism leak by enumerating every iteration site and showing each loop BODY to be order-independent. The per-element claim is true; the conclusion does not follow, because per-element commutativity does not cover early termination. `update_initial_window_size` — the very site the old text singled out as safe — carries the `None => return true` arm RFC 9113 §6.9.2 requires on `checked_add` and returns from INSIDE the loop, without rolling back the writes it already made, so which prefix of the streams was mutated before the abort is exactly the iteration order. Two further sites turn that order into observable behaviour: `handle_goaway_frame` pushes onto `context.pending_links` in map order, so relink and therefore reconnect order was hash order; and `ConnectionH2::close` notifies teardown through `endpoint.end_stream` in map order. Measured before deciding, because `streams` is the only one of the five on the per-frame path: at the sizes this map actually reaches, BTreeMap is 1.7-2.3x faster at n=8 and equal-or-faster at n=100, losing only past a crossover between 100 and 1000. See `lib/benches/h2_stream_table.rs`, which keeps all three containers so that can be re-measured rather than re-argued. `HashMap::with_capacity(8)` is dropped rather than translated — BTreeMap has no equivalent, and `H2StreamTable::new`'s doc now says so, so the 8 is not re-added as a comment claiming a reservation that never happens. Every signature carrying the container type moves with it: `any_stream_has_pending_back`, `any_stream_id_matches`, `Prioriser::push_priority_guarded` and its `is_acceptable`, and `H2Scheduler::push_priority_guarded`. The regression test pins the keys, the values and the pairs of the map to ascending wire `StreamId` — the three iterator shapes those sites read between them. It was seen red on the pre-conversion tree, failing on its first assertion in four runs out of four with four different permutations; no permutation is quoted as a fact anywhere, because `RandomState` is seeded per process and the value is unreproducible. `doc/architecture.md`, `doc/h2_mux_internals.md` and LIFECYCLE.md §1.2 (prose and diagram), §4.1 and checklist invariant 1 move in the same changeset. The two `h2_stream_table.rs:125` citations there are replaced by the symbol the prose already names rather than renumbered: the field did not move, because the module-doc rewrite is line-count neutral, and a symbol cannot drift — which is what `check_doc_citations.py` itself recommends over a number. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
refactor/h2-stream-table-btreemap
branch
from
September 24, 2026 15:21
d4fc8d1 to
3907708
Compare
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.
What
H2StreamTable::streams— the wireStreamId -> GlobalStreamIdmap every inbound H2 frame islooked up in — becomes a
BTreeMap. It was the last of the five maps in the H2 core still walkedin
RandomStateorder, and the last open question in #1338.Why the old module doc was wrong
h2_stream_table.rs's Determinism section stated thatstreams"stays aHashMap— it is NOT adeterminism leak", and justified it by enumerating every iteration site and showing each loop
body to be order-independent. The per-element claim is true. The conclusion does not follow,
because per-element commutativity does not cover early termination.
update_initial_window_sizeis the counter-example, and it is the site the old text singled out assafe ("applies an additive delta to each stream's own
windowfield independently and OR-combinesa
bool— both order-independent"):The
Nonearm returns from inside the loop, and the writes already made tocontext.streams[..].windoware not rolled back. So on aSETTINGS_INITIAL_WINDOW_SIZEthatoverflows one stream, which prefix of the other streams was already mutated is exactly the
iteration order.
handle_settings_frameturns thetrueintoGOAWAY, and the half-updatedwindow set stays in
context.streamsforclose's teardown walk and any pass still to run.Two further sites order observable work rather than arithmetic, which the old text acknowledged and
then dismissed as "scheduling only":
handle_goaway_framewalksstreams()intoretry_streamsand pushes each retryable streamonto
context.pending_links— so relink, and therefore reconnect/dial order, was hash order.ConnectionH2::closenotifies each linked stream throughendpoint.end_stream— so teardownnotification order was hash order.
Neither reorders the bytes of a fixed frame set. Both are restart-to-restart irreproducibility of
exactly the kind #1338 is about.
Why this is free (measured, not argued)
streamsis the only one of the five on the per-frame path, solib/benches/h2_stream_table.rs(#1502) was written before the decision.
btree / fixed-seedratios, below 1.00 =BTreeMapfaster:
The realistic range is n = 8 (the occupancy
H2StreamTable::newused to declare) to n = 100(
DEFAULT_MAX_CONCURRENT_STREAMS):BTreeMapis 1.7–2.3x faster at 8 and equal-or-faster at 100,because SipHash-1-3 over a
u32costs ~9 ns whatevernis while a tree of eleven keys or fewer isone cache line. It loses past a crossover between 100 and 1000, reaching ~+50 ns/frame at n = 10000,
an operator-raised cap. A fixed-seed hasher measured below the noise floor against
RandomStateinall twenty cells, so it had no performance case either way and is not adopted. The bench keeps all
three containers so the crossover can be re-measured rather than re-argued.
Changes
H2StreamTable::streams: BTreeMap<StreamId, GlobalStreamId>;streams()returns&BTreeMap<…>.HashMap::with_capacity(8)is dropped, not translated.BTreeMaphas nowith_capacity— itallocates a node at a time, not one contiguous bucket array.
H2StreamTable::new's doc now saysso explicitly, so the 8 is not re-added as a comment claiming a reservation that never happens;
the number itself survives as the bench's smallest
n.any_stream_has_pending_back,any_stream_id_matches(h2.rs),Prioriser::push_priority_guardedand itsis_acceptable, andH2Scheduler::push_priority_guarded(h2_scheduler.rs).h2_stream_table.rsmodule-doc Determinism section is rewritten around the reasoning above.doc/architecture.md,doc/h2_mux_internals.mdand the bench's prose are updated in the samechangeset.
Regression test, seen red
streams_iterates_in_ascending_stream_id_order_whatever_the_insertion_orderregisters ninescrambled ids and pins the keys, the values and the pairs — the three iterator shapes
the three sites above read between them — to ascending wire
StreamId.Red, on the unmodified pre-conversion tree (
42ed6bac,streams: HashMap, guard test injected andnothing else):
Green, on this branch:
The failing value is deliberately not quoted as a fact anywhere:
RandomStateis seeded perprocess, so it is unreproducible by construction. Four consecutive runs of the red state produced
four different permutations and four failures — the invariant is what reproduces, not the number.
One sample:
left: [501, 901, 1, 17, 45, 3, 19, 5, 777].Docs, and the citation gate
Updated in this changeset:
doc/architecture.md,doc/h2_mux_internals.md(theH2StreamTablefield diagram and the
push_priority_guardedsignature row),lib/benches/h2_stream_table.rs'sprose, and
lib/src/protocol/mux/LIFECYCLE.md— §1.2 prose, the §1.2 ASCII diagram (which spellsstreams: HashMaptwice, and whose column offsets are preserved), §4.1, and checklist invariant 1.The two
h2_stream_table.rs:125line citations in LIFECYCLE.md are replaced by the symbol theprose already names, not renumbered. That is deliberate and it matters:
streams:is still line 125 and lines 126–131 are byte-identical to their pre-image. Renumberinga citation that is already correct is how a wrong number gets merged.
check_doc_citations.pyitself recommends over a number.legitimately changed stays compared and stays reported.
Gate results on the final tree, all exit 0:
--root .--base d192407b(merge base)--base 42ed6bach2.rsre-anchors, none from this commitThe
0 exempton the merge-base run is the load-bearing number: the exemption is the gate's blindspot, and this changeset renumbers nothing, so nothing was skipped. Independently: every cited file
this commit touches has a line-count delta of exactly 0 against
d192407b.Still stale in
LIFECYCLE.md, not touched here because they are not caused by this change —stream_last_activity_at,stream_fc_stalled_sinceandstream_fc_stalled_progresswere alreadyBTreeMapbefore this commit, yet §7.2 (lines 676, 683, 684) still calls all threeHashMap.Reported for the doc-corrections changeset rather than edited.
The
sozu-e2eflake, and why it is not this changeTwo full-suite runs on this branch each lost one test. Taking the H2 one first: this change cannot
reach
test_h2_continuation_survives_a_graceful_drain_mid_reassembly. Every site that readsstreamsis either order-free byconstruction or unreachable in its fixture:
write_streams→H2Scheduler::begin_passsorts the ids it is handed withsort_by_cached_key(|id| (urgency, *id)).*idis unique, so the result is fully determined bythe key set; the input order is discarded. The ready-incremental census then iterates that
sorted buffer.
compute_stream_byte_totalsaccumulates twousizesums — commutative.any_stream_has_pending_back/any_stream_id_matchesare.any(): the boolean cannot depend onvisit order.
update_initial_window_sizediffers only on thechecked_addoverflow abort, which needs aSETTINGS_INITIAL_WINDOW_SIZElarge enough to push a stream window past 2^31-1. The test sends nosuch SETTINGS.
handle_goaway_frameneeds a GOAWAY received from the peer. Here Sōzu is the one sending it;the test client sends none.
ConnectionH2::close'sendpoint.end_streamteardown walk runs only underPosition::Client—an H2 backend. The fixture builds its cluster with
Worker::default_cluster, which leavesCluster.http2at its default, so the backend leg is HTTP/1.1 and noPosition::ClientConnectionH2exists. The frontend connection isPosition::Server, and that match arm returnsbefore the teardown loop.
close's debug-log loop and theDebugimpl order log lines only.The full
sozu-e2esuite flakes at a low rate under its own parallel load, on different tests eachtime. Measured across five full runs of the identical CI command on this machine (20 cores):
42ed6bacd192407b(merge base)h2_tests::test_h2_continuation_survives_a_graceful_drain_mid_reassembly, iteration 3 of 5h1_security_tests::test_h1_smuggling_te_cl_trailing_tab, iteration 4 of 5The second branch failure is the one that settles it:
e2e/src/tests/h1_security_tests.rscontainsno reference to HTTP/2, h2c,
ConnectionH2or an HTTPS listener, and this diff touches onlyh2.rs,h2_scheduler.rs,h2_stream_table.rs, the bench and docs. There is no shared code path,so that failure cannot originate here — which establishes that this suite fails at a base rate on
this branch for reasons unrelated to the change, and removes the need to explain the first one with
it. The H2 drain test itself is 3/3 green in isolation on the branch and 3/3 green in isolation on
the base; it was tightened to sit inside a mid-frame window earlier the same day in
c10b94a4(#1481), and
doc/testing.mddocuments that window as byte-counter-sequenced. ClassifiedCANNOT-REPRODUCE as a regression, not "probably unrelated".