Skip to content

refactor(mux-h2): invert the write path into poll_write_target/handle_write - #1479

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-poll-write-target-a
Sep 24, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-poll-write-target-a

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

The control-flow half of the H2 write-path inversion, and the last large tranche of the sans-io extraction. write_streams + flush_stream_out become a poll_write_target / handle_write drive loop mirroring the landed read-side precedent. flush_stream_out and FlushOutcome are deleted from production — zero occurrences remain above the test module.

Behaviour-preserving. sozu-lib 1092, sozu 113, sozu-e2e 446, all with zero failures.

The shape

pub(super) fn poll_write_target<E, L>(&mut self, context: &mut Context<L>,
    endpoint: &mut E, pass: &mut H2WritePass) -> H2WriteTarget

fn handle_write<L>(&mut self, context: &mut Context<L>, stream_id: H2StreamId,
    size: usize, status: SocketResult, pass: &mut H2WritePass)

pub(super) enum H2WriteTarget {
    Done(MuxResult),
    Transmit { stream_id: H2StreamId },
    Finalize { socket_write: bool, bytes_written: usize },
}

Finalize carries bytes_written as well as socket_write, because finalize_write's second argument becomes made_progress and selects invariant-16 RetainPendingBack over Quiesce — and it is accumulated inside the loop, so only the pass knows it. Three sites end a pass without finalizing (the resume-path stall, the MadeYouReset cap trip, the close-frontend GOAWAY) and all three answer Done; folding any into Finalize would run invariant-16 policy on a pass that must not reach it.

The shell keeps io_slices and brackets gather / write / confirm in three adjacent statements, so the unsafe lifetime-extension window stays exactly as wide as before.

The trap this design is built around

update_readiness classifies a pass as stalled iff size == 0; status only clears the event bit. So size > 0 with SocketResult::WouldBlock is not a stall and the loop must go round again. A machine treating status != Continue as its terminator truncates responses on the hot path, and the natural reading of the code is the wrong one.

That is now structural rather than documented: SocketResult appears at exactly one production type site on the write core, handle_write's parameter. poll_write_target never sees it, so the pass-terminator mutation cannot be written there without first adding a parameter to its signature — a visible change, not a one-token edit.

The round-again is !pass.stalled && !kawa.out.is_empty() re-yielding Transmit for the same stream: the old while loop re-expressed as a resumption state.

Behaviour preservation, checked mechanically

A comment-stripped multiset comparison of the pre-image (write_streams + flush_stream_out) against the inverted form (write_streams + poll_write_target + begin_scheduler_pass + handle_write) leaves only expected re-spellings: field access, *flag = true → pass.socket_write = true, and while → the two resumption guards.

Specifically checked and preserved: socket_write raised only inside !kawa.out.is_empty() in the scheduler arm and never in the resume arm; stalled cleared at the top of Prepare; consumed/stream_bytes reset at the same relative positions; the missing-stream continue logging the same error! without calling priority(); debug_site 2 for resume and 3 for flush; cross_read_amount Some only in resume; and the End tail ordering including the cap trip returning between into_buffers and the put_* calls, dropping the buffers exactly as the pre-image does.

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

edit result
|| !matches!(status, SocketResult::Continue) on the stall assignment 3 failures, left: 5, right: 43 twice and 16384/32768
delete the scheduler arm's set_expect_write 1, a_stalled_stream_parks_expect_write_for_the_next_pass
delete the resume arm's Done(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

All six are now stated in terms the inverted tree actually contains, so each is executable verbatim.

Two defects found by competing implementation, not by testing

This slice was built twice in parallel with different answers to one contested question — how to carry converter, order and census across the poll/handle boundary, given none can be a pass-start field. An adversarial comparison of the two found, in this one:

  • A latent panic, reproduced. Re-polling after Finalize re-entered the End arm and expected on an already-released Option. Closed by a terminal H2WritePhase::Ended. release_scheduler_pass() has exactly one call site and pass.phase = Ended exactly one assignment, on adjacent lines, so no path releases without setting it and none sets it without releasing.
  • An ordering change this commit's own message had denied. Stream::state was being read after the round-again completed, where the pre-image reads it before the flush. Benign today — nothing between poll and handle mutates it, and borrowck enforces the kawa/state disjointness — but latent by accident. Now carried in the phase, read at the pre-image's position.

