Skip to content

refactor(mux-h2): drop the Front type parameter from ConnectionH2 - #1471

Merged
FlorentinDUBOIS merged 8 commits into
mainfrom
refactor/h2-poll-transmit
Sep 23, 2026
Merged

FlorentinDUBOIS merged 8 commits into
mainfrom
refactor/h2-poll-transmit

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Step 9 of the H2 sans-io extraction: ConnectionH2 stops reaching for its Front socket, so the
connection core can be driven without one. Eight commits, reviewable in order.

what it does
9.1 read the log prefix peer from a connection-owned snapshot
9.2 extract the queued RST_STREAM state into h2_control_tx.rs
9.3 split the per-stream vectored write into gather/confirm (h2_transmit.rs)
9.4 hand the Endpoint trait an RTT value, not a peer socket
9.5 extract the TLS-backpressure close decision into h2_close.rs
9.6a invert the H2 read into poll_read_target/handle_read
9.6b decide the end of a write pass in h2_close::finalize_action
fix H2ControlTx::lifetime_cap_reached reads the instance bound, not the constant

Front touch points in h2.rs go from 140 to 27 — 113 of them were the peer= slot of
log_context!, which 9.1 reads from a snapshot instead. That also removes a potential
getpeername(2) per log line
: peer_addr() falls back to a live syscall whenever the cached
address is absent, and that arm is reachable.

Security: the CVE-2025-8671 cap survives the extraction

9.2 moves the RST_STREAM queue into a new file. Git replays a new file with no conflict marker, so a
naive extraction would silently ship the pre-cap enqueue_rst and the moved tests would pass,
because they moved with the code.

The decisive invariant is that the cap is tested before rst_sent.insert. It is, and the
ordering is pinned by mutation: moving the guard below the insert fails exactly one test out of
1072
, test_enqueue_rst_into_refuses_at_capacity_without_side_effects. Deleting the guard entirely
trips mass_reap and the property test instead. Three TO SEE THIS RED recipes are in the commit
message, rewritten to name the guard's new location.

Performance: measured, and it is slightly favourable

Release binaries built with identical flags, lto = true, codegen-units = 1:

.text surviving out-of-line mux:: calls
base 10,324,663 B 1195
this branch 10,277,687 B (−46,976, −0.45%) 1185

Zero surviving calls into h2_transmit::*, h2_close::* or h2_header_reassembly::* — the new
modules inline completely — and zero to the trivial pub(super) accessors. What stays out-of-line is
substantial and deserves to be: H2FloodDetector::check_flood has 33 call sites.

Three things checked because they are the usual costs of this shape, and none materialised:

  • snapshot_rtts is byte-equivalent. The peer side is linked_token.and_then(...) before and
    after — lazy, not eager — and all five call sites are per-stream-termination, never per write pass.
    9.4 moved the socket_rtt call inside the implementor; same getsockopt(TCP_INFO), same count.
  • gather/confirm allocate nothing. io_slices is caller-owned and hoisted per write pass,
    identically to base; gather is clear() + push into retained capacity and the IoSlices point
    straight into kawa.storage. Net delta is one usize add per block. UDP's owned-Vec Transmit
    was deliberately not imitated — H2 needs a borrowed view.
  • FinalizeAction is eight unit variants, size_of == 1, returned in a register.

One behaviour change, stated rather than folded away

9.6b's ReArm arm asks the socket a third time:

path base now
no TLS backpressure — the common case 1 1
backpressure, the flush clears the records (Settled) 2 2
backpressure, records survive the flush (ReArm) 2 3

The extra query happens only when rustls still holds records after a flush attempt — the congested
path, immediately before a WRITABLE re-arm. It costs two L1-hot loads:
!self.peer_reset && self.session.wants_write() reduces to an is_empty() on the sendable-TLS
deque. No syscall, no record encode.

The assumption that makes it free is worth stating: FrontRustls is the only production
SocketHandler overriding socket_wants_write(). Every other production handler takes the false
default and never reaches the query. A future kTLS or OpenSSL handler (SSL_has_pending) could make
it a syscall, and at that point the ReArm arm should carry the answer it already holds.

9.5 carries two further deliberate exceptions in force_disconnect's server arm, including a read
order swap — socket_wants_write() now read before peer_gone_after_final_goaway(), inert because
both are &self pure reads. Both are in that commit's message rather than under a blanket "no
behaviour change".

Verification

cargo +nightly fmt --all -- --check                                  exit 0
cargo build  --locked --no-default-features --features …             exit 0
cargo clippy --all-targets --locked … -- -D warnings                 exit 0   0 warnings
cargo test -p sozu-lib  --locked …                                   exit 0   1073 passed, 0 failed
cargo test -p sozu      --locked …                                   exit 0   113  passed, 0 failed
cargo test -p sozu-e2e  --locked … -- --skip tests::fuzz_tests::     exit 0   446  passed, 0 failed
  --test load_state_rollback_e2e            -- --ignored             exit 0   3
  --test frontend_validate_before_commit_e2e -- --ignored            exit 0   1
  --test listener_validate_before_commit_e2e -- --ignored            exit 0   1
RUSTFLAGS='--cfg tokio_unstable' … --test udp_simulation             exit 0   6
RUSTFLAGS='--cfg tokio_unstable' … --test tcp_preread_sim            exit 0   6
check_doc_citations.py --root .                                      exit 0
check_doc_citations.py --base f2082b6e                               exit 0

Each of the seven refactor commits was also verified to stand alone: a clean checkout of each,
cargo test -p sozu-lib with the same flags, counts rising monotonically 1031 → 1039 → 1044 → 1046
→ 1056 → 1060 → 1072, every one 0 failed.

merge-tree --write-tree f2082b6e HEAD exits 0 and the citation gate passes inside the extracted
merged tree.

No async fn in lib/ or bin/. Cargo manifests and lockfile untouched. signal_pending_write
call sites: 13 before, 13 after. No Shutdown::Both added. No test deleted, ignored or loosened.

