Skip to content

refactor(mux-h2): extract the wire-level stream-slot bookkeeping, and make RST_STREAM reap order deterministic - #1415

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-stream-slots
Sep 22, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-stream-slots

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Step 3 of the H2 sans-io extraction. Stacked on #1406 (step 2) — GitHub will retarget this to main
when that lands. Step 1 was #1403.

Seven raw fields move off ConnectionH2 into a private H2StreamTable with a closed pub(super)
API, the same shape hpack_state.rs (#1403) and h2_flow_control.rs (#1406) established: the
StreamId → GlobalStreamId wire 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_stream and refuse_stream_and_discard stay on
ConnectionH2 — they need Context, logging, metrics, the RFC 9218 prioriser and readiness, none of
which belong in the new module — but delegate their bookkeeping to it. Around 225 call sites rewritten.
router.rs gains 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.storage buffer. shared.rs has 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 why expect_read/expect_write invalidation is non-trivial,
and #1399 had to correct documentation that falsely claimed no inline streams.remove sites remained.

That claim was actually true on this base — exactly one self.streams.remove(...) existed, inside
remove_dead_stream. What this changeset adds is that it can no longer be written: streams is
private to h2_stream_table.rs, so an inline removal in h2.rs does not compile. Verified by
injecting one into force_disconnect and getting error[E0609]: no field 'streams', then reverting.
H2StreamTable::remove has 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

streams itself is not a leak, and stays a HashMap. Every iteration over it was read, not
grepped, and each is order-independent: write_streams discards map order through
sort_by_cached_key(|id| (urgency, *id)), a total order since the id is a unique tiebreaker;
compute_stream_byte_totals and update_initial_window_size are commutative; handle_goaway_frame's
retry 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's last_stream_id comes from the
highest_peer_stream_id scalar, never from iterating.

But two of the maps being extracted were leaking. collect_timed_out iterated
stream_last_activity_at and stream_fc_stalled_since with for (&k, &v) in map, and that order
becomes the order cancel_timed_out_streams calls enqueue_rst, which pushes onto
pending_rst_streams and is drained in push order. RST_STREAM emission order for idle-timeout and
window-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 see for (&k, &v) in map. A previous
enumeration of these leaks in this repository was wrong twice for exactly that reason.

Red:

collect_timed_out must return the idle-timeout guard group in ascending stream_id order
  left:  [17, 501, 777, 45, 1, 5, 3, 901, 19]
 right:  [1, 3, 5, 17, 19, 45, 501, 777, 901]

Fixed by converting all three maps to BTreeMap — the third, stream_fc_stalled_progress, comes
along 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 StreamId is never reused (RFC 9113 §5.1.1). A stream reaped earlier in one pass never
competes 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 tested
before the drain loop and short-circuits to GOAWAY(EnhanceYourCalm), so the loop only runs below
200 entries, and 200 × 13 bytes fits inside the 16393-byte buffer floor. The break path is
unreachable under default configuration.

That trace also surfaced a pre-existing latent gap, filed as #1413 and deliberately not addressed
here: enqueue_rst_into has no per-insert cap, so a mass reap can grow the queue past the bound
check_invariants asserts. 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 — the
three original scenarios are covered verbatim or split cleanly, plus six covering register, remove
and observe_peer_stream_id, which had no unit-level coverage before.

One coverage consequence is documented rather than papered over: collect_timed_out's
streams.contains_key guard defends against an activity entry outliving its wire-map entry, and the
closed API makes that state unconstructible even from a test, since register and remove keep both
maps 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.md and doc/testing.md also carried drifted mux/h2.rs: citations and are
fixed; sweeping by cited path rather than by document is a lesson from a sibling changeset where CI
caught the miss.

Validation, both feature shapes

cargo +1.93.1 build --all-features --locked                       -> exit 0
cargo +1.93.1 build --locked                                      -> exit 0
cargo +1.93.1 clippy --all-targets --all-features -- -D warnings  -> exit 0
cargo +1.93.1 clippy --all-targets --locked -- -D warnings        -> exit 0
cargo +nightly fmt --all -- --check                               -> exit 0
cargo +1.93.1 test -p sozu-lib --locked protocol::mux             -> 371 passed, 0 failed
python3 .github/scripts/check_doc_citations.py --base origin/refactor/h2-flow-control-b -> exit 0

The bare-defaults pair is run because CI's msrv-bare cell sees a feature-off tree that an
--all-features-only chain cannot.

Refs #1336, #1338, #1339, #1413.


Replaces #1414, which GitHub auto-closed when its base branch refactor/h2-flow-control-b was
deleted by the squash-merge of #1406. Same commit content, rebased onto main at ec7d46b1 (the
step-2 commit dropped, since its content is already there), revalidated after the rebase — build and
clippy in both feature shapes, 371 tests in protocol::mux, and the citation gate against the new
base — all exit 0.

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
FlorentinDUBOIS merged commit 595920e into main Sep 22, 2026
24 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the refactor/h2-stream-slots branch September 22, 2026 05:06
FlorentinDUBOIS added a commit that referenced this pull request Sep 24, 2026
…e code

