Repository navigation
refactor(mux-h2): move the write pass's locals onto an H2WritePass - #1477
Merged
Merged
Conversation
`write_streams` builds its pass state as nine `let` bindings between `arm_timeout()` and the `'outer` loop, and the control-flow inversion that follows — a `poll` that names the next transmit, a shell that performs it, a `handle` that reports it back, the shape `poll_read_target` / `handle_read` already gave the read path — needs every one of them to survive a round trip through the caller. This commit moves them and does nothing else, so the diff a reviewer has to check by eye is "locals became fields": not a condition, not an ordering, not the `saturating_add` boundary at the pass total. The nine are `byte_totals`, the last flush's `stalled` verdict, `resume_bytes`, `completed_streams`, `socket_write`, `total_bytes_written`, `freshly_emitted_rsts`, and the per-iteration `consumed` and `stream_bytes`. Each `let` becomes a field initialised in `H2WritePass::new`; the two per-iteration ones become an assignment at the same statement their `let` occupied, so they are still reset once per stream. The comments that documented those bindings move with them and are now field docs. `H2WritePass` is a local threaded by `&mut`, not an `Option<H2WritePass>` on `ConnectionH2`. Every exit of `write_streams` ends the pass — the resume-path stall's `return MuxResult::Continue`, the MadeYouReset cap trip's `return result`, the close-frontend GOAWAY's `return`, and the tail's `self.finalize_write(..)` — and the stalled-stream `break 'outer` falls through to that tail, so the struct cannot outlive one call. Resumption ACROSS calls is already `H2StreamTable::expect_write`. An `Option` field would invent a "None between calls" invariant with no read-side pre-image and would need its own test. `resume_bytes` stays a SEPARATE counter from `total_bytes_written`. The resume path's bytes never reach `finalize_write`, and that is behaviour rather than oversight: a resume-only pass must not read as progress, or `h2_close::finalize_action` retains `Ready::WRITABLE` for a scheduler pass that did nothing and the next tick finds the same nothing. Three values one pass uses stay locals, for two measurable reasons rather than one. The scheduler's loaned `order` buffer and its `ReadyIncrementalCensus` are built AFTER the `expect_write` resume path has run, and that path can retire a stream through `remove_dead_stream` that `H2Scheduler::begin_pass` then does not enumerate, so constructing them at pass start would change which streams the pass visits. That argument cannot apply to `H2ConverterPass`, which enumerates no streams; its reason is buffer stranding. Its constructor `mem::take`s the three reusable scratch buffers out of `HpackState`, and only `into_buffers` (`h2.rs:2640`) followed by `put_converter_buf` / `put_lowercase_buf` / `put_cookie_buf` (`:2655-2657`) hands them back — all after the per-stream loop, while the resume path's stall returns at `:2267` — so a pass-start converter would be dropped on every stalled resume and leave `HpackState` holding three empty `Vec`s to re-grow, discarding the reuse the pass exists to provide on exactly the backpressure path that repeats most. Keeping any of the three as a field without constructing it at pass start needs `Option` and eleven `expect()` sites in the per-stream loop, or a placeholder `ReadyIncrementalCensus` that the type has no `Default` for. Both are more than "a local became a field". The `Vec<IoSlice<'static>>` is a fourth pass-start local left where it is, and it is excluded by design rather than necessity: it is built at `h2.rs:2215`, BEFORE the resume path, and lent to it. `h2_transmit::gather` returns descriptors carrying a `'static` lifetime they do not have, pointing into `kawa.storage`, and `h2_transmit::confirm` must discharge them before the consume that may relocate it. Leaving the vector with the caller keeps that `unsafe` window exactly as wide as the gather/write/confirm triple that opens and closes it, and stops a later poll/handle boundary from spanning it. The `Prepare` / `Flush` phase marker the inversion needs is not introduced either. With the loop unchanged, `Flush` and `End` have no construction site and `phase` has no reader, and `-D warnings` rejects that: measured, `error: variants `Flush` and `End` are never constructed`. The alternatives are a lint-allow or new logic to read the marker, and neither belongs in a commit whose whole value is that it moved no logic. No test was added, removed, ignored or altered, and the suite holds its count. All six reddening recipes this commit's parent recorded on this region were re-run against the field form and redden the same tests with the same values: `|| !matches!(status, SocketResult::Continue)` on the stall test gives 1086 passed / 3 failed, `left: 5, right: 43`; deleting the main loop's `set_expect_write` and deleting the resume path's `return MuxResult::Continue` each give 1088 / 1; `order.iter().chain(order.iter())` gives `left: 65535, right: 32768`. Two recipes take a new spelling and their `TO SEE THIS RED` comments were updated to it: the resume fold is now `write_pass.total_bytes_written = write_pass.resume_bytes;` before the `'outer` loop (the hoist half became structural once `resume_bytes` is a field), giving `left: Writable | Error | Hup, right: Error | Hup`, and the accumulation edit is now `write_pass.total_bytes_written = write_pass.stream_bytes;`, giving `left: Error | Hup, right: Writable | Error | Hup`. Moving the pass state renumbers `h2.rs` and `mux/mod.rs`, and the offset is NOT a single delta -- do not apply one as a rule. Measured with difflib opcodes against the parent, `h2.rs` runs +1, 0, -1, -15, -17, -15, -13, -11 and -6 across base 2214-2701, then -2 for base 2703-8299, then 0 from base 8305 down, because the two test doc-comment edits add back exactly the two lines the extraction removed; `h2.rs` is 11596 lines at both revisions. `mux/mod.rs` is +1 for base 151 onward. 80 citations are re-anchored: 71 on the surface `check_doc_citations.py` reads (`LIFECYCLE.md`, `doc/h2_mux_internals.md`, `doc/testing.md`) and 9 line numbers it does not (`CHANGELOG.md`'s `[Unreleased]` `FinalizeAction` entry, and three `mux/mod.rs` ranges in `e2e/src/tests/h2_priority_rearm_tests.rs`). EVERY new number was derived from the cited line's TEXT at the parent rather than by adding an offset, which is what #1473 got wrong; the one citation whose text this commit changed, `LIFECYCLE.md`'s outbound-byte refresh range, was re-pointed by hand at the same three lines. `check_doc_citations.py` is green on both `--root .` and `--base 1e414ed`, and a whole-tree sweep under the same rule-2 semantics leaves no ungated citation that was textually exact at the parent still pointing at moved text. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 23, 2026 19:12
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.
The state-extraction half of the H2 write-path inversion. Pure refactor, no behaviour change: nine locals in
write_streamsbecome fields on a newH2WritePassinlib/src/protocol/mux/h2_write_pass.rs. The loop is untouched — no control flow moves, no signature changes, no condition or ordering differs.It exists as its own commit so the inversion that follows is reviewable by eye: this diff is "locals became fields", and the next one is a pure control-flow change over a field set already reviewed.
The nine fields
byte_totals,stalled,resume_bytes,completed_streams,socket_write,total_bytes_written,freshly_emitted_rsts,consumed,stream_bytes— each aletin the pre-image, with its comment moved to the field doc.H2WritePassis a local threaded by&mut, not anOption<H2WritePass>onConnectionH2. Every exit ofwrite_streamsends the pass andbreak 'outerfalls through to the tail, so the pass never outlives one call; cross-call resumption is alreadystream_table.expect_write(). A field would invent a "None between calls" invariant with no analogue in the landed read-side precedent.Three fields that cannot be pass fields, and why that matters
converter,orderandcensuswere in the design and are not here. Two different reasons, both measured:order/census— the resume path can reachremove_dead_stream→stream_table.remove, andbegin_passenumeratesstream_table.streams().keys(). Same map. Building them at pass start changes which streams the pass visits, which is a behaviour change, not an inconvenience. (ReadyIncrementalCensusalso carries no#[derive]at all, so noDefaultexists for a placeholder.)converter— this one is not about enumeration;H2ConverterPassenumerates nothing. It is buffer stranding: the constructor's argumentsmem::takethree scratch buffers out ofHpackState, and onlyinto_buffersplus the threeput_*calls hand them back — all after the loop. The resume-path stall returns before both, so a pass-start converter would be dropped on every stalled resume andHpackStatewould permanently lose its pooled buffers, re-growing from empty on every subsequent pass.The phase marker is deferred for a third reason: with the loop unchanged, its
FlushandEndvariants have no construction site andclippy -D warningsrejectsvariants Flush and End are never constructed.These three are exactly the state the inversion must carry across the poll/handle boundary, so it inherits a late-init problem — better learned from a 171-line refactor than from a thousand-line one.
Proving no behaviour changed
Normalising both function bodies (strip comments, collapse whitespace, strip the
write_pass.prefix) and diffing at character level leaves 23 residual hunks, every one either aletremoval or the== FlushOutcome::Stalledrelocation from read-site to write-site. Noif,else,return,break,continue,match,saturating_add, operator or ordering token differs.The one place a field genuinely gains lifetime across iterations is the pre-image's two distinct
outcomelocals collapsing into onestalledfield. It is safe: assigned then read within each of the two regions, the loop's onlycontinueprecedes both, nothing between the second assignment and its read touches it, and with an emptyorderit is never read after the loop.All six mutation recipes on this region still redden the same tests with the same values:
!matches!(status, SocketResult::Continue)left: 5, right: 43set_expect_writea_stalled_stream_parks_expect_write_for_the_next_passreturn MuxResult::Continuea_stalled_resume_does_not_begin_a_scheduler_passtotal_bytes_writtenfromresume_bytesresume_path_bytes_do_not_make_the_pass_progressorder.iter().chain(order.iter())a_yielded_incremental_stream_is_prepared_once_per_pass,65535/32768total_bytes_written = stream_bytesa_later_zero_byte_stream_does_not_erase_the_pass_progressTwo recipes needed re-expressing because their literal text no longer exists as a local; both inject the same defect and reproduce the same
left/right.#[test]count is 1097 onmainand 1097 here;#[ignore]is 0 on both.sozu-lib1092,sozu113.Citations
71 re-anchored: ~38 into
h2.rsand ~33 intomux/mod.rs, which shifts by +1 from registering the ninthh2_*module. Every new number was derived from the text of the cited line via equal-block mapping, never by adding a delta — that distinction is the whole point, since the stated shift is not uniform (offsets run +1 to −17 inside one region, −2 in another, and 0 below a third boundary, because two doc-comment edits grow by exactly 2 and cancel).The one citation whose text this change did alter (
if stream_bytes > 0 {→if write_pass.stream_bytes > 0 {) was re-pointed by hand and its three lines read by eye.The sweep deliberately went beyond the CI gate's surface.
.github/scripts/check_doc_citations.pyreads onlydoc/**and**/LIFECYCLE.md, so livefile:linecitations inCHANGELOG.mdande2e/src/tests/*.rsdrift with no signal — which is how #1473 happened. Nine such citations were found stale here and fixed, including one case where the same source line had been re-anchored inLIFECYCLE.mdand left behind in two copies inh2_priority_rearm_tests.rs.Rebase note
This branch was rebased with
git rebase --onto 19fd5d8c dfa3fa2aafter its parent squash-merged as #1475.git range-diffagainst the pre-rebase reviewed tip reports=, and six of the eight files are blob-identical to it.Refs #1454