What remains after this

9.6c — inverting the write path into poll_write_target/handle_write — is the last large tranche
and is deliberately not in this PR. The trap it has to clear is documented here for whoever writes it:
update_readiness returns stalled iff size == 0, so size > 0 && status == WouldBlock clears
the event bit, returns not stalled, and another socket_write_vectored is issued. A write machine
treating status != Continue as a pass terminator drops that second write, and passes every test that
exists today.

The eighth commit

Review found that H2ControlTx::lifetime_cap_reached compared against the const
MAX_PENDING_RST_STREAMS while enqueue_rst and check_invariants both compared against
self.max_pending. So with_cap(n) built an object whose per-insert bound was n but whose
escalation tripwire was still 200.

No production path is affected — new() is the only non-test constructor and passes the constant, so
the predicate answers exactly as before. What it removes is a latent trap: the three predicates are
indistinguishable under new(), so a natural extension of the capacity test that asserted on the
tripwire would have silently tested against 200 instead of its own cap, and passed for the wrong
reason.

Separating them requires a with_cap instance, which is what the new regression test does — it is
the only shape of test that can tell the two readings apart, and it is red against the previous code:

a queue at its own cap must have reached its own lifetime cap
test result: FAILED. 0 passed; 1 failed; 1072 filtered out

Two documentation fixes ride along: h2_stream_table.rs pointed at enqueue_rst_into, a free
function 9.2 deleted, and h2_transmit.rs's module header described the pre-image call order without
recording that the split moved debug.push ahead of the clear — inert, because debug.push does not
touch kawa and both the clear and the consume now happen inside confirm in that order.

…apshot

`log_context!` and `log_context_stream!` sourced their `peer=` slot from
`$self.socket.peer_addr()`. `log_context!` has 113 production callsites in
`h2.rs` (`log_context_stream!` has none outside tests), so every method that
logged was coupled to the `Front` type parameter whether or not it performed
any I/O. Counting production lines that are not comments, that is 113 of the
type's 140 `Front` touch points, measured against `d8b8546e` — "drop `Front`" reads like an I/O problem
and is, measured, four fifths a log-line peer slot.

Add a private `peer_address: Option<SocketAddr>`, filled once in
`ConnectionH2::new` from `SocketHandler::peer_addr`, and interpolate the
field. Touch points go 140 -> 27 against `d8b8546e`; the remaining 27 are
direct `self.socket`
calls that later steps address.

This is NOT a pure value move, and the earlier claim that it was is wrong.
Both production handlers *prefer* a cached address but keep a **reachable**
live-`getpeername(2)` fallback — `SessionTcpStream` and `FrontRustls` each
answer `self.configured_peer.or_else(|| self.stream.peer_addr().ok())`
(`socket.rs`), and `FrontRustls`' arm carries a comment saying the fallback
is reachable and naming the test that fails without it. Nothing in this
commit licenses deleting those arms.

The behavioural delta is real and is the intended one. The snapshot is taken
after the handshake, so wherever the fallback would have answered it answers
here too; it then survives the peer's reset, where a later live lookup
returns `ENOTCONN` and renders `peer=None` on exactly the error lines an
operator reads during an incident. On the direct-HTTPS frontend route, where
`HttpsSession::new` seeds `peer_address` with a best-effort `peer_addr().ok()`,
a line emitted after a reset now renders `peer=Some(addr)` where it used to
render `peer=None`. That is `df52d83d`'s intent applied one level further in,
and it is strictly better; the backend route passes `Some(address)` always
and is unaffected.

One related claim stated precisely, because the loose version is wrong: no
production caller reaches `SocketHandler::peer_addr` on a bare
`mio::net::TcpStream`. The impl exists and `MioTcpStream` IS instantiated in
production (`TcpStateMachine`, `tcp.rs`); the TCP proxy simply reads its peer
through mio's inherent method. The claim is about call sites, not about the
handler.

Tests: `log_context_reads_the_peer_address_once_per_connection` drives a
counting `SocketHandler` and pins the read count at exactly one per
connection across three rendered lines. Seen red by restoring
`peer = $self.socket.peer_addr(),` in `log_context!`: the count goes to 4 and
the assertion fails `left: 4, right: 1`. The two existing peer-slot tests
stay green under that same revert, which is the point of adding a third —
they pin WHICH address is rendered and cannot observe how often the
connection asks for it, because a caching handler returns the same answer
however often it is asked. Both now say so in their own red-recipes, which
previously named a statement this commit removes;
`e2e/src/tests/h2_log_context_tests.rs`'s recipe is the third member of that
set and is updated with them.

Performance: +32 bytes per connection (one `Option<SocketAddr>`, measured
niche-optimised to the same 32 bytes as `SocketAddr`, so `None` costs nothing
extra) against one fewer virtual dispatch per rendered log line. Not per
stream — per connection. The write path is untouched: no allocation change,
no copy change. This commit *grows* `h2.rs` by 165 lines (+169/-4 against
`d8b8546e`); the file only
shrinks once the later extractions land.

Docs: `doc/observability.md`'s `MUX-H2` peer paragraph stated the mechanism
one step off after this change and now names `ConnectionH2::peer_address` as
the capture point. Against `d8b8546e`, 57 citations carrying 79 line numbers,
across LIFECYCLE.md, doc/testing.md and doc/h2_mux_internals.md, are
renumbered to the lines their text moved to, by an exact `difflib` alignment
map over the diff's `equal` blocks. Every one of them cites `h2.rs`. These
figures describe a diff, so they are pinned to the base they were measured
against.

Signed-off-by: Florentin Dubois <[email protected]>
…_tx.rs

`ConnectionH2` carried `pending_rst_streams`, `total_rst_streams_queued` and
the `MAX_PENDING_RST_STREAMS` cap as three loose members, with the
serialization written inline in `flush_pending_control_frames` — a
gen-into-the-zero-buffer loop with its own offset arithmetic and its own
break-on-full condition, beside a WINDOW_UPDATE stage that had already been
given `H2FlowControl::drain_window_updates_into` for exactly that job.