lib/src/protocol/mux/LIFECYCLE.md carried three `path:NNN` citations that
resolved to real, non-blank, unrelated lines, which is all any rule in
check_doc_citations.py asks of them:

- §4.2 put the `Context.streams` push at `mod.rs:648-649`. Those are
  `listener.get_sticky_name().to_string()` and
  `listener.get_sozu_id_header().to_string()`, arguments of the
  `HttpContext::new(...)` call that opens `Context::create_stream`. The push is
  `self.streams.push(stream)` at `mod.rs:708`.
- §3.1's `Unlinked` bullet read `h1.rs:995-1052`. `995` is a format string in
  `ConnectionH1::end_stream`'s wrong-stream `error!` guard and `1052` is a
  `debug_assert!` argument; the four `StreamState::Unlinked` assignments the
  range is meant to bracket are `h1.rs:1042-1099`. It was exact at fbc83ed
  (`h1.rs:737-772` against assignments at 737, 745, 767 and 772) and successive
  renumberings walked it off them.
- §7.5's arm-site list read `h2.rs:5384`, which is `log_context!(self)` inside
  an `error!` for an out-of-bounds header block fragment. The HEADERS liveness
  refresh is `self.stream_table.touch_activity(stream_id, self.now)` at
  `h2.rs:5418`. #1501 renumbered that one from `h2.rs:5376` in the commit
  directly below this one, faithfully and still onto the wrong statement: a
  re-anchor preserves the pointer, not the claim.

§7.2 described all three per-stream reap caches as `ConnectionH2` fields
holding a `HashMap`. Both halves are wrong and have been since #1415's
stream-slot-bookkeeping extraction: `stream_last_activity_at`,
`stream_fc_stalled_since` and `stream_fc_stalled_progress` are private
`BTreeMap` fields of `H2StreamTable`, built by `BTreeMap::new()` in
`H2StreamTable::new`, and `ConnectionH2` declares no field of any of those
names. #1415 converted them for the determinism reason its own CHANGELOG entry
records and updated §4.1's wire-map bullet, but left §7.2 on the pre-extraction
shape, so the section now inverts the ordering guarantee the code provides.
Cited by symbol rather than line: that module is being edited under #1338.

CHANGELOG.md's #1484 entry said `shared::drain_tls_close_notify`'s two
uncovered lines were uncovered "because nothing calls that function at all". It
has two production callers, the `Position::Server` arms of `ConnectionH1::close`
and `ConnectionH2::close`. What #1484 measured is that its own six-test fixture
never reaches them. Only that causal clause changed; every count and probe tally
in that historical entry was true as measured and is left as written.

The three citations sat in the drift rule's exemption: it keys on the citation
tuple as it stood in the base revision of the citing document, so a renumbered
span is counted exempt and never compared. Measured at 42ed6ba over the window
they were renumbered in, --base f2082b6 --show reported 133 exempt cited ends
across 91 doc sites; 11 are fenced blocks the pinned-quote rule already compares
verbatim, and reading the remaining 80 against the code they name found 77
correct and these three wrong. --base 42ed6ba --show on this tree exempts 67
more, the spans #1501's renumbering re-anchored: 15 pinned fences, the 4 repaired
here, and 48 that anchor on byte-identical text before and after it. --audit
reports 7 findings on this tree, all 7 the heuristic pairing a prose symbol with
a line eight or more away from it. The three §7.2 declarations were in no rule's
surface at all: every rule resolves a `path:NNN` or a fenced quote, and a
sentence naming a type and a container carries neither. Sweeping LIFECYCLE.md
for the same shape leaves only the three `ConnectionH2.streams` references that
#1338 already owns.