The same pass collapsed a duplicated scheduler.priority() lookup (one HashMap lookup per stream per pass) back to the pre-image's single read.

Why this shape over the alternative

The competing variant nested the scheduled state in an enum variant, reaching zero expect() sites against this one's six — a genuine reliability advantage. It was rejected on the project's first tie-breaker, performance: clippy::large_enum_variant forces that shape to Box its payload (256 vs 48 bytes, gap 208 over the 200 threshold), costing one 216-byte allocation per pass that reaches the scheduler.

The deciding measurement, which neither implementation took and which had to be instrumented: in a release build, a single-stream pass that writes nothing allocates zero times. The 36 bytes visible in debug are a #[cfg(debug_assertions)] format! inside finalize_write, shared by both and untouched here. So the alternative's Box would have been the only allocation on the common idle path.

A Drop tripwire retained from the comparison catches the one case ownership cannot: a future caller that abandons the drive loop after a Transmit yield.

Deliberate follow-ups, not in this commit

  • Pooling io_slices on ConnectionH2 — 64 bytes per transmitting pass, but it reopens the ownership question the design settled on purpose (the vector lives in the shell to keep the 'static descriptors' unsafe window as narrow as the gather/write/confirm triple) and would need its own shrink policy.
  • sort_unstable_by_key for the multi-stream scratch — trades one 24-byte allocation for O(n log n) prioriser.get lookups instead of O(n). A maintainer's call, not a refactor's.
  • The resume path's multi-round flush is unpinned: capping it at one round leaves the suite green. Confirmed inherited — the pre-image had one shared while loop serving both call sites, so a resume-only cap was not expressible. The inversion splits it into two independently editable guards, only one of which is pinned.

Citations

97 h2.rs:NNN citation instances sit on lines this commit rewrites — 83 arithmetic renumbers, 14 claim-level re-anchors across nine sites. Every renumber was derived from the text of the cited line, never by adding a delta.