Give the queue its own module, behind the closed API the `hpack_state` /
`h2_flow_control` / `h2_stream_table` / `h2_drain` / `h2_flood_detector` /
`h2_header_reassembly` / `h2_scheduler` steps established. `H2ControlTx` owns
the pending queue, the never-decaying lifetime counter behind the
CVE-2025-8671 MadeYouReset cap, and the cap itself. Serialization becomes
`drain_rst_streams_into(&mut [u8]) -> (usize, usize)` — byte-identical in
shape to `drain_window_updates_into`, which is in turn the shape
`serializer::gen_*` established before either.

No behaviour change on the wire. Emission order is still queue order, a
frame is still written whole or not at all, and frames that do not fit stay
queued for the next `writable()` — `enqueue_rst` already armed WRITABLE, so
a short buffer delays a frame rather than dropping it.

What the module does NOT own is stated in its header with the reason for
each, because every one of them was a candidate:

  * the dedupe set, which lives on `H2StreamTable` because that type's
    removal path asserts it clean — two views of one set can disagree;
  * `Readiness`, because LIFECYCLE invariant 15 arming belongs to whoever
    owns the connection's readiness;
  * the decision to drain, gated on three conditions that all read
    `ConnectionH2` state (nothing queued, a partially-written zero buffer,
    a header block mid-reassembly) — the caller decides whether, this
    module decides what bytes;
  * metrics and the flood detector, because a lifetime-cap trip converts to
    a connection-wide GOAWAY only `ConnectionH2` can return. `enqueue_rst`
    returns an `EnqueueRstOutcome` — `Queued`, `Deduped` or `Dropped` — and
    leaves accounting to the caller, which accounts only `Queued`; the drain
    emits no metric at all, or every frame would be counted twice.

`ConnectionH2::check_invariants`' RST-accounting clause moves to the
module's own `check_invariants`, run as a post-condition of every mutating
method, rather than being restated in two places that can drift.

Tests: the five `test_enqueue_rst_into_*` tests move with the state they
drive and keep their names, and `prop_pending_rst_queue_stays_within_its_bound`
and its `RstStep` generator move with them — the free function they drove existed so the
invariants could be tested without a `ConnectionH2` fixture, and owning them
on `H2ControlTx` gets the same thing from the type instead of from a
six-parameter list. `drain_rst_streams_into` gets the coverage the inline
loop never had: exact fit, a short buffer that takes two of four frames, a
buffer too small for even one, and an empty queue. `draining_does_not_rewind_the_lifetime_cap`
is the new regression, seen red by subtracting the drained count from the
lifetime counter — two tests fail on that revert, because rewinding is
precisely how a peer evades the MadeYouReset cap: drain, re-queue, repeat.

Performance: no allocation change and no copy change. The drain writes the
same bytes into the same `zero.storage` space through the same
`serializer::gen_rst_stream`; what moved is where the loop lives.

Docs: LIFECYCLE.md's queued-RST section and `doc/h2_mux_internals.md`'s
writable stage 6 name the new home. Invariant 7 becomes a symbol citation
rather than a line, because its old anchor was a generic statement inside
the deleted free function and the prose already names the item — with an
in-line note saying so, so the next editor does not convert it back.

Invariant 7 is also now SCOPED to the queued path, and this commit is what
made that necessary. Its pre-image was modest — "check `rst_sent_contains`
before queuing another" — and naming a chokepoint under the absolute
heading "No duplicate RST_STREAM on the wire" would have overclaimed:
`converter.rs` serializes RST_STREAM straight into `kawa.out` from its
`initialize` chokepoint, its trailer-error arm and its HPACK over-budget
abort, and `ConnectionH2::close` writes a `Cancel` frame into
`zero.storage` directly. Those four sites never touch `H2ControlTx`; each
carries its own `rst_sent_contains` guard, and the invariant now says so
instead of implying the queue covers them.

Three in-code comments that named the fields this commit made private are
updated to name `H2ControlTx` instead — `h2_stream_table.rs`'s module doc,
`mod.rs`'s idle-reaper comment and `h2.rs`'s chokepoint comment. None is
reachable by the citation gate, which walks only `doc/**`, `**/LIFECYCLE.md`
and `CHANGELOG.md`.

Against the `d8b8546e` base, 93
citations carrying 132 line numbers, across LIFECYCLE.md, doc/testing.md
and doc/h2_mux_internals.md, are renumbered by a difflib alignment map over
each cited file, which is independent of whether the anchor text is unique;
35 of them are `mod.rs` citations shifted by the single added
`mod h2_control_tx;` line. These are facts about a diff, so they are pinned
to the base they were measured against.

Signed-off-by: Florentin Dubois <[email protected]>
…firm

`ConnectionH2::flush_stream_out`'s loop body built `IoSlice`s pointing into
`kawa.storage`, transmuted them to `'static` with an `unsafe`, handed them
to `socket_write_vectored`, cleared the vector and consumed.
`h2_transmit::gather` now produces the descriptors and `h2_transmit::confirm`
clears them before `kawa.consume`. Both are generic over `kawa::AsBuffer`,
which is what lets them be driven in tests over a `SliceBuffer` with no pool
and no socket.

No behaviour change: the same bytes, one write per round, the same consume,
the same stall classification through `update_readiness_after_write`.

What this does NOT do, stated because an earlier version of this message
claimed all three. The pre-image already cleared before the consume and
already carried the same `debug_assert!`; the gap between the `unsafe` and
that clear was six lines, not eleven, and the debug event, byte counters and
READABLE re-arm all came AFTER the clear rather than between. And nothing is
now enforced at the type level: two free functions each taking an independent
`&mut Vec` is co-location, not enforcement, and a caller can still reach
`Kawa::consume` without asking this module. A guard type owning the vector
would earn the word "structural"; this does not. The gains are real but
modest — one place to read the obligation and its discharge, a `gather`
reusable from a second call site, and both halves unit-testable at all.

