Repository navigation
refactor(mux-h2): invert the write path into poll_write_target/handle_write - #1479
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 23, 2026 20:42
This was referenced Sep 23, 2026
FlorentinDUBOIS
force-pushed
the
refactor/h2-poll-write-target-a
branch
from
September 23, 2026 22:58
228d95c to
98745bb
Compare
…_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]>
FlorentinDUBOIS
force-pushed
the
refactor/h2-poll-write-target-a
branch
from
September 24, 2026 00:22
98745bb to
2252c6b
Compare
This was referenced Sep 24, 2026
ci(doc): forbid a file.rs:NNN citation in a Rust comment, and convert the live ones to symbols
#1493
Merged
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 control-flow half of the H2 write-path inversion, and the last large tranche of the sans-io extraction.
write_streams+flush_stream_outbecome apoll_write_target/handle_writedrive loop mirroring the landed read-side precedent.flush_stream_outandFlushOutcomeare deleted from production — zero occurrences remain above the test module.Behaviour-preserving.
sozu-lib1092,sozu113,sozu-e2e446, all with zero failures.The shape
Finalizecarriesbytes_writtenas well assocket_write, becausefinalize_write's second argument becomesmade_progressand selects invariant-16RetainPendingBackoverQuiesce— 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 answerDone; folding any intoFinalizewould run invariant-16 policy on a pass that must not reach it.The shell keeps
io_slicesand brackets gather / write / confirm in three adjacent statements, so theunsafelifetime-extension window stays exactly as wide as before.The trap this design is built around
update_readinessclassifies a pass as stalled iffsize == 0;statusonly clears the event bit. Sosize > 0withSocketResult::WouldBlockis not a stall and the loop must go round again. A machine treatingstatus != Continueas 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:
SocketResultappears at exactly one production type site on the write core,handle_write's parameter.poll_write_targetnever 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-yieldingTransmitfor the same stream: the oldwhileloop 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, andwhile→ the two resumption guards.Specifically checked and preserved:
socket_writeraised only inside!kawa.out.is_empty()in the scheduler arm and never in the resume arm;stalledcleared at the top ofPrepare;consumed/stream_bytesreset at the same relative positions; the missing-streamcontinuelogging the sameerror!without callingpriority();debug_site2 for resume and 3 for flush;cross_read_amountSomeonly in resume; and theEndtail ordering including the cap trip returning betweeninto_buffersand theput_*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:
|| !matches!(status, SocketResult::Continue)on the stall assignmentleft: 5, right: 43twice and16384/32768set_expect_writea_stalled_stream_parks_expect_write_for_the_next_passDone(MuxResult::Continue)a_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_progressAll 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,orderandcensusacross the poll/handle boundary, given none can be a pass-start field. An adversarial comparison of the two found, in this one:Finalizere-entered theEndarm andexpected on an already-releasedOption. Closed by a terminalH2WritePhase::Ended.release_scheduler_pass()has exactly one call site andpass.phase = Endedexactly one assignment, on adjacent lines, so no path releases without setting it and none sets it without releasing.Stream::statewas 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 thekawa/statedisjointness — 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 (oneHashMaplookup 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_variantforces that shape toBoxits 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!insidefinalize_write, shared by both and untouched here. So the alternative'sBoxwould have been the only allocation on the common idle path.A
Droptripwire retained from the comparison catches the one case ownership cannot: a future caller that abandons the drive loop after aTransmityield.Deliberate follow-ups, not in this commit
io_slicesonConnectionH2— 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'staticdescriptors'unsafewindow as narrow as the gather/write/confirm triple) and would need its own shrink policy.sort_unstable_by_keyfor the multi-stream scratch — trades one 24-byte allocation for O(n log n)prioriser.getlookups instead of O(n). A maintainer's call, not a refactor's.whileloop 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:NNNcitation 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