Documentation only: no production code, no test, no dependency and no
Cargo.lock entry changes.

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 24, 2026
…e code

lib/src/protocol/mux/LIFECYCLE.md carried three `path:NNN` citations that
resolved to real, non-blank, unrelated lines, which is all any rule in
check_doc_citations.py asks of them:

- §4.2 put the `Context.streams` push at `mod.rs:713-714`. Those are
  `listener.get_sticky_name().to_string()` and
  `listener.get_sozu_id_header().to_string()`, arguments of the
  `HttpContext::new(...)` call that opens `Context::create_stream`. The push is
  `self.streams.push(stream)` at `mod.rs:773`.
- §3.1's `Unlinked` bullet read `h1.rs:995-1052`. `995` is a format string in
  `ConnectionH1::end_stream`'s wrong-stream `error!` guard and `1052` is a
  `debug_assert!` argument; the four `StreamState::Unlinked` assignments the
  range is meant to bracket are `h1.rs:1042-1099`. It was exact at fbc83ed
  (`h1.rs:737-772` against assignments at 737, 745, 767 and 772) and successive
  renumberings walked it off them.
- §7.5's arm-site list read `h2.rs:5387`, which is `log_context!(self)` inside
  an `error!` for an out-of-bounds header block fragment. The HEADERS liveness
  refresh is `self.stream_table.touch_activity(stream_id, self.now)` at
  `h2.rs:5421`. The two commits directly below this one each renumbered that
  citation and neither noticed: #1501 moved it from `h2.rs:5376` to
  `h2.rs:5384`, and #1497 from `h2.rs:5384` to `h2.rs:5387`. Both moves were
  faithful and both landed on `log_context!(self)`: a re-anchor preserves the
  pointer, not the claim.

§7.2 described all three per-stream reap caches as `ConnectionH2` fields
holding a `HashMap`. Both halves are wrong and have been since #1415's
stream-slot-bookkeeping extraction: `stream_last_activity_at`,
`stream_fc_stalled_since` and `stream_fc_stalled_progress` are private
`BTreeMap` fields of `H2StreamTable`, built by `BTreeMap::new()` in
`H2StreamTable::new`, and `ConnectionH2` declares no field of any of those
names. #1415 converted them for the determinism reason its own CHANGELOG entry
records and updated §4.1's wire-map bullet, but left §7.2 on the pre-extraction
shape, so the section now inverts the ordering guarantee the code provides.
Cited by symbol rather than line: that module is being edited under #1338.

CHANGELOG.md's #1484 entry said `shared::drain_tls_close_notify`'s two
uncovered lines were uncovered "because nothing calls that function at all". It
has two production callers, the `Position::Server` arms of `ConnectionH1::close`
and `ConnectionH2::close`. What #1484 measured is that its own six-test fixture
never reaches them. Only that causal clause changed; every count and probe tally
in that historical entry was true as measured and is left as written.

The three citations sat in the drift rule's exemption: it keys on the citation
tuple as it stood in the base revision of the citing document, so a renumbered
span is counted exempt and never compared. Measured at 42ed6ba over the window
they were renumbered in, --base f2082b6 --show reported 133 exempt cited ends
across 91 doc sites; 11 are fenced blocks the pinned-quote rule already compares
verbatim, and reading the remaining 80 against the code they name found 77
correct and these three wrong. --base 42ed6ba --show on this tree exempts 109
more, the spans #1501's and #1497's renumberings re-anchored: 15 pinned fences,
the 4 repaired here, and 90 that anchor on byte-identical text before and after
them. --audit
reports 7 findings on this tree, all 7 the heuristic pairing a prose symbol with
a line eight or more away from it. The three §7.2 declarations were in no rule's
surface at all: every rule resolves a `path:NNN` or a fenced quote, and a
sentence naming a type and a container carries neither. Sweeping LIFECYCLE.md
for the same shape leaves only the three `ConnectionH2.streams` references that