The module header states why this is a two-call protocol and not a
`poll_transmit`. A pure `poll_transmit(&mut self, buf: &mut [u8])` would
introduce a copy this path does not make, and unlike a QUIC datagram a TLS
byte stream accepts partial writes, so `kawa.consume(size)` needs a number
only the shell knows. There is no `poll_transmit` anywhere in this
repository; the sibling UDP core — `protocol/udp/` is a sibling of
`protocol/mux/`, not a layer above it — names its coarser equivalent
`UdpManager::poll_output`, and it drains a manager-wide queue where `gather`
sees one stream's `Kawa`.

It also records where scheduler fairness meets this code, with the mechanism
named correctly. `apply_incremental_rotation` rotates EVERY same-urgency
run; what LIFECYCLE invariant 26 scopes to the leading bucket is the COMMIT,
and hence the fairness bound. `Prioriser` holds one connection-global cursor
and `end_pass` commits only the first incremental stream that fired, always
in the lowest-numbered ready bucket — so in any other bucket that cursor is a
foreign id range, `partition_point` returns a constant, and the rotation runs
but is a no-op. The result is positional unfairness while a pass completes,
and BYTE starvation the moment a pass stalls: the streams after the stall are
not written, and a frozen order presents them last again next pass.

Tests. `confirm_leaves_no_descriptor_for_the_next_round` is named for what it
can observe. Its predecessor was called
`confirm_clears_the_descriptors_before_consuming` and could not detect that
ordering at all: it inspects the vector only after `confirm` returns, where
both orderings leave it empty. Verified by moving the clear after the consume
AND deleting the internal `debug_assert!` — 421/421 green. It had been "seen
red" by the revert, but the assertion that fired was production's, not the
test's, which is a way for the red-then-green ritual to pass while proving
nothing. The ordering's real guard is that `debug_assert!`; it is a
POSITIONAL check, so it fires only if the clear is moved past it and says
nothing if clear and assert move together, and it compiles out in release.
Both facts are now in the test's doc with a separate red recipe for each: six
tests fail on the ordering revert, exactly one fails when the clear is
deleted outright.

`partial_write_property` drives multi-round gather/confirm over an arbitrary
block split, arbitrary interleaved `Delimiter`s and an arbitrary cycle of
accepts INCLUDING ZERO — production's `WouldBlock`, and the only way to reach
the stalled pass this header discusses. The earlier generator emitted
`1 + arbitrary % len`, so that path was structurally ungenerable and the
header described something no test could enter. Its `drive` now mirrors
`flush_stream_out` instead of approximating it: it stops on a zero accept
against a non-zero offer, where before it broke on a zero OFFER — which
production never does, and which would skip a leading `Delimiter` rather than
consuming it. The oracle is a prefix of the payload the test itself built,
plus full delivery exactly when the queue drained. It asserts nothing about
liveness or turn-taking across streams; a property claiming every stream
drains would assert something invariant 26 does not guarantee. Its
justification is the input space it covers — every deterministic case here is
single-round — not exclusive detection, and the recipe says so: the mutation
that reddens it reddens four other tests too, and I could not construct one
that reddens only it.

The pair assertion in `gather` no longer requires descriptor count and
offered bytes to be zero together: a zero-length `Store` yields a descriptor
offering no bytes, which the pre-image handled and an `assert_eq!` on the two
emptinesses would have turned into a panic. Only the load-bearing direction
is asserted — a non-zero offer implies at least one descriptor. `gather`'s
return value gains a production consumer: `flush_stream_out` now asserts the
socket never reports more bytes written than were offered.

Performance: no allocation change and no copy change on the write path. The
`io_slices` vector is still hoisted once per write pass, and the descriptors
still point straight into `kawa.storage`. `gather` sums the offered length,
one add per block over a loop that already walks every block.

Docs: `doc/h2_mux_internals.md` gains a section on the pair beside
`write_streams()`, which the first version of this change omitted while its
sibling extraction documented its own module. Against the `d8b8546e` base, 94
citations carrying 133 line numbers, across LIFECYCLE.md, doc/testing.md and
doc/h2_mux_internals.md, are renumbered by a difflib alignment map over each
cited file; the figures are pinned to that base because they describe a diff. The old test name
is registered in the citation checker's `RENAMED_TESTS`, because CHANGELOG.md
cites it deliberately to record that the rename is the fix.

Signed-off-by: Florentin Dubois <[email protected]>
`Endpoint::socket(token) -> Option<&TcpStream>` existed for exactly one
purpose: sampling TCP_INFO round-trip time for the side a connection does
NOT own, so the access log's `server_rtt` cell could be filled. Every one of
its four call sites — `ConnectionH2::snapshot_rtts` and H1's upgrade,
early-hint and complete paths — immediately did `.and_then(socket_rtt)` on
the result and used nothing else from it.

Replace it with `Endpoint::peer_rtt(token) -> Option<Duration>` and move the
`socket_rtt` call into the two implementors. `EndpointServer` ignores the
token and reports its single frontend; `EndpointClient` keys backends by
token and reports that one.

No behaviour change: the same `getsockopt(TCP_INFO)` on the same socket at
the same moment, and the same `None` on a token that does not resolve.

What changes is the boundary, and it is the point of the commit. A concrete
`mio::net::TcpStream` leaves the `Endpoint` trait. That type was two problems
at once: an authority leak, because any connection could reach any other
connection's socket through this method for any purpose it liked; and the
reason no in-memory transport could ever implement `Endpoint`, since a pipe
cannot produce a `mio::net::TcpStream`. RTT is intrinsically a live-socket
property, so it stays on the embedder's side of the boundary and the cores
receive a value captured for them rather than a handle to capture it
themselves. This is the Q11 half of the sans-io boundary; the connection's
OWN socket is still reached directly and is 9.6's problem, not this one.

