Skip to content

refactor(mux-h2): lift the two H2 byte movers into a socket shell - #1511

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-lift-byte-movers
Sep 24, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-lift-byte-movers

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Part of the H2 sans-io extraction, issue #1339 Q10. Rebased onto d4f6d070 (#1513), after #1512 (S4) and #1510.

What moves

ConnectionH2::readable and ConnectionH2::write_streams — the only production code on the H2
stream read and write paths that touches self.socket — move into a dedicated
impl<Front: SocketHandler> ConnectionH2<Front> block, the last one in h2.rs before
#[cfg(test)] mod tests, holding those two functions and nothing else.

Behaviour-preserving, measured against d4f6d070 rather than asserted. readable's body is
byte-identical to its pre-image (32 lines). write_streams's body (66 → 72 lines) differs in
exactly two places, both shown by a mechanical diff: the unsafe { … } wrapper around the gather
call with its // SAFETY: comment, and the removal of one comment line that the outer block makes
untrue. An inherent impl is order-independent, so no condition, ordering, counter or readiness
decision changed.

Reconciliation with the three PRs that landed first

  • refactor(mux-h2): split finalize_write and flush_pending_control_frames at their flush points #1512 (S4) split finalize_write into finalize_write(…) -> H2FinalizeTarget plus
    finalize_write_after_flush. The merged write_streams is S4's body in the new location:
    its query / flush / query triple travels into the shell block unchanged. That step is a socket
    touch too, and the shell block's doc says why it belongs on the same side of the split as the
    vectored write. H2FinalizeTarget and H2ControlFlushTarget stay pub(super) — they appear
    only in private signatures, so private_interfaces does not reach them.
  • fix(mux): capture listener configuration per request, not per connection #1513 changed three lines of h2.rs (context.protocol, stream.answers.clone(), and a
    test_answers() argument inside mod tests). All three are present and the pre-images are gone
    — verified by grep after the auto-merge, not assumed from it.

What becomes public

poll_read_target, handle_read, poll_write_target and handle_write become pub. Four types
follow because private_interfaces makes them follow, not by choice — H2ReadTarget,
H2ReadOutcome, H2WriteTarget and H2WritePass appear in those signatures. All four are
re-exported from protocol::mux beside H2StreamId, because a pub method whose argument type
cannot be named out of crate is not callable out of crate either.

h2_transmit is exported asymmetrically, and that is the point

mod h2_transmit becomes pub mod, gather becomes a pub unsafe fn, and confirm a
plain pub fn
.

gather could not be a plain pub fn. It pushes IoSlice<'static> borrowed out of its
&Kawa<T> argument, so this is undefined behaviour from out-of-crate code with no unsafe written
anywhere in it:

let mut v: Vec<IoSlice<'static>> = Vec::new();
{ let k = make_kawa(); gather(&k, &mut v); }   // k dropped
let _ = v[0][0];                               // use-after-free

kawa is a published crate, so not one Sōzu internal is needed to reach it. A 'static in a safe
signature does not merely fail to state the obligation — it denies there is one. unsafe in the
signature puts the lifetime obligation on the caller, and the # Safety section names both halves:
kawa must not be dropped or mutated while a descriptor is readable, and io_slices must be
emptied before that first mutation.

confirm is deliberately not unsafe, and the asymmetry is argued rather than assumed. It
produces no descriptor; it only destroys them, and destroying them is well defined even when they
already dangle — Vec::clear drops IoSlice values, and an IoSlice is a pointer and a length
with no Drop that dereferences. Everything after the clear is Kawa::consume, a safe kawa API
where too large a size is a truncation bug rather than undefined behaviour. So it leaves its
caller no obligation, and unsafe on it would be decoration that blunts what unsafe means at the
one call site where it means "a lifetime is being asserted here".

The unsafe windows, re-stated at the rebased line numbers

  • Inner, unchanged: h2_transmit.rs:161 — gather's unsafe { std::slice::from_raw_parts(…) },
    opening and closing inside that function.
  • Outer: h2.rs:6998 — the unsafe { … } the pub unsafe fn forces into write_streams. It
    wraps the gather call and nothing else — not the vectored write, not the confirm. It is
    the only unsafe block in h2.rs production code (verified by counting above mod tests).
shell impl opens h2.rs:6842
private fn write_streams h2.rs:6938
vector declared h2.rs:6952 — let mut io_slices: Vec<IoSlice<'static>> = Vec::new();
opens h2.rs:6998 — unsafe { h2_transmit::gather(kawa, &mut io_slices) }
only statement between h2.rs:6999 — socket_write_vectored(&io_slices), a reborrow that cannot retain them
closes h2.rs:7004 — confirm(…), whose io_slices.clear() (h2_transmit.rs:219) precedes kawa.consume (:224)

