Skip to content

refactor(mux-h2): make the H2 wire stream map a BTreeMap - #1506

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-stream-table-btreemap
Sep 24, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-stream-table-btreemap

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

What

H2StreamTable::streams — the wire StreamId -> GlobalStreamId map every inbound H2 frame is
looked up in — becomes a BTreeMap. It was the last of the five maps in the H2 core still walked
in RandomState order, and the last open question in #1338.

Why the old module doc was wrong

h2_stream_table.rs's Determinism section stated that streams "stays a HashMap — it is NOT a
determinism 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_size is the counter-example, and it is the site the old text singled out as
safe ("applies an additive delta to each stream's own window field independently and OR-combines
a bool — both order-independent"):

for &global_stream_id in self.stream_table.streams().values() {
    let stream = &mut context.streams[global_stream_id];
    match stream.window.checked_add(delta) {
        Some(new_window) => {
            open_window |= stream.window <= 0 && new_window > 0;
            stream.window = new_window;
        }
        None => return true,
    }
}

The None arm returns from inside the loop, and the writes already made to
context.streams[..].window are not rolled back. So on a SETTINGS_INITIAL_WINDOW_SIZE that
overflows one stream, which prefix of the other streams was already mutated is exactly the
iteration order. handle_settings_frame turns the true into GOAWAY, and the half-updated
window set stays in context.streams for close'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_frame walks streams() into retry_streams and pushes each retryable stream
    onto context.pending_links — so relink, and therefore reconnect/dial order, was hash order.
  • ConnectionH2::close notifies each linked stream through endpoint.end_stream — so teardown
    notification 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)

streams is the only one of the five on the per-frame path, so lib/benches/h2_stream_table.rs
(#1502) was written before the decision. btree / fixed-seed ratios, below 1.00 = BTreeMap
faster:

group n=8 n=100 n=1000 n=10000
get_hit 0.43 0.83 2.38 6.40
get_miss 0.57 0.88 2.00 6.12
churn 0.58 0.88 1.30 2.98
write_pass uniform 0.53 0.59 1.15 1.11
write_pass varied 0.58 0.93 1.94 2.16

The realistic range is n = 8 (the occupancy H2StreamTable::new used to declare) to n = 100
(DEFAULT_MAX_CONCURRENT_STREAMS): BTreeMap is 1.7–2.3x faster at 8 and equal-or-faster at 100,
because SipHash-1-3 over a u32 costs ~9 ns whatever n is while a tree of eleven keys or fewer is
one 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 RandomState in
all 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. BTreeMap has no with_capacity — it
    allocates a node at a time, not one contiguous bucket array. H2StreamTable::new's doc now says
    so 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.
  • Every signature that carried the container type moves with it: any_stream_has_pending_back,
    any_stream_id_matches (h2.rs), Prioriser::push_priority_guarded and its is_acceptable, and
    H2Scheduler::push_priority_guarded (h2_scheduler.rs).
  • The h2_stream_table.rs module-doc Determinism section is rewritten around the reasoning above.
  • doc/architecture.md, doc/h2_mux_internals.md and the bench's prose are updated in the same
    changeset.

Regression test, seen red

streams_iterates_in_ascending_stream_id_order_whatever_the_insertion_order registers nine
scrambled 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 and
nothing else):

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 1113 filtered out; finished in 0.00s

Green, on this branch:

test result: ok. 1114 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 2.17s

The failing value is deliberately not quoted as a fact anywhere: RandomState is seeded per
process, 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 (the H2StreamTable
field diagram and the push_priority_guarded signature row), lib/benches/h2_stream_table.rs's
prose, and lib/src/protocol/mux/LIFECYCLE.md — §1.2 prose, the §1.2 ASCII diagram (which spells
streams: HashMap twice, and whose column offsets are preserved), §4.1, and checklist invariant 1.