Tests: `endpoint_client_peer_rtt_is_keyed_by_token` pins the token-keyed
lookup — an unknown token must yield `None` rather than the only backend in
the map — and asserts its own premise first, that a KNOWN token returns
`Some`, because without that half it would pass against a `peer_rtt` that
always answered `None`. Seen red by swapping `.get(&token)` for
`.values().next()`: it fails with `an unknown token must not resolve to
another backend's RTT`, and the sibling test stays green.
`endpoint_server_peer_rtt_ignores_the_token` pins the other implementor,
seen red by returning `None`, failing on the first loop iteration with
`EndpointServer must report its single frontend's RTT for any token`.

The pair is worth having because the two sides populate DIFFERENT access-log
cells — `snapshot_rtts` reads the local socket for `client_rtt` and this
trait method for `server_rtt` — so a lookup that returned the wrong
connection's RTT would mislabel the value rather than lose it, and nothing
downstream asserts on RTT content.

H1 regression, required because this changes three `h1.rs` call sites in an
H2-motivated changeset: `cargo test -p sozu-e2e -- mux_tests h1_security`,
41 passed, 0 failed. No friction.

Docs: `doc/h2_mux_internals.md`'s RTT block states what `peer_rtt` returns
and why it is not the socket. Against its parent `844cbaca`, 64 citations
carrying 89 line numbers are renumbered across LIFECYCLE.md, doc/testing.md
and doc/h2_mux_internals.md, by a difflib alignment map over each cited file.
The figure is a property of this commit's own diff, so it is anchored to the
parent it was measured against and not to the branch base; measured by
aligning each document's citation list on the digit-normalised line each
citation sits on, counting a citation once and a single-number citation as one
line number.

Signed-off-by: Florentin Dubois <[email protected]>
…_close.rs

Three sites decide whether an H2 connection may close while rustls may still
hold encrypted records: the `H2State::GoAway` arm of `ConnectionH2::writable`,
the `(H2State::Error, Position::Server)` arm beside it, and
`force_disconnect`'s server arm. Closing with records pending sends FIN and
destroys them, which the client reads as a truncated response — the GoAway
arm's own comment calls it the primary truncation vector under HAProxy
chaining. That is data loss, not style, so the decision moves somewhere it
can be enumerated and tested.

Behaviour: the same queries, the same flush between them, the same results,
with two deliberate exceptions, both in `force_disconnect`'s server arm. Its
two `debug!` lines hard-coded `wants_write=true` and `wants_write=false`; the
closing arm is also reached with records still PENDING whenever the peer is
gone, so the line an operator reads while diagnosing a truncation under
HAProxy chaining could state the opposite of the socket's state. Both now
interpolate one binding. Taking that binding also swaps the read order —
`socket_wants_write()` is now read before `peer_gone_after_final_goaway()` —
which is inert because both are `&self` pure reads, and is stated rather than
folded into a blanket "no behaviour change" that would only be true under an
unstated premise.

The decision becomes a pure function of `(peer gone, records pending, have we
flushed yet)`. The third input is the point of the commit. The pre-image
nested two `socket_wants_write()` calls around a `socket_write(&[])` whose
returned `size` and `SocketResult` are BOTH discarded at that site, so "did
the kernel take them?" is inferred purely from the same accessor answering
differently after the flush. The two queries are two different questions
wearing one name. `TlsFlushPhase` makes them two values that cannot be passed
for each other, and `the_two_phases_are_not_interchangeable` pins that they
answer differently for the same `tls_wants_write` — a caller that reuses the
first answer for the second flushes forever and never re-arms.

The flush still happens inside the same `writable()` call. Deferring it would
deliver the bytes on the next WRITABLE, but would double the latency of every
close under backpressure and strand the connection against a peer that never
re-arms. `a_flush_that_succeeds_closes_within_one_writable_call` pins that a
single call reaches the disconnect, and is red against the deferred shape.

This closes a coverage gap rather than a defect, and the gap is the reason
the commit needed a new harness. NO test anywhere instantiated a
`ConnectionH2` over a handler whose `socket_wants_write()` could return
`true`: `mio::net::TcpStream` and `SessionTcpStream` take the trait's `false`
default and only `FrontRustls` overrides it, which no test builds. Every
branch named above was statically dead in the suite, including the truncation
vector. See #1454.

`BackpressuredTlsSocket` models rustls over a kernel that accepts a
configurable number of records per flush. It models the STATE rather than
scripting an answer sequence, because the close path queries
`socket_wants_write()` a number of times that depends on which branches it
takes — a positional script would pin the query count instead of the
behaviour and would have to be rewritten by anyone adding a query.

Both outcomes of the second question are covered for the `H2State::GoAway`
arm, which is the only one of the three sites a real `ConnectionH2` reaches
here:

  * `a_flush_that_does_not_drain_keeps_the_connection_open` — the kernel
    accepts nothing, records survive, the session stays open, the connection
    is still in `H2State::GoAway`, and the WRITABLE EVENT bit is re-signalled.
    The event bit, not the interest bit: interest is the argument this
    fixture itself hands `ConnectionH2::new` and nothing on this path clears
    it, so an assertion on it could not fail. Its red recipe is in the test's
    own doc comment.
  * `a_flush_that_succeeds_closes_within_one_writable_call` — the kernel
    takes them and the disconnect is reached in the same call. Red by
    returning `Continue` after the flush: `a drained flush must reach the
    disconnect in the SAME writable call`.

Each asserts its own premise first — that the harness really does report
buffered records — because without that half both would pass against a
handler taking the `false` default, which is precisely the blind spot #1454
names.

What is still uncovered: the `(H2State::Error, Position::Server)` arm and
`force_disconnect`'s re-arm branch are exercised only as pure functions in
`h2_close`'s tables, and no test reaches them through a connection whose
handler answers `true`. `BackpressuredTlsSocket` is a TCP handler with a
modelled `socket_wants_write`, which is the fixture shape #1454 explicitly
rules out for closing it, so #1454 stays open and this changeset does not
resolve it.