Both bracket ends are statements of the private write_streams. The vector moved with the
loop. No IoSlice<'static> survives one loop iteration. The bracket still does not span the
poll/handle seam — which matters more now that the seam is pub; write_streams stays private for
that reason. The five in-module test call sites of gather each carry a tight unsafe { … } with
its own // SAFETY: line.

Still not drivable from out of crate

Two gaps remain, neither in this step's scope: the buffers both protocols name are reached through
the private read_space / write_buffer over the private ConnectionH2::zero, and H2WritePass
has no reachable constructor. sim/tests/h2_simulation.rs keeps driving readable / writable
over its own in-memory SocketHandler, and its header names those two gaps.

Documentation

Two doc comments claiming poll_write_target is pub(super) — in h2_write_pass.rs's
H2WritePhase::Ended and in the matching arm of poll_write_target itself — are corrected, since
it no longer is.

Intra-doc links in newly-public documentation are demoted to plain backticks, because
private_intra_doc_links under RUSTDOCFLAGS="-D warnings" rejects a link from public
documentation to a private item. Every one still names its symbol, so no citation became a line.

Sixty-one line citations are re-anchored onto the text they already named: 30 into h2.rs,
which this lift shifts by 159 lines, and 31 into mod.rs, which the two-line re-export shifts
by two. #1513's own h2.rs change moves none of them — its insertion sits inside mod tests, and
the highest h2.rs line cited anywhere in the guarded prose is 6857 while mod tests begins at
7013. The map was re-derived by content from d4f6d070 (not composed with the previous one,
not rebased textually), then all 87 re-anchored line ends were checked on both keys —
byte-identical text and identically-named enclosing fn — 0 failures on each. The
--audit finding set is unchanged from d4f6d070: seven findings before, the same seven after,
three merely at re-anchored numbers.

CHANGELOG does not conflict: #1513 placed its entry below the section head. The three entries at
the top of ### 🔄 Changed are newest-first by landing order.

Verification

All run at 85d617f1, each exit code read directly, cargo build before cargo fmt --check:

command exit
cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd 0
cargo +nightly fmt --all -- --check 0
cargo clippy --all-targets --locked <same flags> -- -D warnings 0
cargo test -p sozu-lib --locked <same flags> 0 — 1117 passed, 0 failed
cargo test -p sozu --locked <same flags> 0 — 113 passed, 0 failed
cargo test -p sozu-e2e --locked <same flags> -- --skip tests::fuzz_tests:: 0 — 447 passed, 0 failed
RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked 0 — 30 passed, 0 failed
RUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets --locked -- -D warnings 0
python3 .github/scripts/check_doc_citations.py --root . 0
python3 .github/scripts/check_doc_citations.py --base d4f6d070129ed31e50fe65579057183af4342881 0
python3 .github/scripts/check_doc_citations.py --audit --root . 0 (advisory)
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked 0
cargo bench -p sozu-lib --bench h2_stream_table -- --test 0

The sozu-e2e run started at 1-minute loadavg 1.54 with zero sozu_e2e processes already running,
and produced zero Connection refused lines.

`ConnectionH2::readable` and `ConnectionH2::write_streams` -- the only
production code on the H2 stream read and write paths that touches
`self.socket` -- move into a dedicated
`impl<Front: SocketHandler> ConnectionH2<Front>` block, the last one in
`h2.rs` before `#[cfg(test)] mod tests`, holding those two functions and
nothing else. Both bodies move statement for statement: `readable` is
byte-identical to its pre-image, and `write_streams` differs only by the
`unsafe { ... }` described below. An inherent impl is order-independent,
so this is behaviour-preserving -- no condition, ordering, counter or
readiness decision changed. What moves is where two `self.socket`
expressions sit, so the socket coupling still owed on this path is
countable by reading one region instead of grepping the file.

The query / flush / query triple that #1512 moved out of `finalize_write`
travels into the shell block with `write_streams`, unchanged: the
`tls_wants_write` query, the `H2FinalizeTarget` match that performs
`flush_tls_records` for `Flush` and not for `SkipFlush`, the second query
and `finalize_write_after_flush`. That step is a socket touch too and
belongs on the same side of the split as the vectored write.
`H2FinalizeTarget` and `H2ControlFlushTarget` stay `pub(super)`: they
appear only in the signatures of private functions.