Documentation only: no production code, no test, no dependency and no
Cargo.lock entry changes.

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 24, 2026
…e code (#1504)

lib/src/protocol/mux/LIFECYCLE.md carried three `path:NNN` citations that
resolved to real, non-blank, unrelated lines, which is all any rule in
check_doc_citations.py asks of them:

- §4.2 put the `Context.streams` push at `mod.rs:713-714`. Those are
  `listener.get_sticky_name().to_string()` and
  `listener.get_sozu_id_header().to_string()`, arguments of the
  `HttpContext::new(...)` call that opens `Context::create_stream`. The push is
  `self.streams.push(stream)` at `mod.rs:773`.
- §3.1's `Unlinked` bullet read `h1.rs:995-1052`. `995` is a format string in
  `ConnectionH1::end_stream`'s wrong-stream `error!` guard and `1052` is a
  `debug_assert!` argument; the four `StreamState::Unlinked` assignments the
  range is meant to bracket are `h1.rs:1042-1099`. It was exact at fbc83ed
  (`h1.rs:737-772` against assignments at 737, 745, 767 and 772) and successive
  renumberings walked it off them.
- §7.5's arm-site list read `h2.rs:5387`, which is `log_context!(self)` inside
  an `error!` for an out-of-bounds header block fragment. The HEADERS liveness
  refresh is `self.stream_table.touch_activity(stream_id, self.now)` at
  `h2.rs:5421`. The two commits directly below this one each renumbered that
  citation and neither noticed: #1501 moved it from `h2.rs:5376` to
  `h2.rs:5384`, and #1497 from `h2.rs:5384` to `h2.rs:5387`. Both moves were
  faithful and both landed on `log_context!(self)`: a re-anchor preserves the
  pointer, not the claim.

§7.2 described all three per-stream reap caches as `ConnectionH2` fields
holding a `HashMap`. Both halves are wrong and have been since #1415's
stream-slot-bookkeeping extraction: `stream_last_activity_at`,
`stream_fc_stalled_since` and `stream_fc_stalled_progress` are private
`BTreeMap` fields of `H2StreamTable`, built by `BTreeMap::new()` in
`H2StreamTable::new`, and `ConnectionH2` declares no field of any of those
names. #1415 converted them for the determinism reason its own CHANGELOG entry
records and updated §4.1's wire-map bullet, but left §7.2 on the pre-extraction
shape, so the section now inverts the ordering guarantee the code provides.
Cited by symbol rather than line: that module is being edited under #1338.

CHANGELOG.md's #1484 entry said `shared::drain_tls_close_notify`'s two
uncovered lines were uncovered "because nothing calls that function at all". It
has two production callers, the `Position::Server` arms of `ConnectionH1::close`
and `ConnectionH2::close`. What #1484 measured is that its own six-test fixture
never reaches them. Only that causal clause changed; every count and probe tally
in that historical entry was true as measured and is left as written.

The three citations sat in the drift rule's exemption: it keys on the citation
tuple as it stood in the base revision of the citing document, so a renumbered
span is counted exempt and never compared. Measured at 42ed6ba over the window
they were renumbered in, --base f2082b6 --show reported 133 exempt cited ends
across 91 doc sites; 11 are fenced blocks the pinned-quote rule already compares
verbatim, and reading the remaining 80 against the code they name found 77
correct and these three wrong. --base 42ed6ba --show on this tree exempts 109
more, the spans #1501's and #1497's renumberings re-anchored: 15 pinned fences,
the 4 repaired here, and 90 that anchor on byte-identical text before and after
them. --audit
reports 7 findings on this tree, all 7 the heuristic pairing a prose symbol with
a line eight or more away from it. The three §7.2 declarations were in no rule's
surface at all: every rule resolves a `path:NNN` or a fenced quote, and a
sentence naming a type and a container carries neither. Sweeping LIFECYCLE.md
for the same shape leaves only the three `ConnectionH2.streams` references that

Documentation only: no production code, no test, no dependency and no
Cargo.lock entry changes.

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