`h2_close`'s own tests are exhaustive rather than illustrative: the three
functions are total over their inputs and every reachable row is asserted,
including that `Flush` is never returned after a flush (which would loop) and
that no site closes on a live peer with records pending (the truncation
guard, stated as one assertion over all three).

Docs: LIFECYCLE.md gains invariant 27 for the two-question rule, the
tick-count constraint and the #1454 coverage note. Against its parent
`4403dd83`, 83 citations carrying 113 line numbers are renumbered by a difflib
alignment map, and five citations are converted to symbols, each with an
in-line note so it is not converted back. The figure is a property of this
commit's own diff, so it is anchored to the parent it was measured against and
not to the branch base; measured by aligning each document's citation list on
the digit-normalised line each citation sits on, counting a citation once and a
single-number citation as one line number.
Three are the collision case: the number my alignment map chose for the
citation is one a DIFFERENT bullet used at the base revision, and the drift
rule keys on the citation rather than on where it sits, so it cannot tell
that collision from staleness. A sixth conversion this step used to make, the
`Recycle` transition list, is no longer needed: `d8b8546e` had already
replaced that bullet's four line citations with symbols, which also retired
the collision the `recycle_slot` conversion used to cite — that one is now by
symbol because `recycle_slot` is the one binding in `create_stream` that
performs the search, not because anything collides. The fifth, the
socket-backpressure resume path, is not a collision
— it was already stale at the merge base, where it named
`enqueue_rst(header.stream_id, H2Error::StreamClosed)` rather than the resume
path, and passed the drift rule only because the text at that number happened
not to change until this commit moved it.

Signed-off-by: Florentin Dubois <[email protected]>
`ConnectionH2::readable` was one function: a pass prelude, a
`self.socket.socket_read` in the middle, and the frame state machine after it.
It is now a two-call protocol, the read-side mirror of the
`h2_transmit::gather` / `confirm` split. The core names the buffer it wants
filled, the caller performs the read, and the core is told how many bytes
arrived and with what status.

`poll_read_target` owns everything up to the decision, because two of its three
answers come out of the prelude: `H2ReadTarget::Done(result)` when a
SETTINGS-ACK timeout or an idle `expect_read` ended the pass with nothing owed,
`Skip(stream_id)` when the frame in flight carries a zero-length payload,
`Fill { stream_id, amount }` otherwise. A poll that could not say "nothing"
would not be the core's answer, which is why the prelude moved rather than
staying behind. `handle_read` takes `H2ReadOutcome::Skipped` or
`Filled { amount, size, status }`, fills, counts, classifies the stall and
dispatches the frame. `readable` is the caller between them and holds the only
read syscall on the whole H2 read path.

No behaviour change. The prelude runs in the same order, `arm_timeout()` still
fires for an `H2StreamId::Other` before the read and before the available-space
bail-out, the debug event still carries `usize::MAX` for stream 0, the byte
counters and `update_readiness_after_read` are untouched, and the whole
`match (&self.state, &self.position)` moved verbatim. `signal_pending_write()`
still has exactly five call sites.

`Skip` is a variant rather than `Fill { amount: 0 }`, and that is load-bearing
rather than taste. A zero-length read answers `(0, SocketResult::Continue)`,
and `update_readiness_after_read` returns `true` for it — "nothing arrived,
stop" — so a caller handed a zero-length `Fill` would return before the state
machine ever ran, and every frame carrying no payload (an empty SETTINGS, an
empty DATA, a SETTINGS ACK) would stop being parsed. The variant is what keeps
a future caller from having to know that.

The offer is a descriptor and not a `&mut [u8]` for a borrow reason worth
stating, because it is the same one that made `h2_transmit::gather` a free
function: a method returning a borrow of all of `*self` would make the
following `self.socket.socket_read(buf)` a second mutable borrow of `self`.
`read_buffer` and `read_space` therefore take `zero` and `streams` apart, which
keeps `ConnectionH2::socket` and `Context::debug` borrowable while the offered
buffer is live. `read_space` caps the slice at `amount`: reading past the byte
debt would fold the next frame's header into this frame's payload.

Naming. `poll_read_target` / `handle_read` follow `UdpManager::poll_output` and
`UdpManager::handle_input` (`lib/src/protocol/udp/manager.rs`), the sibling
sans-io core's existing spelling for the two directions. Deliberately not
`poll_read`: that is `AsyncRead::poll_read`'s name, its first parameter is a
`task::Context` and this one's is the mux's own `Context`, and nothing in
`lib/` or `bin/` is asynchronous — the shadow is not worth two saved words.
There is still no `poll_transmit` anywhere in this tree, and UDP's `Transmit`
is not copied either: it carries an owned `Vec<u8>` where this path needs a
borrowed view into live `kawa.storage`.

Tests. `read_buffer` is the only new logic in the commit; everything else
moved. Four tests, each red against one distinct single-token mutation, on its
own assertion — every recipe executed rather than asserted:

- `read_space_offers_the_read_buffer_of_the_stream_the_core_named` — pointer
  identity for `Zero` and for `Other`, plus the `[..amount]` cap. `.rbuffer` ->
  `.wbuffer` gives ``left: 0x7fa2178a2060 / right: 0x7fa21789e040`` on "a
  server position must offer the stream's request (front) buffer". It asserts
  its own premise first — that front and back really are distinct allocations —
  so the comparison can discriminate at all.
- `poll_read_target_skips_the_read_when_the_frame_carries_no_payload` —
  dropping the `Skip` branch gives "a zero-length payload must be a Skip, not a
  zero-length Fill: Fill { stream_id: Zero, amount: 0 }".
- `handle_read_subtracts_the_byte_count_the_caller_reported` — `amount` for
  `amount - size` gives ``left: Some((Zero, 9)) / right: Some((Zero, 6))``. 6
  is neither number the test hands in, so it cannot pass by echoing its own
  fixture.
