Skip to content

refactor(mux-h2): move the write pass's locals onto an H2WritePass - #1477

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-write-pass-state
Sep 23, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-write-pass-state

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

The state-extraction half of the H2 write-path inversion. Pure refactor, no behaviour change: nine locals in write_streams become fields on a new H2WritePass in lib/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 a let in the pre-image, with its comment moved to the field doc.

H2WritePass is a local threaded by &mut, not an Option<H2WritePass> on ConnectionH2. Every exit of write_streams ends the pass and break 'outer falls through to the tail, so the pass never outlives one call; cross-call resumption is already stream_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, order and census were in the design and are not here. Two different reasons, both measured:

  • order / census — the resume path can reach remove_dead_stream → stream_table.remove, and begin_pass enumerates stream_table.streams().keys(). Same map. Building them at pass start changes which streams the pass visits, which is a behaviour change, not an inconvenience. (ReadyIncrementalCensus also carries no #[derive] at all, so no Default exists for a placeholder.)
  • converter — this one is not about enumeration; H2ConverterPass enumerates nothing. It is buffer stranding: the constructor's arguments mem::take three scratch buffers out of HpackState, and only into_buffers plus the three put_* 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 and HpackState would 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 Flush and End variants have no construction site and clippy -D warnings rejects variants 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 a let removal or the == FlushOutcome::Stalled relocation from read-site to write-site. No if, 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 outcome locals collapsing into one stalled field. It is safe: assigned then read within each of the two regions, the loop's only continue precedes both, nothing between the second assignment and its read touches it, and with an empty order it is never read after the loop.

All six mutation recipes on this region still redden the same tests with the same values:

edit result
terminate the pass on !matches!(status, SocketResult::Continue) 3 failures, left: 5, right: 43
delete the main loop's set_expect_write 1, a_stalled_stream_parks_expect_write_for_the_next_pass
delete the resume path's return MuxResult::Continue 1, a_stalled_resume_does_not_begin_a_scheduler_pass
seed total_bytes_written from resume_bytes 1, resume_path_bytes_do_not_make_the_pass_progress
order.iter().chain(order.iter()) 1, a_yielded_incremental_stream_is_prepared_once_per_pass, 65535/32768
total_bytes_written = stream_bytes 1, a_later_zero_byte_stream_does_not_erase_the_pass_progress

Two 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 on main and 1097 here; #[ignore] is 0 on both. sozu-lib 1092, sozu 113.

Citations

71 re-anchored: ~38 into h2.rs and ~33 into mux/mod.rs, which shifts by +1 from registering the ninth h2_* 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.py reads only doc/** and **/LIFECYCLE.md, so live file:line citations in CHANGELOG.md and e2e/src/tests/*.rs drift 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 in LIFECYCLE.md and left behind in two copies in h2_priority_rearm_tests.rs.

Rebase note

This branch was rebased with git rebase --onto 19fd5d8c dfa3fa2a after its parent squash-merged as #1475. git range-diff against the pre-rebase reviewed tip reports =, and six of the eight files are blob-identical to it.

Refs #1454

`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
FlorentinDUBOIS merged commit 04fade6 into main Sep 23, 2026
43 of 44 checks passed
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