Skip to content

fix(mux): capture listener configuration per request, not per connection - #1513

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
fix/h2-listener-config-snapshot
Sep 24, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
fix/h2-listener-config-snapshot

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Answers Question 7 of #1340: does the H2 core freeze the listener into an owned
snapshot at construction, or keep Rc<RefCell<L>> and go on taking live borrows on
the write, reset and access-log paths?

Neither. The capture is per request, taken when the request arrives.

The contract

A request captures the listener configuration it needs when it arrives and runs to
completion on that capture. A reload landing afterwards does not reach it. The next
request picks the reload up. The staleness window is therefore exactly one
request.

#1340 asked for that window to be stated rather than left to emerge from wherever
the next listener.borrow() happens to sit, so it is now written down in
lib/src/protocol/mux/LIFECYCLE.md §2.5 (data plane) and
doc/configure_admin_ops.md §1.1 (operator facing), not only implemented.

Freezing at construction was rejected because hot reconfiguration is the reason this
proxy exists: a long-lived H2 connection would serve every stream under the
configuration in force when it was accepted.

The sites

Nineteen production listener.borrow() sites live under mux/. Set aside
Context::new's four construction reads and Router::connect's four backend-dial
reads, and eleven are on the datapath — none of them touching a socket, all of
them reads (there is no borrow_mut on the listener anywhere in mux/).

Site Reads Scope Disposition
Context::create_stream get_sticky_name, get_sozu_id_header, get_strict_sni_binding, get_elide_x_real_ip, get_send_x_real_ip, get_answers per request this is the capture point
ConnectionH1::readable, its keep-alive reparse, ConnectionH1::end_stream get_answers per request read Stream::answers
ConnectionH2::end_stream get_answers per request read Stream::answers
Mux::ready_inner connect-error arm, Mux::timeout_inner get_answers per request, in a connection-wide loop read each stream's own Stream::answers
ConnectionH2::begin_scheduler_pass protocol() per connection — a listener's kind is fixed by its type Context::protocol, captured in Context::new
Router::backend_from_request get_sticky_name per request removed
Stream::generate_access_log get_tags per request left live, see below
Router::route_from_request frontend_from_request per request left live — Question 6
Router::connect (×4) get_h2_flood_config, get_h2_connection_config, get_h2_stream_idle_timeout, get_h2_graceful_shutdown_deadline per backend connection, at dial unchanged

One further occurrence is inside #[cfg(test)] (h2.rs, the write_streams helper)
and is left as it is.

What changed

Three knobs were the construction-time freeze, already in the tree.
Context::strict_sni_binding, Context::elide_x_real_ip and
Context::send_x_real_ip were read once in Context::new, and all three are
patchable through UpdateHttpListenerConfig / UpdateHttpsListenerConfig — so an
operator patching them never reached an open connection at all. They move into
Context::create_stream, beside the sticky cookie name and Sozu-Id header name it
already captured there.

One live borrow was the opposite failure. Router::backend_from_request re-read
get_sticky_name after routing, under a comment reading "update sticky name in case
it changed I guess?"
. A request matched on the old cookie name could be answered
with a Set-Cookie under a new one. That read is gone and the method no longer takes
a listener handle.

The answer registry is captured by handle, so the listener now publishes it.
Template owns a kawa::Kawa and cannot be cloned, so Stream::answers is an Rc
rather than a copy — and an Rc to a cell the listener rewrites is only a renamed
live borrow. HttpListener::update_config / HttpsListener::update_config therefore
build a fresh HttpAnswers and install it under a new Rc.
HttpAnswers::cluster_answers holds Rc<Template> so the per-cluster overrides can
be copied into the published registry: migrating them with std::mem::take, as the
in-place rewrite did, would empty the registry the in-flight requests still hold and
strip their custom pages mid-response.

That publication boundary is the listener reload and nothing else — add_cluster /
remove_cluster still edit the live registry in place, which §2.5 states.

Two reads deliberately left live

  • frontend_from_request — Question 6, still open, and a request must in any case be
    routed against the frontends that exist when it is routed.
  • get_tags — the access-log fallback, reached only for a request that never
    finished routing. Resolving it needs the request authority, which does not exist at
    the capture point, and snapshotting the listener's authority-keyed map per request
    would cost more than the observability it buys. Flagged as a judgement call rather
    than made silently.

Neither Question 6 (routing out of the core) nor Question 12 (opaque backend ids) is
touched.

The reload test

a_listener_reload_between_two_streams_moves_only_the_second (mod.rs) opens a
stream, reloads the listener under it, opens a second, and asserts the second moved
while the first did not. Both halves matter and they fail for opposite reasons — a
construction-time freeze breaks the second, a live datapath borrow breaks the first.