- `handle_read_clears_the_readable_event_not_the_interest_when_nothing_arrived`
  — `update_readiness_after_write` for `update_readiness_after_read` gives "an
  empty read must clear the READABLE event". The interest half is asserted
  deliberately: this path and `signal_pending_write` both touch
  `Readiness.event` only, and an assertion written against `interest` cannot
  see either of them move.

Docs. `doc/h2_mux_internals.md`'s `readable()` section describes the protocol
and why `Skip` exists; every LIFECYCLE.md sentence that named an arm of
`readable` now names the half it actually lives in — `H2State::Discard` and
`H2State::ContinuationFrame` in `handle_read`, the DATA-payload `arm_timeout()`
site in `poll_read_target`, §7.4's interaction order across both. Against its
parent `a75f9017`, 46 citations carrying 63 line numbers are renumbered by a
difflib alignment map over the cited file. The figure is a property of this
commit's own diff, so it is anchored to the parent it was measured against and
not to the branch base; measured by aligning each document's citation list on
the digit-normalised line each citation sits on, counting a citation once and a
single-number citation as one line number. Three citations the map could not
follow correctly, because this change moves the lines they name out of
`readable` wholesale, were re-anchored by hand instead: the `read_buffer`
dereference, the SETTINGS-ACK deadline block, and one pinned code block
relocated by its literal content. A map can answer those three with a
plausible wrong line rather than with nothing, so each was re-derived from the
code and its enclosing `fn` checked, not just its text.

Signed-off-by: Florentin Dubois <[email protected]>
…e_action

