…113 §6.9)
Move H2FlowControl (send window, receive-side byte accounting, pending
WINDOW_UPDATE queue), queue_window_update, the connection-level
(stream_id == 0) arm of handle_window_update_frame's window arithmetic,
and the WINDOW_UPDATE drain stage of flush_pending_control_frames into a
new lib/src/protocol/mux/h2_flow_control.rs, behind the same closed-API
shape hpack_state.rs established in the prior step: private fields,
narrow pub(super) accessor/mutator methods, debug_assert! pre/post-
conditions, and a check_invariants() sweep run as a post-condition of
every public mutating method, exactly as protocol::udp::manager::UdpManager
does. ConnectionH2 keeps only the frame-dispatch orchestration (flood
counters, logging, GOAWAY) that needs `self`; the per-stream arm of
handle_window_update_frame and Stream.window are untouched, staying on
ConnectionH2/Stream for a later step. The new type's transmit surface,
drain_window_updates_into(&mut self, buf: &mut [u8]) -> (usize, usize),
follows the house serializer::gen_*(buf, ...) caller-supplied-buffer
contract: it writes into the caller's existing zero.storage ring buffer
and never allocates or returns owned bytes.
Separately, and it is a behaviour change: pending_window_updates was a
HashMap<u32, u32>, and the drain loop serialized it in the map's
iteration order, which is seeded per-process (RandomState) — so which
stream's WINDOW_UPDATE reached the wire first was non-deterministic
across process restarts, one of the order leaks issue #1338 decided to
close. It is now a BTreeMap, so drain order is the ascending stream-id
total order: deterministic, free of an extra sort step, and the
connection-level entry (key 0) always sorts first, which is also the
protocol-friendlier choice — it unblocks every stream at once rather
than merely being reproducible.
A narrower correctness fix rides along: queue_window_update used to
insert a zero-increment entry for an empty non-END_STREAM DATA frame
and let the drain stage silently skip it; it now treats increment == 0
as a no-op and queues nothing. This does NOT change the
h2.connection.pending_window_updates gauge, which is sampled only from
gauge_connection_state via write_streams on the writable() path, after
flush_pending_control_frames (which already stripped any zero-increment
entry) has already run at the top of that same writable() call — the
gauge never observed a dead entry either way, before or after this fix.
What the fix actually changes is the pending map's state at rest,
between the readable() pass that used to insert a zero entry and the
next writable() pass that would have flushed it: fewer inserts and
removes, and a check_invariants invariant that holds unconditionally
rather than only by the time anything looks.
The RFC 9113 §6.9.1 2^31-1 ceiling is asserted where it is actually
checkable: apply_window_update's overflow arm widens to i64 and
confirms checked_add rejected the increment because the true sum
exceeds i32::MAX, rather than comparing the already-i32 window against
i32::MAX on the struct itself, which clippy's absurd_extreme_comparisons
correctly rejects as a tautology the i32 type already guarantees.
Complexity is UNMEASURED beyond the default max_concurrent_streams:
queue_window_update's BTreeMap insert/coalesce is O(log n) against the
prior HashMap's amortized O(1), where n is capped at 1 + 4 *
max_concurrent_streams. At the default (n <= 401) this is not expected
to be measurable, but that expectation has not been benchmarked, and an
operator raising max_concurrent_streams up to MAX_SAFE_CONCURRENT_STREAMS
(10_000) reaches n = 40_001 by the same formula — the point at which
O(log n) stops being self-evidently negligible. Closing this needs a
before/after run of this repository's Bombardier bench CI job (or a
local equivalent) at or near that configuration; none has been produced
for this change. See the module's doc comment for the full note.
One pre-existing unit test, test_flow_control_window_settings_change_negative,
is removed rather than adapted: its docstring claimed to simulate a
SETTINGS_INITIAL_WINDOW_SIZE-driven connection-window shrink, but
update_initial_window_size only ever adjusts per-stream windows, never
the connection-level window this test constructed directly, so it never
exercised a real code path. A new h2_flow_control.rs test,
consume_send_window_saturates_at_i32_min_without_wrapping, does not
restore that coverage — it covers a different, previously-untested
boundary of consume_send_window (the saturating_sub floor at i32::MIN).
Re-anchored every mux/h2.rs and mux/mod.rs line citation in LIFECYCLE.md
and doc/testing.md that this diff shifted, by content, and updated
doc/h2_mux_internals.md's flow-control section (struct diagram, access
pattern, file table) and CHANGELOG.md in the same changeset.
Signed-off-by: Florentin Dubois <[email protected]>
Step 2 of the H2 sans-io extraction (#1339, #1336). Step 1 landed in #1403.
Connection-level HTTP/2 flow control (RFC 9113 §6.9) moves out of
ConnectionH2intolib/src/protocol/mux/h2_flow_control.rs, with private fields and a closedpub(super)API —the same shape
hpack_state.rsestablished in #1403.It also fixes a real nondeterminism defect on the way out.
The defect: WINDOW_UPDATE emission order was wire-observable and varied per process
pending_window_updateswas aHashMap, and the drain picked entries by iteration order. Whichstream gets unblocked first was therefore visible to the peer and different on every process, because
Rust's
RandomStateis per-process seeded. This is one of the order leaks #1338 decided to close.Proven, not argued — three runs of the same compiled test binary, three different wrong orders:
Fixed with
BTreeMap. The reasoning, since it will be cited later: aBTreeMapgives a total orderindependent of insertion history, which is a stronger guarantee than a seeded
HashMapand needsno seed threaded through construction and tests. It also makes every iteration deterministic rather
than only the drain, closing the door on a future non-drain iteration reintroducing the leak. And
ascending order happens to be protocol-friendly here: stream id
0sorts first, so theconnection-level update that unblocks every stream is always flushed first in a pass.
A fairness cursor was considered and deliberately not built.
max_pending_window_updatescaps thequeue at
1 + 4 × max_concurrent_streams(401 by default), each frame is 13 bytes, and the bufferfloor is enforced independently — so under the documented default a single drain empties the map and
the partial-drain starvation path is defensive dead code. That reasoning is in the module doc, flagged
to revisit if the cap/buffer coupling is ever loosened.
Transmit surface
drain_window_updates_into(&mut self, buf: &mut [u8]) -> (usize, usize)— the caller passeskawa.storage.space()and gets back bytes and frames written. No allocation, no owned bytes returned.This is the same shape
serializer::gen_window_updatealready has, which the method calls directly;sozu's manual ring-buffer management is preserved end to end.
Metrics stay in the
ConnectionH2caller rather than moving into the new module, mirroringUdpManager: the core stays side-effect-free beyond the buffer it is handed.Complexity, stated honestly
queue_window_updateis on the per-DATA-frame path andBTreeMapmakes it O(log n) against theprevious amortized O(1). At the default
max_concurrent_streamsof 100 (n ≤ 401) this is not expectedto be measurable, but it has not been benchmarked, before or after. An operator raising that
listener setting toward
MAX_SAFE_CONCURRENT_STREAMSreaches n ≈ 40,001. The module doc carries anexplicit
UNMEASUREDsection naming what would close it: a before/after run of this repository'sBombardier benchjob. No such run has been produced for this change.Scope, and why it is wider than the four named items
Making the three fields private forces every reader through the new API — send-window consumption in
write_streams, receive-byte accounting inhandle_data_frame, themin(stream, connection)comparisons, the
Debugimpl, gauges and log macros. A half-private struct would be an inconsistentseam, so the whole struct was closed. Each accessor is a faithful translation of what the call site
already did; a review traced all of them.
Explicitly not touched, because they are step 3: the per-stream arm of
handle_window_update_frameand
Stream.windowinstream.rs.git diffagainststream.rsis empty.A second behaviour change, named rather than buried
queue_window_updateno longer inserts a zero-increment entry for empty non-END_STREAM DATA frames.The CHANGELOG is precise about what this does and does not do, after an earlier revision of this
branch overclaimed it. It does not change the
h2.connection.pending_window_updatesgauge: thatgauge is sampled only from
gauge_connection_state, reached only throughwrite_streamson thewritable()path, andflush_pending_control_frames— which already stripped zero-increment entries —runs at the top of that same
writable()call. The gauge never observed a dead entry either way. Whatchanges is the map's state at rest, between the
readable()pass that used to insert and thewritable()pass that would have flushed, plus an invariant that now holds unconditionally instead ofonly by the time something looks.
Invariants
check_invariants()runs as a post-condition of every public mutating method, asUdpManagerdoes.One requirement had to be restated rather than written literally: asserting the window never exceeds
2^31 - 1is tautological on ani32, and clippy'sabsurd_extreme_comparisonsrejects it. Ratherthan
#[allow]it or drop the requirement, the RFC 9113 §6.9.1 ceiling is now checked where it isfalsifiable —
apply_window_update's overflow arm, in widenedi64arithmetic, asserting thatchecked_addrejected the increment because the true sum exceedsi32::MAX.windowis private andgrows only through that one method, so the ceiling is enforced on every path that can raise it.
Tests
11 in the new module, including the determinism regression above. One pre-existing test was removed,
not moved:
test_flow_control_window_settings_change_negativeclaimed to simulate aSETTINGS_INITIAL_WINDOW_SIZEreduction shrinking the connection window, butupdate_initial_window_sizeonly ever adjusts per-stream windows and never touchesflow_control.window— its premise was never real, so it covered nothing.Its replacement does not restore that coverage, and does not claim to. It covers a boundary the
adjacent test does not reach:
consume_send_windowusessaturating_sub, so a legal but pathologicalsequence (RFC 9113 §6.9.2 permits an arbitrarily negative window) clamps at
i32::MINrather thanwrapping the sign or aborting a debug build.
Documentation
64 citation groups in
LIFECYCLE.mdre-anchored, verified by content rather than arithmetic: everyold-line/new-line pair was compared byte-for-byte between the base and this head. A review re-ran that
comparison independently across 384 individual line citations with zero mismatches.
Validation
Refs #1336, #1338, #1339.