Skip to content

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
refactor/h2-flow-control-bfrom
refactor/h2-stream-slots
Closed

FlorentinDUBOIS wants to merge 1 commit into
refactor/h2-flow-control-bfrom
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.

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]>
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