`ConnectionH2::finalize_write` held the last unconverted instance of the
query / flush / query shape the close sites already delegate:
`socket_wants_write()`, a CONDITIONAL `socket_write(&[])`, then
`ensure_tls_flushed()`'s second `socket_wants_write()`. It is now one
`h2_close::finalize_action(BeforeFlush, …)` call, the step that answer names,
and the same function at `AfterFlush`. Zero lines of `write_streams`' `'outer`
loop move.

No behaviour change. The same queries in the same order, the same flush between
them, the same `Readiness` mutations, the same debug narration, the same
`MuxResult::Continue`, and the RFC 9113 §6.8 graceful-GOAWAY `if` untouched
where it was — it is decided before any flush and needs no phase. The one
mechanical delta is that the post-flush `socket_wants_write()` is now read at
the call site instead of inside `ensure_tls_flushed`; `FrontRustls`'s
implementation is `!self.peer_reset && self.session.wants_write()`, a pure
`&self` read, so the extra query cannot change what the pass observes.

A sibling `FinalizeAction`, not a widened `CloseAction`. Every `CloseAction`
variant answers "may this connection close, or must it keep draining".
`finalize_write`'s non-flush branch answers which `Readiness` bits the next tick
needs — LIFECYCLE §9 invariant 16's readiness policy — and decides nothing about
closing; widening `CloseAction` would force a named-impossible arm into every
exhaustive `match` `writable` already writes over it. `TlsFlushPhase` is shared,
because the two-query distinction is the identical one.

The conditional middle flush becomes the third input. `if !socket_write` does
not stay behind in `h2.rs`: it is the `socket_write` parameter and surfaces as
two pre-flush answers, `Flush` and `SkipFlush`, differing only in the step the
caller performs and both leading to the same post-flush query. EIGHT variants,
not the seven the plan predicted — the boundary report and the brief both say
seven while the report's own list enumerates eight, an arithmetic slip over the
list rather than a design one. `Parked` and `Settled` are NOT merged to reach
seven: both mean "change no bit", but they answer different phase questions,
which is this module's whole thesis. Both caller matches are exhaustive with
named-impossible arms; no `_`, and no `other => unreachable!`, which is a
wildcard in disguise that compiles when a variant is added and becomes a
release-mode panic on the proxy write path instead of a compile error.

The invariant-16 probe is passed as `impl FnOnce() -> bool`, the one departure
from this module's one-bit-projection convention, and it is a cost decision.
`any_stream_has_pending_back` walks every open stream of the connection, and the
pre-image reached it only under
`!socket_wants_write && expect_write.is_none() && bytes_written > 0`. A `bool`
would make the caller run that walk on every write pass instead, including every
TLS-backpressured one and every zero-progress one — a cost regression wearing
"no behaviour change" as a disguise.

No `SocketResult` reaches the decision. `finalize_write` discards
`socket_write(&[])`'s `(size, status)` exactly as the close sites do, so
`update_readiness`'s `size > 0` with `WouldBlock` case — NOT stalled, event bit
cleared, another write issued — is unreachable through `finalize_action`. It
stays where it is, in `flush_stream_out` via `update_readiness_after_write`, and
`flush_zero_buffer`, the one write-path site that does consume a status, is
untouched.

`FinalizeAction::ReArm` calls `ensure_tls_flushed()` rather than
`signal_pending_write()` directly. That asks the socket a third time for an
answer the decision already has, which is redundant and deliberate: it keeps
every post-decision TLS re-arm in this file spelled the same way, as the GoAway
and Error arms of `writable` already do, and keeps this commit free of an
unrelated change. `signal_pending_write()` still has exactly 13 production call
sites. `self.socket` in `h2.rs` goes 34 -> 35 raw and 27 -> 28 effective (7
doc-comment mentions at both revisions): making the two queries two values
requires the CALLER to hold the post-flush query, which the pre-image hid inside
`ensure_tls_flushed`. `grep -rn "async fn" lib/src bin/src` still returns
nothing.

Size: ~236 production insertions (176 in `h2_close`, ~60 in `h2.rs`), ~565 test,
~174 doc. The plan's 250-350 estimate was the production figure.

Tests. Ten pure tables in `h2_close` sweeping full cross products rather than
re-deriving the priority chain — TLS backpressure dominates all sixteen
readiness combinations, a parked `expect_write` dominates the remaining eight,
the pre-flush and post-flush answer sets are disjoint in both directions, and
invariant 16's retain/withdraw decision is eight explicit rows — plus two
`writable()` tests in `h2.rs`.
`a_finalized_write_pass_flushes_once_and_re_arms_while_records_survive` runs a
real `ConnectionH2` over `BackpressuredTlsSocket` in `H2State::Header` with
three records and one drained per flush, so the preamble takes one,
`finalize_write` takes the second and the third survives — which is what lets
the post-flush query answer something the fixture could not answer by
construction. `a_write_pass_that_owes_nothing_withdraws_writable_interest`
covers the withdrawal. `goaway_connection_with_backpressure` gains a `state`
parameter instead of a second copy of the fixture. `SkipFlush`, `Parked`,
`RetainPendingBack` and `ArmControlQueue` are pinned by the pure rows only; no
assertion in `h2.rs` reads any of them, and reaching the first three through
`writable()` needs a stream carrying response bytes through the scheduler that
no fixture here builds.

Eight "TO SEE THIS RED" recipes, every one EXECUTED rather than asserted, each
red on its own test's own assertion and none through a production `unreachable!`
or `debug_assert!`:

  - `Flush` returned unconditionally -> `a pass that already wrote must not
    spend a second empty-buffer flush` (left Flush / right SkipFlush)
  - drop the `made_progress &&` conjunct -> `no progress: a starved pass must
    relinquish WRITABLE rather than busy-spin, got RetainPendingBack`
  - hoist the probe to the top of the arm -> `the invariant 16 probe must not be
    walked while rustls still holds records`
  - swap the `&&` conjuncts -> `a zero-progress pass cannot retain WRITABLE, so
    the probe must not be walked` (the answers are unchanged; only the work
    moves, which is what a `bool` parameter would bake in)
  - `AfterFlush` delegates to `BeforeFlush` -> `AfterFlush must never ask for
    another flush: [true, false, false, true, true, true] gave Flush`; measured,
    four tests fail together, the fourth being `h2.rs`'s integration test at the
    production `unreachable!` with `AfterFlush yielded Flush`
  - empty the `Flush` arm -> `finalize_write must attempt exactly one
    empty-buffer flush of its own` (left 1 / right 2)
  - empty the `ReArm` arm -> `the WRITABLE event must be re-signalled`
  - drop `interest.remove(Ready::WRITABLE)` -> `a pass that owes nothing must
    relinquish WRITABLE interest`

Docs. `doc/h2_mux_internals.md` gains a `finalize_write()` section carrying the
answer table, LIFECYCLE.md's invariants 16 and 27 and §8.2 name the decision's
new home while `finalize_write` keeps the `Readiness` bits. Against its parent
`20f4293c`, 32 citations into `h2.rs`, carrying 46 line numbers, change number
by a difflib alignment map over the cited file, each verified landing on
byte-identical text inside the same `fn`. The figure is a property of this
commit's own diff, so it is anchored to the parent it was measured against and
not to the branch base; measured by aligning each document's citation list on
the digit-normalised line each citation sits on, counting a citation once and a
single-number citation as one line number.

One citation is converted to a symbol: §5.2's `try_resume_reading` dereference,
which becomes "the `expect_read` block" because that read is the file's only
`let stream = &context.streams[global_stream_id];`, so the symbol resolves
unambiguously while a line number there cannot. What changed against the
pre-rebase version of this step is the REASON, not whether the conversion
happens — it used to be a collision with a number a different bullet held, and
`d8b8546e` retired that collision by replacing the `Link` bullet's six numbers
with eight symbols and the `Recycle` bullet's four with four. §3.1's `Link`
transition list, which this step also used to convert, therefore needs nothing.

Signed-off-by: Florentin Dubois <[email protected]>
…ched

`H2ControlTx` carries one cap per instance, `max_pending`, and three
predicates that must all read it: the per-insert bound in `enqueue_rst`,
the post-condition in `check_invariants`, and the escalation tripwire in
`lifetime_cap_reached`. The first two read `self.max_pending`; the third
read the `MAX_PENDING_RST_STREAMS` constant, so a `with_cap(n)` instance
had a per-insert bound of `n` and a tripwire still waiting for 200.

Not reachable in production. `new()` is the only non-test constructor and
passes the constant, so all three agree there; the two `with_cap` callers
(caps 4 and 16) never call `lifetime_cap_reached`, and the four tests that
do all build with `new()`. The defect is latent and specific: a natural
extension of `test_enqueue_rst_into_refuses_at_capacity_without_side_effects`
that asserted on the tripwire would have compared a queue at its own cap of
4 against 200, reported "not reached", and passed for the wrong reason on a
type whose whole job is the CVE-2025-8671 cap.

The three predicates are genuinely indistinguishable under `new()`, so the
regression has to build the instance that separates them.
`the_lifetime_cap_tracks_the_instance_bound_not_the_constant` fills a
`with_cap(4)` queue to its own cap and asserts the tripwire has fired. Seen
red by restoring the constant: `a queue at its own cap must have reached its
own lifetime cap`.

Two dead or stale doc pointers in the same area, both left behind by the
`h2_control_tx.rs` extraction:

  * `H2StreamTable::rst_sent_mut` named `enqueue_rst_into`, "a free function,
    unit-tested independently of `ConnectionH2`". That function no longer
    exists — `grep -r 'fn enqueue_rst_into'` finds nothing — and the pointer
    now names `h2_control_tx::H2ControlTx::enqueue_rst`, which LIFECYCLE.md
    §8.2 was already rewritten to name.
  * `h2_transmit.rs`'s module header described the pre-image call order. The
    split did move one thing: the caller now pushes its `DebugEvent::SocketIO`
    before calling `confirm`, so the clear follows the debug event instead of
    preceding it. That is inert — `debug.push` does not touch `kawa` — and the
    obligation the module states, "clear before the consume", still holds
    because both now happen inside `confirm`, in that order. The header says
    so rather than implying nothing moved.

No behaviour change on any production path: in production `self.max_pending`
IS `MAX_PENDING_RST_STREAMS`, so the predicate answers exactly as before.

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