Repository navigation
refactor(mux-h2): extract the wire-level stream-slot bookkeeping, and make RST_STREAM reap order deterministic - #1414
Closed
FlorentinDUBOIS wants to merge 1 commit into
Closed
FlorentinDUBOIS wants to merge 1 commit into
FlorentinDUBOIS wants to merge 1 commit into
Conversation
Move the wire StreamId -> GlobalStreamId map, highest_peer_stream_id, expect_read/expect_write, rst_sent, and the per-stream activity/flow-control-stall caches into lib/src/protocol/mux/h2_stream_table.rs, behind the same closed-API shape hpack_state.rs and h2_flow_control.rs established in the two prior extraction steps. ConnectionH2 keeps a single private stream_table: H2StreamTable field. create_stream, start_stream, remove_dead_stream and refuse_stream_and_discard stay on ConnectionH2 (they orchestrate Context, logging, metrics, the RFC 9218 prioriser and readiness, none of which the new module has), but their stream-table bookkeeping now delegates to H2StreamTable's narrow API. H2StreamTable::remove is the sole removal chokepoint, including the expect_read/expect_write gid invalidation LIFECYCLE.md SS5.4 documents; streams is now a private field of h2_stream_table.rs, so self.streams.remove(...) cannot be written from h2.rs any more, which was verified by temporarily reintroducing an inline removal and observing E0609 (reverted). This makes SS5.4's "no call site removes inline anymore" claim compiler-enforced instead of prose that can silently go stale, which already happened to it once (#1399). On this branch the claim was independently verified true before the move too: self.streams.remove occurred at exactly one call site, inside remove_dead_stream itself, so no parallel removal site needed eliminating here. Determinism fix: H2StreamTable::collect_timed_out (the reap-candidate union cancel_timed_out_streams drives) used to read stream_last_activity_at and stream_fc_stalled_since as plain HashMaps with `for (&k, &v) in map` loops, so which of several simultaneously-timed-out streams got RST_STREAM'd first was non-deterministic across process restarts -- the same class of leak issue #1338 decided to close, and the same fix step 2 already applied to pending_window_updates. That order flows onto the wire: collect_timed_out's returned order is the order cancel_timed_out_streams calls enqueue_rst in, which pushes onto pending_rst_streams, drained in push order. Both maps are now BTreeMap (stream_fc_stalled_progress converts alongside stream_fc_stalled_since since the two are documented as kept in lockstep), so collect_timed_out walks each guard group in ascending StreamId order. Every other iteration over the wire map itself was enumerated by reading (not only grepping for .iter()/.keys()/.values()/.drain(), which misses a `for (&k, &v) in &map` site) and found not to leak: the priority scheduler's HashMap-order keys() feed is immediately sorted by (urgency, *id), a total order; the GOAWAY retry loop and close()'s backend-teardown loop only affect scheduling order, not the bytes of a fixed frame set; and GOAWAY's own last_stream_id is the incrementally-updated highest_peer_stream_id scalar. H2StreamTable carries debug_assert! pre/post-conditions on every mutating method plus a check_invariants() sweep, matching h2_flow_control::H2FlowControl and protocol::udp::manager::UdpManager. router.rs reaches the wire-map length through a new ConnectionH2::stream_count() accessor, the sole external reader now that the field is private. LIFECYCLE.md citations are re-anchored by content throughout; doc/h2_mux_internals.md, doc/lifetime_of_a_session.md and doc/testing.md follow. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 22, 2026 00:11
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.
Step 3 of the H2 sans-io extraction. Stacked on #1406 (step 2) — GitHub will retarget this to
mainwhen that lands. Step 1 was #1403.
Seven raw fields move off
ConnectionH2into a privateH2StreamTablewith a closedpub(super)API, the same shape
hpack_state.rs(#1403) andh2_flow_control.rs(#1406) established: theStreamId → GlobalStreamIdwire map,highest_peer_stream_id,expect_read,expect_write,rst_sent, and the three per-stream activity and flow-control-stall maps.create_stream,start_stream,remove_dead_streamandrefuse_stream_and_discardstay onConnectionH2— they needContext, logging, metrics, the RFC 9218 prioriser and readiness, none ofwhich belong in the new module — but delegate their bookkeeping to it. Around 225 call sites rewritten.
router.rsgains one accessor because the field it read is now private.Deliberately not touched, because they are later steps or belong elsewhere: the generic recycle
slab shared with H1 (
StreamState,Context::create_stream,shrink_trailing_recycle),stream.rs,and HEADERS+CONTINUATION reassembly with the
zero.storagebuffer.shared.rshas a zero-line diff,which matters because it is used byte-for-byte by H1.
The invariant stops being prose and becomes a compiler error
LIFECYCLE.md§5.3 explains at length whyexpect_read/expect_writeinvalidation is non-trivial,and #1399 had to correct documentation that falsely claimed no inline
streams.removesites remained.That claim was actually true on this base — exactly one
self.streams.remove(...)existed, insideremove_dead_stream. What this changeset adds is that it can no longer be written:streamsisprivate to
h2_stream_table.rs, so an inline removal inh2.rsdoes not compile. Verified byinjecting one into
force_disconnectand gettingerror[E0609]: no field 'streams', then reverting.H2StreamTable::removehas exactly one caller.An invariant that a reviewer had to check by reading is now one the compiler checks.
A real determinism leak, found by reading rather than grepping
streamsitself is not a leak, and stays aHashMap. Every iteration over it was read, notgrepped, and each is order-independent:
write_streamsdiscards map order throughsort_by_cached_key(|id| (urgency, *id)), a total order since the id is a unique tiebreaker;compute_stream_byte_totalsandupdate_initial_window_sizeare commutative;handle_goaway_frame'sretry loop and
close()'s teardown loop affect scheduling rather than the bytes of a fixed frame set;close()'s debug loop is log-only; and GOAWAY'slast_stream_idcomes from thehighest_peer_stream_idscalar, never from iterating.But two of the maps being extracted were leaking.
collect_timed_outiteratedstream_last_activity_atandstream_fc_stalled_sincewithfor (&k, &v) in map, and that orderbecomes the order
cancel_timed_out_streamscallsenqueue_rst, which pushes ontopending_rst_streamsand is drained in push order. RST_STREAM emission order for idle-timeout andwindow-stall reaps was non-deterministic across process restarts — the same class #1406 fixed for
WINDOW_UPDATE.
No grep for
.iter(),.keys(),.values()or.drain()can seefor (&k, &v) in map. A previousenumeration of these leaks in this repository was wrong twice for exactly that reason.
Red:
Fixed by converting all three maps to
BTreeMap— the third,stream_fc_stalled_progress, comesalong because
LIFECYCLE.md§7.2 requires it stay in lockstep with its sibling.Why ascending order is fair here, when it needed an argument for WINDOW_UPDATE
#1406 had to argue that ascending stream-id order could not starve anyone, resting on the queue
draining fully in one pass. The argument here is different and stronger, and it is recorded in the
module doc rather than only in this description:
A wire
StreamIdis never reused (RFC 9113 §5.1.1). A stream reaped earlier in one pass nevercompetes for that slot again — there is no round-over-round disadvantage the way a low-numbered stream
could keep winning a replenished connection-level send window on every drain. A one-shot reap and a
repeatedly contested resource are different problems, and only the second needs a fairness cursor.
Partial drain was checked anyway:
total_rst_streams_queued >= MAX_PENDING_RST_STREAMS(200) is testedbefore the drain loop and short-circuits to
GOAWAY(EnhanceYourCalm), so the loop only runs below200 entries, and 200 × 13 bytes fits inside the 16393-byte buffer floor. The
breakpath isunreachable under default configuration.
That trace also surfaced a pre-existing latent gap, filed as #1413 and deliberately not addressed
here:
enqueue_rst_intohas no per-insert cap, so a mass reap can grow the queue past the boundcheck_invariantsasserts. Verified byte-identical at this changeset's base.Tests
371 pass in
protocol::mux. Three tests were deleted and replaced by nine in the new module — thethree original scenarios are covered verbatim or split cleanly, plus six covering
register,removeand
observe_peer_stream_id, which had no unit-level coverage before.One coverage consequence is documented rather than papered over:
collect_timed_out'sstreams.contains_keyguard defends against an activity entry outliving its wire-map entry, and theclosed API makes that state unconstructible even from a test, since
registerandremovekeep bothmaps in lockstep. A comment at that guard says so — untested by construction rather than by omission,
kept as defence in depth against a future internal change breaking the lockstep, and not to be deleted
as apparently-dead code. No test reaching into private fields was added; that would test the escape
hatch rather than the contract.
Documentation
About 131 citations re-anchored by content — locating where each original cited text now lives —
never by arithmetic. A review re-verified all 193 compared citations byte-identical by script.
doc/lifetime_of_a_session.mdanddoc/testing.mdalso carried driftedmux/h2.rs:citations and arefixed; sweeping by cited path rather than by document is a lesson from a sibling changeset where CI
caught the miss.
Validation, both feature shapes
The bare-defaults pair is run because CI's
msrv-barecell sees a feature-off tree that an--all-features-only chain cannot.Refs #1336, #1338, #1339, #1413.