An audit after the first pass found three breaks and a method failure worth naming: verifying each renumbering pass as base[old] == new[new'] catches an error that pass introduced, but silently re-tracks one inherited from the previous pass. Re-auditing against the original parent is what closes it. Two further passes then compared every changed citation (97) and every unchanged one against the original parent: one genuine arithmetic error, zero misses.

Refs #1454

…_write

`write_streams` becomes a drive loop over a `poll_write_target` /
`handle_write` core, the write-side mirror of the landed `poll_read_target`
/ `handle_read` pair, and `flush_stream_out` and `FlushOutcome` are deleted.
No condition, counter boundary or readiness decision moves.

One divergence from the read side is forced. A read pass performs exactly
one `socket_read`, so `readable()` is a two-call protocol that ends with
`handle_read`; a write pass performs an unbounded number of vectored writes
— the pre-image's `while !kawa.out.is_empty()` nested inside its walk of the
scheduler's order — so `write_streams` is a loop. It is now nothing but the
shell: it owns the `Vec<IoSlice<'static>>` and brackets `h2_transmit::gather`
/ `socket_write_vectored` / `h2_transmit::confirm` in three adjacent
statements, keeping that `unsafe` window exactly as wide as the pre-image's
loop body kept it. `write_buffer` is added as the exact mirror of
`read_buffer`, taking `zero` and `streams` apart rather than
`&mut ConnectionH2` and `&mut Context` so `ConnectionH2::socket` stays
borrowable while the gathered descriptors are live.

The one ORDERING question a poll/handle split raises is answered by
preserving the pre-image, not by re-deriving. `Stream::state` is read BEFORE
the flush — in `H2WritePhase::Start` and in `H2WritePhase::Prepare` — and
carried on the phase through the transmits rather than re-read after them.
Its consumer is `handle_1xx_reset`, which decides whether to re-arm
`Ready::READABLE` on the linked token, so a stream retired mid-flush must not
change which state that check sees. `H2Scheduler::priority` is carried for a
different reason: once per stream per pass is what the pre-image did, and
re-reading it in `Flush` would be a second `HashMap` lookup on the write hot
path.

`H2WriteTarget::Finalize` carries `bytes_written` as well as `socket_write`,
because `finalize_write` reads it as `made_progress` and that alone selects
`FinalizeAction::RetainPendingBack` over `Quiesce` (LIFECYCLE §9 invariant
16); it is accumulated stream by stream inside the loop, so only the pass
knows it. Three sites end a pass without finalizing and are `Done(MuxResult)`
— the resume path's stall, the MadeYouReset emitted-RST cap trip, and the
close-frontend GOAWAY — because folding any of them into `Finalize` would run
invariant 16's readiness policy over a pass that must not reach it.

`SocketResult` is confined to two places on the write core. `update_readiness`
returns stalled iff `size == 0`; the status only clears the WRITABLE event
bit, so `(size > 0, WouldBlock)` — which `FrontRustls` returns structurally
whenever rustls accepted plaintext while the kernel was full — is not a stall
and the flush must go round again or the response is truncated. The pass
terminator is `H2WritePass::stalled`, written by the single statement in
`handle_write` whose parameter is the type's only other appearance;
`poll_write_target` never sees a `SocketResult`, so keying the terminator on
the status there cannot be a one-token edit.

`H2WritePass` gains `H2WritePhase` and three late-initialised `Option`
fields. The `Prepare` / `Flush` split is load-bearing: a round-again re-enters
`Flush` and never `Prepare`, which keeps one pass to one `kawa.prepare` per
stream. The `H2ConverterPass`, the scheduler's loaned `order` buffer and its
`ReadyIncrementalCensus` cannot be built when the pass is — `begin_pass`
enumerates a map the resume path may have removed from, and the converter's
constructor `mem::take`s three scratch buffers out of `HpackState` that a
stalled resume would then drop — so they are adopted at the transition into
`Prepare` and released as the first statement of `End`. Six `expect` sites
share one message naming the invariant, three in `release_scheduler_pass` and
one in each of the three accessors, beside two `debug_assert!`.

Two ways that could go wrong, and both are closed. A caller that stops driving
after a `Transmit` would strand the converter's three pooled buffers:
`poll_write_target` has exactly one `return` between the adoption and the
first statement of `End`, which the shell's loop always answers, and
`H2WritePass`'s `Drop` carries the matching `debug_assert!`. A caller that
polls once MORE after the pass answered would re-enter `End`, whose first
statement takes three `Option`s it has already emptied; the terminal `Ended`
phase answers `Done(MuxResult::Continue)` instead. `write_streams` does
neither, but `poll_write_target` is `pub(super)` and `poll_read_target`
already has direct unit tests. The MadeYouReset cap trip still drops the three
buffers, because it returns between `into_buffers` and the `put_*` calls
exactly as the pre-image did.

`flush_stream_out` is deleted rather than left as a single-shot helper: a
vestigial one would keep its fixture tests green against a function production
no longer calls. No test is added, removed, renamed or ignored. The three
tests that drove it now drive `write_streams` directly over the same scripted
socket, through a test-module-local `FlushOutcome` derived from `kawa.out`
being empty — the pre-image's own loop-exit condition, and the same fact as
the tuple's `out_is_empty` element, which that type's doc now states rather
than hides. All six reddening recipes recorded on this region still redden the
same tests with the same `left:` / `right:` values.

`doc/h2_mux_internals.md`, `doc/architecture.md`, `doc/configure.md`,
`LIFECYCLE.md` and `CHANGELOG.md` follow the two deleted symbols and the moved
sites, and `doc/README.md` and `e2e/src/tests/h2_correctness_tests.rs` stop
naming `FlushOutcome::Stalled`, which no longer exists — `doc/README.md` used
it as the worked example of the symbol-citation convention, so a stale one
there would refute the rule it teaches.

80 `h2.rs:NNN` citation instances across the tree sit on lines this commit
writes — counting each `path:NNN` or `path:NNN-MMM` occurrence once, measured
off `git diff` rather than off the renumbering plan, and including
`CHANGELOG.md`, which the citation gate never reads. 68 are arithmetic; the
other 12, across eight sites, are re-anchored by CLAIM because the rewrite
moved what they name, and each was checked by reading the new line rather than
by trusting the offset. Every changed instance was then audited against the
base by exact line text, and every h2.rs citation the commit left alone was
checked to confirm its target had not moved: no misses. Citations in Rust
comments carry no line number at all, per `doc/README.md`'s convention, so the
ones in `e2e/src/tests/` name symbols and cannot drift. Five anchors are left
deliberately untouched although their targets moved: `h2_flood_detector.rs`'s
is scoped "at the pre-extraction revision", and four in `CHANGELOG.md` sit
inside a quoted resolver transcript. Renumbering a historical citation defeats
it; rewriting a transcript falsifies it.

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