Seen red before it was trusted, three ways:

Reverted to Assertion that fired
knobs frozen in a Context::new field a request arriving after the reload must use the new X-Real-IP policy
answers captured per connection a request arriving after the reload must render from the newly published answer registry

a_listener_answers_reload_publishes_a_new_registry (lib/src/http.rs) covers the
publication half against the real HttpListener:

Reverted to Assertion that fired
*self.answers.borrow_mut() = new_answers a reload must publish a NEW answer registry: rewriting the captured one reaches every request already in flight
new Rc, but mem::take for the overrides the registry captured before the reload must keep its cluster overrides

The production diff adds no string literal at all, and shares no literal with
either test file.

HTTP/1.1 is not covered by the one-request window

http.rs and https.rs call Context::create_stream once per H1 connection, and
HttpContext::reset deliberately carries the listener-scoped knobs — along with the
session id and the request id — across every keep-alive and pipelined request in that
slot. An H1 connection's staleness window is the connection, not one request.
Narrowing it means giving the keep-alive reset in ConnectionH1::end_stream a
re-capture of its own, which is a separate change. §2.5, configure_admin_ops.md
§1.1 and the CHANGELOG all say so rather than letting the headline overstate.

Verification

cargo +nightly fmt --all -- --check, cargo build, cargo clippy --all-targets -- -D warnings, cargo test -p sozu-lib (1117 passed), -p sozu (113),
-p sozu-e2e --skip tests::fuzz_tests:: (447), RUSTFLAGS="--cfg tokio_unstable" cargo test/clippy -p sozu-sim, check_doc_citations.py --root . / --base /
--audit, RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features, and
cargo bench -p sozu-lib --bench h2_stream_table -- --test all exit 0.

The line shifts in mod.rs, stream.rs, h1.rs, router.rs and answers.rs moved
52 existing citations; each was re-anchored to the line its original text now sits on
and hand-audited against its prose. One of them landed on a number the base revision
used for different code (the #1447 class), and is cited by symbol instead.

Closes nothing on its own — #1340 stays open for Questions 6 and 12.

Question 7 of #1340 asked whether the H2 core freezes the
listener into an owned snapshot at construction, or keeps Rc<RefCell<L>>
and goes on taking live borrows on the write, reset and access-log paths.
It is neither: the capture is per request, taken when the request arrives,
and the staleness window it implies -- exactly one request -- is now stated
in LIFECYCLE.md and configure_admin_ops.md rather than left to emerge from
wherever the next listener.borrow() happened to sit.

Context::strict_sni_binding, Context::elide_x_real_ip and
Context::send_x_real_ip were the construction-time freeze already in the
tree, and all three are patchable, so an operator patch never reached an
open connection. They move into Context::create_stream, which
ConnectionH2::create_stream calls from its HEADERS branch.

The live borrows go the other way. Router::backend_from_request re-read
get_sticky_name after routing, so a request matched on the old cookie name
could be answered with a Set-Cookie under a new one; that read is gone and
the method no longer takes a listener handle. The six remaining get_answers
borrows on the datapath read Stream::answers instead, captured with the
rest. frontend_from_request (Question 6, still open) and get_tags (the
access-log fallback for a request that never finished routing) stay live on
purpose and are named in LIFECYCLE.md 2.5.

Stream::answers is a handle rather than a copy, because Template owns a
kawa::Kawa and cannot be cloned, so update_config now publishes a new
HttpAnswers under a new Rc instead of rewriting the one every in-flight
request holds. HttpAnswers::cluster_answers holds Rc<Template> so the
per-cluster overrides can be copied into the published registry; migrating
them with mem::take would empty the registry the in-flight requests still
hold and strip their custom pages mid-response.

Context::protocol is captured once per connection instead, and honestly so:
a listener's HTTP/HTTPS kind is fixed by its type and no patch can change
it. That retires the last datapath listener borrow in
ConnectionH2::begin_scheduler_pass.

HTTP/1.1 is not covered by the one-request window and LIFECYCLE.md 2.5 says
so: http.rs and https.rs call Context::create_stream once per H1 connection
and HttpContext::reset deliberately carries the listener-scoped knobs across
every keep-alive request in that slot, so an H1 connection's window is the
connection.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the fix/h2-listener-config-snapshot branch from d2c4471 to 80c7e53 Compare September 24, 2026 20:54
@FlorentinDUBOIS
FlorentinDUBOIS merged commit d4f6d07 into main Sep 24, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/h2-listener-config-snapshot branch September 24, 2026 21:45
FlorentinDUBOIS added a commit that referenced this pull request Sep 24, 2026
`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 added a commit that referenced this pull request Sep 24, 2026
)

`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]>
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