`poll_read_target`, `handle_read`, `poll_write_target` and `handle_write`
become `pub`. Four types follow because `private_interfaces` makes them
follow, not by choice: `H2ReadTarget`, `H2ReadOutcome`, `H2WriteTarget`
and `H2WritePass` appear in those signatures. All four are re-exported
from `protocol::mux` beside `H2StreamId`, because a `pub` method whose
argument type cannot be named out of crate is not callable out of crate
either.

`h2_transmit` is exported asymmetrically. `mod h2_transmit` becomes `pub
mod`, `gather` becomes a `pub unsafe fn` and `confirm` a plain `pub fn`.
`gather` could not be a plain `pub fn`: it pushes `IoSlice<'static>`
borrowed out of its `&Kawa<T>` argument, so three lines of safe
out-of-crate code -- call `gather`, drop the `Kawa`, read the first
descriptor -- would be undefined behaviour with no `unsafe` written
anywhere in them, and `kawa` is a published crate, so no Sozu internal is
needed to reach it. A `'static` in a safe signature does not merely fail
to state the obligation, it denies there is one. `unsafe` in the
signature puts that obligation on the caller, and a `# Safety` section
names both halves: `kawa` must not be dropped or mutated while a
descriptor is readable, and `io_slices` must be emptied before that first
mutation.

`confirm` is deliberately NOT `unsafe`. It produces no descriptor and
only destroys them, which is well defined even when they already dangle:
`Vec::clear` drops `IoSlice` values, and an `IoSlice` is a pointer and a
length with no `Drop` that dereferences. Everything after the clear is
`Kawa::consume`, a safe `kawa` API where too large a `size` is a
truncation bug rather than undefined behaviour. So it leaves its caller
no obligation, and `unsafe` on it would be decoration that blunts what
`unsafe` means at the one call site where it means "a lifetime is being
asserted here".

There are two `unsafe` blocks on this path. The inner one is unchanged:
`gather`'s `slice::from_raw_parts`, opening and closing inside that
function. The outer one is the `unsafe { ... }` the `pub unsafe fn`
forces into `write_streams`, and it wraps the `gather` call and nothing
else -- not the vectored write, not the `confirm`. It is the only
`unsafe` keyword in `h2.rs` production code. The window they guard is the
same one and did not widen: it opens at that `gather` call, closes at the
`confirm` three statements later where `io_slices.clear()` runs before
the consume that may relocate `kawa.storage`, and the only thing entered
in between is the `socket_write_vectored` that reborrows the descriptors
and cannot retain them. No `IoSlice<'static>` survives one loop
iteration. The bracket still does not span the poll/handle seam, which
matters more now that the seam is `pub`; `write_streams` stays private
for that reason.

Out-of-crate driving is still not possible and nothing here claims it is:
the buffers both protocols name are reached through the private
`read_space` / `write_buffer` over the private `ConnectionH2::zero`, and
`H2WritePass` has no reachable constructor. `sim/tests/h2_simulation.rs`
keeps driving `readable` / `writable` over its own in-memory
`SocketHandler` and names those two gaps.

Two doc comments claiming `poll_write_target` is `pub(super)` -- in
`h2_write_pass.rs`'s `H2WritePhase::Ended` and in the matching arm of
`poll_write_target` itself -- are corrected, since it no longer is.

Intra-doc links in newly-public documentation are demoted to plain
backticks, because `private_intra_doc_links` under
`RUSTDOCFLAGS="-D warnings"` rejects a link from public documentation to
a private item. Every one still names its symbol. Sixty-one line
citations in `doc/h2_mux_internals.md`, `doc/testing.md` and
`LIFECYCLE.md` are re-anchored onto the text they already named: 30 into
`h2.rs`, which this lift shifts by 159 lines, and 31 into `mod.rs`,
which the two-line re-export shifts by two. #1513's own `h2.rs` change
moves none of them -- its insertion sits inside `mod tests`, and the
highest `h2.rs` line cited anywhere in the guarded prose is 6857 while
`mod tests` begins at 7013. All 87 re-anchored line ends were checked to
name byte-identical text inside an identically-named enclosing `fn` at
`d4f6d070`.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the refactor/h2-lift-byte-movers branch from e8c9874 to 85d617f Compare September 24, 2026 22:00
@FlorentinDUBOIS
FlorentinDUBOIS merged commit c5c8090 into main Sep 24, 2026
27 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the refactor/h2-lift-byte-movers branch September 24, 2026 22:50
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