The two h2_stream_table.rs:125 line citations in LIFECYCLE.md are replaced by the symbol the
prose already names, not renumbered
. That is deliberate and it matters:

  • The field did not move. The module-doc rewrite replaces 39 lines with exactly 39, so
    streams: is still line 125 and lines 126–131 are byte-identical to their pre-image. Renumbering
    a citation that is already correct is how a wrong number gets merged.
  • A symbol cannot drift, which is what check_doc_citations.py itself recommends over a number.
  • It is also the only edit that turns the gate green: a correct line citation whose target text
    legitimately changed stays compared and stays reported.

Gate results on the final tree, all exit 0:

command result
--root . 205 citations resolve; 557 cited test names resolve; 16 pinned blocks verbatim
--base d192407b (merge base) none of 321 compared lines changed — 0 re-anchored spans exempt
--base 42ed6bac none of 257 compared lines changed; 64 exempt, all of them d192407's own h2.rs re-anchors, none from this commit

The 0 exempt on the merge-base run is the load-bearing number: the exemption is the gate's blind
spot, 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_since and stream_fc_stalled_progress were already
BTreeMap before this commit, yet §7.2 (lines 676, 683, 684) still calls all three HashMap.
Reported for the doc-corrections changeset rather than edited.

The sozu-e2e flake, and why it is not this change

Two 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 reads streams is either order-free by
construction or unreachable in its fixture:

  • write_streams → H2Scheduler::begin_pass sorts the ids it is handed with
    sort_by_cached_key(|id| (urgency, *id)). *id is unique, so the result is fully determined by
    the key set; the input order is discarded. The ready-incremental census then iterates that
    sorted buffer.
  • compute_stream_byte_totals accumulates two usize sums — commutative.
  • any_stream_has_pending_back / any_stream_id_matches are .any(): the boolean cannot depend on
    visit order.
  • update_initial_window_size differs only on the checked_add overflow abort, which needs a
    SETTINGS_INITIAL_WINDOW_SIZE large enough to push a stream window past 2^31-1. The test sends no
    such SETTINGS.
  • handle_goaway_frame needs a GOAWAY received from the peer. Here Sōzu is the one sending it;
    the test client sends none.
  • ConnectionH2::close's endpoint.end_stream teardown walk runs only under Position::Client —
    an H2 backend. The fixture builds its cluster with Worker::default_cluster, which leaves
    Cluster.http2 at its default, so the backend leg is HTTP/1.1 and no Position::Client
    ConnectionH2 exists. The frontend connection is Position::Server, and that match arm returns
    before the teardown loop.
  • close's debug-log loop and the Debug impl order log lines only.

The full sozu-e2e suite flakes at a low rate under its own parallel load, on different tests each
time. Measured across five full runs of the identical CI command on this machine (20 cores):

tree result failing test
base 42ed6bac 447 passed, 0 failed —
base d192407b (merge base) 447 passed, 0 failed —
branch, pre-rebase 446 passed, 1 failed h2_tests::test_h2_continuation_survives_a_graceful_drain_mid_reassembly, iteration 3 of 5
branch, rebased 446 passed, 1 failed h1_security_tests::test_h1_smuggling_te_cl_trailing_tab, iteration 4 of 5
branch, rebased (re-run) 447 passed, 0 failed —

The second branch failure is the one that settles it: e2e/src/tests/h1_security_tests.rs contains
no reference to HTTP/2, h2c, ConnectionH2 or an HTTPS listener, and this diff touches only
h2.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.md documents that window as byte-counter-sequenced. Classified
CANNOT-REPRODUCE as a regression, not "probably unrelated".

`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
FlorentinDUBOIS force-pushed the refactor/h2-stream-table-btreemap branch from d4fc8d1 to 3907708 Compare September 24, 2026 15:21
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 0dddedf into main Sep 24, 2026
27 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the refactor/h2-stream-table-btreemap branch September 24, 2026 16:15
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