Skip to content

refactor(mux-h2): extract connection-level flow control, and make WINDOW_UPDATE order deterministic - #1406

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-flow-control-b
Sep 22, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-flow-control-b

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

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 ConnectionH2 into
lib/src/protocol/mux/h2_flow_control.rs, with private fields and a closed pub(super) API —
the same shape hpack_state.rs established 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_updates was a HashMap, and the drain picked entries by iteration order. Which
stream gets unblocked first was therefore visible to the peer and different on every process, because
Rust's RandomState is 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:

[501, 2, 13, 8, 9, 45, 333, 7, 0, 21, ...]
[777, 5, 4, 111, 0, 8, 2, 21, ...]
[9, 45, 2, 777, 0, 3, 4, 13, ...]
expected ascending: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 13, ...]

Fixed with BTreeMap. The reasoning, since it will be cited later: a BTreeMap gives a total order
independent of insertion history, which is a stronger guarantee than a seeded HashMap and needs
no 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 0 sorts first, so the
connection-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_updates caps the
queue at 1 + 4 × max_concurrent_streams (401 by default), each frame is 13 bytes, and the buffer
floor 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 passes
kawa.storage.space() and gets back bytes and frames written. No allocation, no owned bytes returned.
This is the same shape serializer::gen_window_update already has, which the method calls directly;
sozu's manual ring-buffer management is preserved end to end.

Metrics stay in the ConnectionH2 caller rather than moving into the new module, mirroring
UdpManager: the core stays side-effect-free beyond the buffer it is handed.

Complexity, stated honestly

queue_window_update is on the per-DATA-frame path and BTreeMap makes it O(log n) against the
previous amortized O(1). At the default max_concurrent_streams of 100 (n ≤ 401) this is not expected
to be measurable, but it has not been benchmarked, before or after. An operator raising that
listener setting toward MAX_SAFE_CONCURRENT_STREAMS reaches n ≈ 40,001. The module doc carries an
explicit UNMEASURED section naming what would close it: a before/after run of this repository's
Bombardier bench job. 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 in handle_data_frame, the min(stream, connection)
comparisons, the Debug impl, gauges and log macros. A half-private struct would be an inconsistent
seam, 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_frame
and Stream.window in stream.rs. git diff against stream.rs is empty.

A second behaviour change, named rather than buried

queue_window_update no 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_updates gauge: that
gauge is sampled only from gauge_connection_state, reached only through write_streams on the
writable() path, and flush_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. What
changes is the map's state at rest, between the readable() pass that used to insert and the
writable() pass that would have flushed, plus an invariant that now holds unconditionally instead of
only by the time something looks.

Invariants

check_invariants() runs as a post-condition of every public mutating method, as UdpManager does.

One requirement had to be restated rather than written literally: asserting the window never exceeds
2^31 - 1 is tautological on an i32, and clippy's absurd_extreme_comparisons rejects it. Rather
than #[allow] it or drop the requirement, the RFC 9113 §6.9.1 ceiling is now checked where it is
falsifiable — apply_window_update's overflow arm, in widened i64 arithmetic, asserting that
checked_add rejected the increment because the true sum exceeds i32::MAX. window is private and
grows 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_negative claimed to simulate a
SETTINGS_INITIAL_WINDOW_SIZE reduction shrinking the connection window, but
update_initial_window_size only ever adjusts per-stream windows and never touches
flow_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_window uses saturating_sub, so a legal but pathological
sequence (RFC 9113 §6.9.2 permits an arbitrarily negative window) clamps at i32::MIN rather than
wrapping the sign or aborting a debug build.

Documentation

64 citation groups in LIFECYCLE.md re-anchored, verified by content rather than arithmetic: every
old-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

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

Refs #1336, #1338, #1339.

…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]>
@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator Author

msrv-bare red is a pre-existing flake, not a regression from this changeset

The failing step was Test sozu-e2e, and the failing test is
tests::tls_tests::test_tls_connection_close_large_response:

TLS-CONN-CLOSE-LARGE: FAIL - backend sent 0 responses, expected 1
Test not successful after: 3 iterations
thread '...' panicked at e2e/src/tests/tls_tests.rs:1242:5:
assertion `left == right` failed
  left: Fail
 right: Success
test result: FAILED. 437 passed; 1 failed; ... finished in 1435.28s

No code-path overlap. That test sets config.alpn_protocols = vec![b"http/1.1".to_vec()] and
sends GET /large HTTP/1.1. It never negotiates h2, so it never reaches ConnectionH2, h2.rs or
the new h2_flow_control.rs — the only files this changeset touches on the datapath. There is no
mechanism by which the BTreeMap ordering change or the zero-increment no-op could reach it.

Reproduction, both sides. Full suite on this branch with the exact msrv-bare invocation
(cargo +1.93.1 test -p sozu-e2e --locked, default features, no --all-features), twice:
442 passed; 0 failed in 446s and 443s. Then the failing test in isolation, three times on this
branch (c1d28c8e) and three times on the base (af4005a3, in a scratch worktree since removed) —
all six green. Seven local passes out of seven across both commits, which satisfies this repository's
three-isolated-runs rule on both sides.

The signature is a catalogued class. #1393 documented five CI failures across
tcp_sni_tests, hsts_tests, protocol_pair_matrix and h1_security_tests, each with the same
left: Fail / right: Success shape and the same "backend received 0 bytes" symptom, late in ~1400s
runs, spread across every crypto/feature cell rather than preferring one. This failure landed at
1435s into its run.

Why msrv-bare and not msrv-full is timing, not features. msrv-full adds
opentelemetry,splice,simd, none of which touch the H1-over-TLS backend-connect path. The two cells
are separate concurrent jobs on separate runners; #1393's catalogue already shows this signature
recurring across cells without preference, which is runner contention rather than a feature gate.

Two findings worth keeping, independent of this PR

repeat_until_error_or is a stability check, not a retry. Reading e2e/src/tests/mod.rs, it
loops while iterations succeed and returns Fail on the first failing one. So
repeat_until_error_or(5, …) demands five consecutive clean worker and backend spin-ups and fails
the whole test on any single bad trial. That makes every test using it structurally about five times
more exposed to a rare per-trial race than its name suggests — this run died on the third iteration,
the first two having passed silently. Worth knowing before reading any future failure of this shape.

The diagnostic added in #1395 paid off on this test's first ever failure. That changeset hardened
test_tls_connection_close_large_response to name its failing conjunct and distinguish truncation
from corruption, explicitly because it carried the same bare assert_eq!(…, State::Success) shape
that had made every failure in #1393 cost a log-archaeology session — and noted at the time that the
test had never failed. It has now, and instead of a bare Fail, the log says
backend sent 0 responses, expected 1, which is what made this diagnosis quick.

I have re-run the failed job. A green rerun would be consistent with the above but is not proof of
flakiness on its own — #1393 recorded one case that failed twice then passed on re-run and another
that failed thirteen consecutive iterations, i.e. deterministic under that load condition. The
evidence here is the seven local passes and the absent code path, not the rerun.

No change is proposed to this PR. Hardening that test is a separate pre-existing task.

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