You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Part of the H2 sans-io extraction decision set. lib/src/protocol/mux/ holds 95 I/O and
ambient-state touchpoints: 26 mechanical, 55 structural, 14 requiring a maintainer decision
(h2.rs 53 / mod.rs 24 / connection.rs 9 / stream.rs 6 / router.rs 3). ConnectionH2<Front: SocketHandler>
carries 54 production socket references in h2.rs alone, and Context<L> holds pub pool: Weak<RefCell<Pool>>. The structural majority is the signal: this is not a mechanical
extraction.
No design is proposed here and no work is budgeted until the question below is answered. The goal of
the extraction is a deterministic simulator for H2 in the FoundationDB style described in doc/testing.md; every question below is a place where the current code reaches for I/O, the clock,
the allocator or a random source from inside what would become the pure core.
Question 6 — does the core include routing
mod.rs:1197self.router.connect(...). Does the core stop at ConnectionH2 + Context, leaving
Router, backend dialling and Rc<RefCell<dyn L7Proxy>> to the embedder — or include Router, with
backend selection expressed as a returned ConnectFrontend / ConnectBackend request?
Question 7 — listener configuration
mod.rs:443 listener borrows. Is the listener frozen into an owned config snapshot at construction —
which requires deciding what happens to an operator hot-reload mid-connection, since Sōzu's whole
premise is hot reconfiguration — or does the core keep Rc<RefCell<L>> and go on taking live borrows
on the write, reset and access-log paths?
Question 12 — backend handles and accounting
mod.rs:199Position::Client(String, Rc<RefCell<Backend>>, BackendStatus). Keep Rc<RefCell<Backend>> and go on mutating shared registry counters from the datapath, or hold an
opaque backend id and return the LIFECYCLE-invariant-14 accounting deltas for the embedder to apply?
Why these are one decision
These three draw the same line from three sides: 6 is whether routing is inside, 7 is whether
configuration is inside, 12 is whether backend state is inside. Answer them separately and the
perimeter ends up jagged — routing excluded but backend counters still mutated from the datapath,
say, which is neither a pure core nor an honest impure one.
Question 7 carries the product risk: freezing listener config at construction is the simplest core,
but hot reconfiguration is the reason this proxy exists, so the snapshot's staleness window needs an
explicit answer rather than an emergent one.
Q7 is a smaller question than it is framed as: the codebase has already chosen snapshot, and already written the staleness note
Measured against main at 5cb5395e. Q7 reads as an open "snapshot at construction vs. live borrow" policy question. In-tree, that policy has already been chosen for nine values, with the rationale written down — and the hot-reload staleness concern already has a documented, deliberate answer one layer up.
Already snapshotted at Context::new, on purpose
Four listener values are captured once (mod.rs:443-449): h2_stream_shrink_ratio, strict_sni_binding, elide_x_real_ip, send_x_real_ip. The field docs say why, explicitly — mod.rs:400-416, e.g. "captured once at Context::new so routing decisions on each stream avoid a per-stream listener.borrow()".
Five more are frozen at handshake rather than borrowed at all (mod.rs:394-433, seeded from https.rs): tls_server_name, tls_cert_names, tls_version, tls_cipher, tls_alpn.
The live borrows that remain
Eleven listener.borrow() sites in mux/ production code are on the datapath rather than at construction:
mod.rs:521 (create_stream), mod.rs:1181 and mod.rs:1380 (get_answers().clone())
Three of these are get_answers().clone(), which is a different shape of question from a scalar config read.
The staleness question already has an in-tree precedent answer
https.rs:574-599 is a ~25-line block headed "# Known race window (accepted risk)" that reasons through exactly this class: a resolver mutation interleaving with a handshake between two lookups, the single-threaded-worker invariant preventing simultaneous mutation but not interleaving between mio iterations. It concludes by keeping the second lookup and documenting the window honestly.
What that means for the decision
Q7 is not "decide a snapshot policy from scratch". It is "extend an existing, deliberate, documented snapshot policy to some of eleven remaining datapath borrows, and write the same kind of honest staleness note for the ones that move". That is still a maintainer call — which values may safely go stale for a connection's lifetime is a product question, not a mechanical one — but it is a materially smaller and better-anchored call than the issue currently implies.
Q6 and Q12 need nothing added; both are cleanly framed perimeter decisions. For the record, Q12's registry mutation really is spread across four files: connection.rs:392, :425-426, :449-450, mod.rs:886-888, :893, :984-993, :1032-1033, :1817, :1840-1841, h2.rs:4321-4322, h2.rs:5972-5975.
Decision — Q6, Q7 and Q12: narrow core, opaque backend id, config snapshotted per stream
Q6 — routing is OUTSIDE. The core stops at ConnectionH2 + Context. Router, backend dialling and Rc<RefCell<dyn L7Proxy>> stay with the embedder.
Q12 — opaque backend id.Rc<RefCell<Backend>> does not enter the core. Backends are held as an opaque id and the LIFECYCLE-invariant-14 accounting is returned as deltas for the embedder to apply. No registry counter is mutated from the datapath.
Q7 — owned config snapshot, re-taken at stream creation on HEADERS. No live listener borrows on the write, reset or access-log paths.
The issue asked for these three to be answered together so the perimeter does not come out jagged. They are: routing out, configuration owned, backend state out. The line is the same on all three sides.
The precedent is in-repo and already shipped
This is not a new shape for this codebase. lib/src/protocol/udp/ is already sans-io and already does exactly this:
udp/mod.rs:129 — the core emits Output::SelectBackend and the shell does the actual load balancing. udp/mod.rs:111 documents the reply path: "Reply to an earlier Output::SelectBackend: the shell resolved the...". That is Q6's answer, running in production today.
udp/mod.rs:110 — configuration arrives as ManagerInput::Config(ConfigEvent), an input event, not a live borrow. That is Q7's answer.
So the H2 perimeter is being aligned with the one this repository already chose for UDP, not invented. sim/tests/udp_simulation.rs is the proof it works: moonpool supplies the seeded runtime, the virtual clock and the seeded RNG, and the manager's outputs are a pure function of the seed.
Q7 — where the refresh happens, since H2 multiplexes
"Between requests" has no meaning on a busy H2 connection, so it was pinned explicitly: the connection holds the latest configuration, and each stream snapshots it at creation, on HEADERS, keeping that snapshot for the stream's lifetime.
The staleness window is therefore one stream's duration, and a hot reload reaches every stream opened after it, on every connection, immediately. The rejected alternative was a connection-level snapshot refreshed when the active stream count reaches zero: cheaper, and the whole connection would always agree on one configuration, but a long-lived H2 connection under steady load may never reach zero, so a reload could sit unapplied for hours on exactly the connections that carry the most traffic. Hot reconfiguration is the reason this proxy exists; an unbounded staleness window is not an acceptable price for a cheaper snapshot.
Two things the design has to state explicitly, because they are now reachable questions rather than emergent ones:
what a configuration change does to streams already open when it lands — under this decision, nothing; they finish on the configuration they started with;
whether a certificate or listener change that would have rejected the connection can be honoured mid-connection at all, or whether that remains a connection-lifetime property.
Q4 (metrics) recorded its decision as (c), a MetricEvent enum, blocked on this issue. That block is now lifted: with the perimeter narrow and the shell owning both core and socket, the shell wrapper carries the Drop-time gauge rebalance that h2.rs:1849 does today, one layer up where METRICS legitimately lives. The udp/ and tcp_preread/ cores already return Output::Metric(MetricEvent) and sim/tests/udp_simulation.rs already consumes those events.
Q6 is closer to done than this issue assumes: the ConnectionH2 / Context split already exists
Measured against origin/main at 7be659544163f0d780f8eb0666a25d992f5f8e23.
The decision recorded here is that the core stops at ConnectionH2 + Context, with routing and
load balancing outside. Reading the tree, that boundary is already the codebase's architecture, not
a change to make.LIFECYCLE.md §1.2 diagrams the split as existing structure. Context<L> already
owns streams: Vec<Stream>, pending_links, backend_streams, pool: Weak<RefCell<Pool>>, the
listener and the TLS SNI/cert-name snapshot; Context::create_stream already builds an owned HttpContext snapshot rather than holding a live reference, which is Q7's answer already
half-implemented.
What is left for Q6 is narrower than "move routing out": it is ConnectionH2 ceasing to need Front. That is Q10, answered in #1339, and it is the last step of the extraction sequence rather
than an independent piece of work.
router.rs is where the remaining reach concentrates, and there is substantially more of it than the
surveys suggested — 12 non-comment socket references rather than 3, and they are the least mechanical
kind: set_nodelay (setsockopt), register_socket (epoll registration, with its own CWE-400
fd-pressure rollback), and the raw TcpStream handoff from the connect path. None of those belong in
a protocol core; all of them stay in the I/O shell. But they should be budgeted for, because the
shell is where they land rather than where they disappear.
Q7 — one refinement to "snapshot at stream creation on HEADERS"
The decision holds. One consequence worth writing down: the stream-slot bookkeeping and per-stream
flow control cannot be separated cleanly, because handle_window_update_frame's stream-level arm
reads self.streams to resolve the slot. So the extraction takes connection-level flow control first,
then the H2 wire-level stream-slot map, and only then per-stream flow control. Attempting per-stream
flow control before the slot map is stable produces a tree where either the logic is duplicated across
the boundary or the extracted piece reaches back into an unextracted one.
Q12 — the accounting decision interacts with Q11
Opaque backend id with invariant-14 accounting returned as deltas is unchanged. Note that Q11 (#1339)
deletes Endpoint::socket(token) from the trait, since RTT is injected by the shell rather than read
by the core. That changes the Endpoint trait's shape for every implementor, not only the H2
ones — EndpointServer and EndpointClient in connection.rs both carry it, and h1.rs has three
inline copies of the same RTT pattern with no shared helper. Worth doing in one changeset rather than
discovering the H1 side later.
Maintainer decision on all three questions. They were answered together, as the issue asks, so the perimeter is drawn once rather than three times.
Q6 — routing is inside the core
The core includes Router, and backend selection is expressed as a returned request rather than performed in place: the core decides, and the embedder fulfils. Dialling, the L7Proxy handle and the session handle stay outside.
This is the larger of the two options and deliberately so. It is chosen for determinism: with selection inside, a simulator can drive load-balancing decisions reproducibly, which it cannot do while the decision happens behind an Rc<RefCell<dyn L7Proxy>> the harness does not control. The cost is accepted — every entry point's return vocabulary grows, and Router::connect's two trait-object parameters (Rc<RefCell<dyn ProxySession>>, Rc<RefCell<dyn L7Proxy>>) have to be dissolved rather than threaded through.
Q7 — listener configuration is snapshotted per stream, at HEADERS
Not frozen at construction, and not live-borrowed on the datapath. A stream captures the listener configuration it needs when its HEADERS arrive and runs to completion on that snapshot.
The staleness window is exactly one request. An operator reload mid-connection does not disturb streams already in flight; they finish on the configuration they started with, and the next stream on that connection sees the new one. The issue asked for this window to be explicit rather than emergent — this is that answer, and it is being written into LIFECYCLE.md alongside the implementation rather than left to be inferred.
A construction-time freeze was rejected because hot reconfiguration is the reason this proxy exists. Live borrows were rejected because they keep configuration inside the core while leaving it impure, which is the worst of both.
Q12 — opaque backend id, borrowed view in, accounting deltas out
Position::Client holds an opaque backend id. The core never holds Rc<RefCell<Backend>>.
Because Q6 puts routing inside, the core needs mutable backend load state to select at all — active_connections, active_requests, failures, connection_time: PeakEWMA, health, status. It gets them as a read-only view the embedder supplies at each selection point, and returns the chosen backend together with the LIFECYCLE invariant-14 accounting deltas for the embedder to apply.
Two alternatives were considered and rejected:
A core-owned mirror of backend state, synchronised by the embedder. Rejected for holding two copies of the same truth, where divergence under reload or health flap becomes a failure class that only appears in production.
Keeping Rc<RefCell<Backend>> and moving it inside with the router. Rejected because the core would still mutate shared registry counters from the datapath, so the perimeter would move outward without the core becoming pure — Q6's determinism argument would buy nothing.
The mechanism deliberately matches Q7's: a view in with a defined staleness, a result out. One discipline, applied twice, rather than two inventions.
Sequencing
Q7 needs nothing from the socket-boundary extraction and is in progress now. Q6 and Q12 both need S7 — "a request the embedder fulfils" and "deltas for the embedder to apply" each presuppose an embedder distinct from the core, and S7 is the step that creates one (H2Shell { core, socket }, ConnectionH2 dropping its Front parameter).
S3 landed in #1507. The remaining sequence is S4 and S6 in parallel, then S5, then S7. S5 is the highest-risk step: it lifts writable's (H2State::Error, Position::Server) and (H2State::GoAway, _) arms, and the GoAway arm's nested check fuses "rustls has buffered records" with "did the kernel accept the flush" — its own comment names it the primary truncation vector under HAProxy chaining. #1484's six ConnectionH2<FrontRustls> tests are the net for that step and must be run unchanged across it, never adapted to it.
Correction to the Q7 paragraph above, found while implementing it in #1513.
"The staleness window is exactly one request" is true for H2 and false for H1. I wrote it as an unqualified decision; it is not one.
Context::create_stream is called once per connection on the H1 path — lib/src/http.rs:168, lib/src/http.rs:355 and lib/src/https.rs:688, all at handshake — not once per request. HttpContext::reset (lib/src/protocol/kawa_h1/editor.rs:1202) then deliberately preserves the listener-scoped fields across every keep-alive and pipelined request in that slot. Its own comment says so — "set once at handshake, reused across every keep-alive request" — and it enforces the property with debug_assert!s on strict_sni_binding, elide_x_real_ip and send_x_real_ip, alongside the session and request identity.
So the contract is:
H2: the staleness window is one request. A stream captures at HEADERS; a reload reaches the next stream on the same connection.
H1: the staleness window is the connection. A reload reaches the next connection, not the next request on an open keep-alive connection.
The asymmetry is pre-existing behaviour, not something #1513 introduces, and widening into the H1 keep-alive reset would be a separate behaviour change rather than the capture-point move Q7 asked for. It is documented in LIFECYCLE.md §2.5, doc/configure_admin_ops.md §1.1 and the CHANGELOG so the headline does not overstate.
Two further things the implementation established, both of which sharpen the original question:
Three of the eleven datapath sites were already the rejected extreme.Context::strict_sni_binding, elide_x_real_ip and send_x_real_ip were frozen at Context::new with field docs saying so, and all three are patchable — so before this change a reload never reached an already-open connection at all. Moving them to the capture point is what makes the second half of the contract ("the next stream picks up the new configuration") true; without it, only the first half held.
A per-stream handle is not by itself a snapshot.update_config rewrote *self.answers.borrow_mut() in place, so an Rc captured at HEADERS was a renamed live borrow, not a snapshot of anything. Making it real required the listener to publish a new registry on reload. That was blocked by Template: !Clone — it owns a kawa::Kawa, upstream, no derive — and was resolved by putting the Rc on the template rather than the map (HashMap<ClusterId, BTreeMap<String, Rc<Template>>>), so cluster overrides copy into the published registry instead of being moved out of the one in-flight requests still hold.
Correction to the record: Q6 has two contradictory decisions on this issue, and the later one stands
This issue carries two decision comments that say opposite things about Q6. Both are still above. Flagging it explicitly because an implementer read the earlier one as authoritative and was right to ask, and because the next reader will hit the same thing.
The earlier comment says "Q6 — routing is OUTSIDE", and argues it from a real in-repo precedent: lib/src/protocol/udp/ already emits Output::SelectBackend from the core and does the load balancing in the shell, in production today.
The later comment says "Q6 — routing is inside the core", argued from determinism: with selection inside, a simulator can drive load-balancing decisions reproducibly, which it cannot while the decision happens behind an Rc<RefCell<dyn L7Proxy>> the harness does not control.
The later decision stands. Routing goes inside the core. The earlier comment is superseded on Q6 and should be read as historical from here.
Two things that decision does not change, and one it extends:
The udp/ precedent is not being left as a counter-example.udp/ is to be brought to the same shape rather than standing as the one protocol that does it the other way. A repository that routes inside the core for H2 and outside for UDP has two architectures and no rule, which is worse than either choice made consistently.
What stage 2 actually costs, recorded before it is written
Router::connect splits into a pure decision and an embedder-performed effect, the same protocol used four times in the socket-boundary extraction: the core answers Reuse { token } | Dial { cluster_id, backend, h2 } | Err, the embedder performs the dial, add_session, register_socket and the gauge block, then calls back. That is what dissolves Rc<RefCell<dyn ProxySession>> and Rc<RefCell<dyn L7Proxy>> rather than threading them through.
Two wrinkles found while implementing stage 1, neither anticipated by this issue:
The per-(cluster, source-IP) gate (track_cluster_ip) is a registry mutation sitting between two in-core steps — cluster resolution and backend selection. It becomes either a second returned step or part of the view.
Backend::try_connect both dials and calls inc_connections(). The view-in/request-out split has to pull those apart, or the view is stale by one for the very selection that caused the dial.
Q6's UDP half landed in #1529, merged as 747128ea. Selection now happens inside the manager, from a BackendSource view the embedder supplies.
Two findings from the implementation are worth keeping here, because both reframe what the inversion was.
Established never meant "socket open".on_backend_resolved set Establishedbefore emitting Output::OpenUpstream, so it has always meant "backend chosen". That is why FlowPhase::AwaitingBackend had nothing left to wait for once the core chose the backend — the waiting state was waiting on a decision, not on a socket.
Output::OpenUpstream was already the Q6 shape: the core decides, the embedder fulfils. The inversion collapsed a two-step into the one-step H2 already had. It was a simplification, not a demolition, which is not how it looked from the issue.
Behaviour change, accepted deliberately and documented as such. The retired wait window is also what the newest-wins one-slot buffer existed for. Today a client's opening burst of three datagrams reaches the backend as one — #1 buffered then overwritten by #2, overwritten by #3. After this change all three are forwarded. Fewer silently dropped datagrams on a bursty first exchange; recorded in CHANGELOG.md, udp/LIFECYCLE.md's phase diagram and doc/testing.md's worked example as behaviour rather than as an internal note.
Library API break. Five public items removed: Output::SelectBackend, ManagerInput::BackendResolved, ManagerInput::ClientDatagram's shape, UdpFlow::pending_payload, FlowPhase::AwaitingBackend. Deprecation was considered and rejected on measurement: supplying a borrowed view to the core requires changing either a public signature or a public variant's shape, and no deprecation avoids that one, so the break was unavoidable and taking it plainly produced a considerably smaller change than working around it.
Test accounting: 24 of 24 tests kept, none deleted, assertions 92 → 85, with 21 tests unchanged in assertion count — which is the evidence that retargeting the plumbing tests cost nothing, rather than a claim that it did not. Every removed assertion is labelled with a subject that demonstrably no longer exists. Model::check's four harness assertions never referred to the retired machinery, so every simulator assertion survives unchanged.
Seed→interleaving identity is lost for sim/tests/udp_simulation.rs, stated plainly in the PR so a differing seed result is not later read as a regression. It was never preservable by re-weighting the action table alone: the sim consumed a seeded random_bool(0.6) draw per select, so retiring the output removes draws from the RNG stream whatever the table does. Action::ChangeBackendSet takes index 1 at weight 16 so the cumulative walk keeps its dispatch boundaries, and the fuzz target's seven-way dispatch stays at seven.
Recommendation left for a maintainer, measured but not implemented: none of the 11 public types in lib/src/protocol/udp/ carries #[non_exhaustive]. Output and MetricEvent could take it today — they are produced by the core and only matched outside it. ManagerInput, ConfigEvent, ClusterConfig and FlowKey cannot without constructors, because sim and fuzz build them directly. A major boundary is the natural moment for that, and this one has passed.
Q6's H2 half is complete. #1527 merged as 223a4511, closing the sequence #1517 → #1519 → #1525 → #1527, with the UDP half in #1529.
Router::plan_connect now takes no L7Proxy handle at all. It answers ConnectStep::CheckIpLimit(ConnectResume), the embedder performs the consult and the track, and Router::plan_connect_resume finishes on the verdict.
Two properties the types enforce rather than comments.ConnectResume is taken by value, so a parked decision cannot be resumed twice. And the resumed call returns ConnectPlan, not ConnectStep, so a second gate consultation is unrepresentable. Both entries share one Router::decide_after_gate body, so the gated and ungated paths cannot drift. This is the same discipline as H2WritableStateTarget::Flush carrying no bool: make the bug impossible to write rather than document it.
Counts across the H2 half, mux/router.rs, production code references: Rc<RefCell<dyn ProxySession>>4 → 0, L7Proxy5 → 3.
It stops at 3, not 0, and that is a further stage rather than a shortfall. The remaining three are the import plus Router::backend_from_request and Router::get_backend_for_sticky_session, which still reach L7Proxy::backends. Reaching zero requires giving selection a borrowed view of backend load state — Q12 part 2, a fourth stage in an arc originally scoped as two, and a smaller prize than the stages before it. Recording it here so nobody reads a count stalled at 3 as work left undone.
The seen-red test targets the resume ordering, not the gate's verdict.an_admitted_stream_is_counted_before_the_decision_resumes drives the real sequence for two different frontend tokens from one source IP against a limit of one. Two tokens because the gate is idempotent within a token, so a same-token retry could never trip it and would have proved nothing — the obvious single-token version would have passed for the wrong reason. consult_ip_gate is a free function precisely so the test drives production code rather than a copy.
One citation was converted to a symbol rather than renumbered: Mux::timeout_inner's, because the number was one this changeset reused for different code — the #1447 class. That fix has since landed, so the gate would now pass either way; the symbol citation stays because citing a symbol the prose already names is better than citing a number.
Q6 and Q7 are answered and shipped. Q12's first half shipped in #1517. What remains under this issue is Q12 part 2 alone, unscheduled.
Q6, Q7 and the first half of Q12 are shipped. Q12 part 2 is the only thing left, and it needs your call.
Measured against origin/main at fa11f549c02722a378b983a0b3cb716187f54e14. Symbols, not line
numbers — the citations in this arc's issue bodies have drifted once already.
UDP: backend selection moved into the manager (Q6, applied to the second protocol)
Router::connect was 511 lines that decided, dialled and committed in one breath. It is now Router::plan_connect, which decides and returns a ConnectPlan; Mux::dial_backend, which
performs; and Router::commit_dialed, which records. The per-IP gate became ConnectStep::CheckIpLimit(ConnectResume), answered by consult_ip_gate and resumed through Router::plan_connect_resume.
Two shapes there are worth keeping, because they are the part that a later refactor could silently
undo:
ConnectResume is taken by value. A parked decision cannot be resumed twice.
plan_connect_resume returns ConnectPlan, not ConnectStep. A second gate consultation is
not merely forbidden, it is unrepresentable.
Where the perimeter actually sits now
Rc<RefCell<dyn ProxySession>> in router.rs: 0 production uses. The single remaining
occurrence of the type name is a doc comment recording why the router no longer needs one.
Rc<RefCell<dyn L7Proxy>>: 3, and it is worth naming them precisely rather than quoting a
count, because two of the three are the same call chain — the import, Router::backend_from_request
and the Router::get_backend_for_sticky_session it delegates to. The handle survives for exactly
one purpose: reaching proxy.borrow().backends() to pick a backend.
Q12 part 2 — proposed, not scheduled
That one purpose is the whole of what remains: a borrowed view of backend load state for
selection, the same shape #1525 gave cluster configuration. It would take router.rs from 3 to 0
and remove the last L7Proxy handle from the routing path.
I have deliberately not started it, and I would rather you ruled on it than have me assume:
it is a fourth stage in an arc that was scoped as two, and each stage so far has been smaller
than the one before it;
the prize is smaller than the stages that preceded it. Configuration is read once per connect and
is stable; backend load is read once per connect and is inherently live, so a borrowed view has
to answer what staleness is acceptable between the borrow and the dial — a question the
configuration view never had to answer;
the three remaining sites are a single chain, not a scatter. They are cheap to leave and cheap to
come back to.
Q6 and Q7 are answered, so nothing else in this issue is waiting on anyone. Keeping it open for
that one decision.
Q6, Q7 and both halves of Q12 are shipped (#1517, #1519, #1525, #1527, #1529, and #1550 for Q12 part 2, with #1516 as the Q10 prerequisite). router.rs no longer holds any production L7Proxy handle. The arc, including the deliberate BackendDialer shape chosen in #1550 instead of a read-only load view, is summarised in #1684. Closing as completed.
Activity
FlorentinDUBOIS commentedon Sep 19, 2026
Q7 is a smaller question than it is framed as: the codebase has already chosen snapshot, and already written the staleness note
Measured against
mainat5cb5395e. Q7 reads as an open "snapshot at construction vs. live borrow" policy question. In-tree, that policy has already been chosen for nine values, with the rationale written down — and the hot-reload staleness concern already has a documented, deliberate answer one layer up.Already snapshotted at
Context::new, on purposeFour listener values are captured once (
mod.rs:443-449):h2_stream_shrink_ratio,strict_sni_binding,elide_x_real_ip,send_x_real_ip. The field docs say why, explicitly —mod.rs:400-416, e.g. "captured once atContext::newso routing decisions on each stream avoid a per-streamlistener.borrow()".Five more are frozen at handshake rather than borrowed at all (
mod.rs:394-433, seeded fromhttps.rs):tls_server_name,tls_cert_names,tls_version,tls_cipher,tls_alpn.The live borrows that remain
Eleven
listener.borrow()sites inmux/production code are on the datapath rather than at construction:mod.rs:521(create_stream),mod.rs:1181andmod.rs:1380(get_answers().clone())h2.rs:2866(scheme),h2.rs:6521(get_answers().clone())router.rs:456,:457,:458(flood config, connection config, stream idle timeout),router.rs:680(frontend_from_request),router.rs:921(sticky_name)stream.rs:389Three of these are
get_answers().clone(), which is a different shape of question from a scalar config read.The staleness question already has an in-tree precedent answer
https.rs:574-599is a ~25-line block headed "# Known race window (accepted risk)" that reasons through exactly this class: a resolver mutation interleaving with a handshake between two lookups, the single-threaded-worker invariant preventing simultaneous mutation but not interleaving between mio iterations. It concludes by keeping the second lookup and documenting the window honestly.What that means for the decision
Q7 is not "decide a snapshot policy from scratch". It is "extend an existing, deliberate, documented snapshot policy to some of eleven remaining datapath borrows, and write the same kind of honest staleness note for the ones that move". That is still a maintainer call — which values may safely go stale for a connection's lifetime is a product question, not a mechanical one — but it is a materially smaller and better-anchored call than the issue currently implies.
Q6 and Q12 need nothing added; both are cleanly framed perimeter decisions. For the record, Q12's registry mutation really is spread across four files:
connection.rs:392,:425-426,:449-450,mod.rs:886-888,:893,:984-993,:1032-1033,:1817,:1840-1841,h2.rs:4321-4322,h2.rs:5972-5975.FlorentinDUBOIS commentedon Sep 21, 2026
Answered by the maintainer on 2026-09-21.
Decision — Q6, Q7 and Q12: narrow core, opaque backend id, config snapshotted per stream
Q6 — routing is OUTSIDE. The core stops at
ConnectionH2+Context. Router, backend dialling andRc<RefCell<dyn L7Proxy>>stay with the embedder.Q12 — opaque backend id.
Rc<RefCell<Backend>>does not enter the core. Backends are held as an opaque id and the LIFECYCLE-invariant-14 accounting is returned as deltas for the embedder to apply. No registry counter is mutated from the datapath.Q7 — owned config snapshot, re-taken at stream creation on HEADERS. No live listener borrows on the write, reset or access-log paths.
The issue asked for these three to be answered together so the perimeter does not come out jagged. They are: routing out, configuration owned, backend state out. The line is the same on all three sides.
The precedent is in-repo and already shipped
This is not a new shape for this codebase.
lib/src/protocol/udp/is already sans-io and already does exactly this:udp/mod.rs:129— the core emitsOutput::SelectBackendand the shell does the actual load balancing.udp/mod.rs:111documents the reply path: "Reply to an earlierOutput::SelectBackend: the shell resolved the...". That is Q6's answer, running in production today.udp/mod.rs:110— configuration arrives asManagerInput::Config(ConfigEvent), an input event, not a live borrow. That is Q7's answer.udp/manager.rs:173—pub fn handle_input(&mut self, input: ManagerInput<'_>, now: Instant), consistent with h2 sans-io: the clock, the timers and the flood-detector window (Q2, Q3, Q13) #1337.So the H2 perimeter is being aligned with the one this repository already chose for UDP, not invented.
sim/tests/udp_simulation.rsis the proof it works: moonpool supplies the seeded runtime, the virtual clock and the seeded RNG, and the manager's outputs are a pure function of the seed.Q7 — where the refresh happens, since H2 multiplexes
"Between requests" has no meaning on a busy H2 connection, so it was pinned explicitly: the connection holds the latest configuration, and each stream snapshots it at creation, on HEADERS, keeping that snapshot for the stream's lifetime.
The staleness window is therefore one stream's duration, and a hot reload reaches every stream opened after it, on every connection, immediately. The rejected alternative was a connection-level snapshot refreshed when the active stream count reaches zero: cheaper, and the whole connection would always agree on one configuration, but a long-lived H2 connection under steady load may never reach zero, so a reload could sit unapplied for hours on exactly the connections that carry the most traffic. Hot reconfiguration is the reason this proxy exists; an unbounded staleness window is not an acceptable price for a cheaper snapshot.
Two things the design has to state explicitly, because they are now reachable questions rather than emergent ones:
Consequence for #1341
Q4 (metrics) recorded its decision as (c), a
MetricEventenum, blocked on this issue. That block is now lifted: with the perimeter narrow and the shell owning both core and socket, the shell wrapper carries theDrop-time gauge rebalance thath2.rs:1849does today, one layer up whereMETRICSlegitimately lives. Theudp/andtcp_preread/cores already returnOutput::Metric(MetricEvent)andsim/tests/udp_simulation.rsalready consumes those events.FlorentinDUBOIS commentedon Sep 21, 2026
Q6 is closer to done than this issue assumes: the
ConnectionH2/Contextsplit already existsMeasured against
origin/mainat7be659544163f0d780f8eb0666a25d992f5f8e23.The decision recorded here is that the core stops at
ConnectionH2+Context, with routing andload balancing outside. Reading the tree, that boundary is already the codebase's architecture, not
a change to make.
LIFECYCLE.md§1.2 diagrams the split as existing structure.Context<L>alreadyowns
streams: Vec<Stream>,pending_links,backend_streams,pool: Weak<RefCell<Pool>>, thelistener and the TLS SNI/cert-name snapshot;
Context::create_streamalready builds an ownedHttpContextsnapshot rather than holding a live reference, which is Q7's answer alreadyhalf-implemented.
What is left for Q6 is narrower than "move routing out": it is
ConnectionH2ceasing to needFront. That is Q10, answered in #1339, and it is the last step of the extraction sequence ratherthan an independent piece of work.
router.rsis where the remaining reach concentrates, and there is substantially more of it than thesurveys suggested — 12 non-comment socket references rather than 3, and they are the least mechanical
kind:
set_nodelay(setsockopt),register_socket(epoll registration, with its own CWE-400fd-pressure rollback), and the raw
TcpStreamhandoff from the connect path. None of those belong ina protocol core; all of them stay in the I/O shell. But they should be budgeted for, because the
shell is where they land rather than where they disappear.
Q7 — one refinement to "snapshot at stream creation on HEADERS"
The decision holds. One consequence worth writing down: the stream-slot bookkeeping and per-stream
flow control cannot be separated cleanly, because
handle_window_update_frame's stream-level armreads
self.streamsto resolve the slot. So the extraction takes connection-level flow control first,then the H2 wire-level stream-slot map, and only then per-stream flow control. Attempting per-stream
flow control before the slot map is stable produces a tree where either the logic is duplicated across
the boundary or the extracted piece reaches back into an unextracted one.
Q12 — the accounting decision interacts with Q11
Opaque backend id with invariant-14 accounting returned as deltas is unchanged. Note that Q11 (#1339)
deletes
Endpoint::socket(token)from the trait, since RTT is injected by the shell rather than readby the core. That changes the
Endpointtrait's shape for every implementor, not only the H2ones —
EndpointServerandEndpointClientinconnection.rsboth carry it, andh1.rshas threeinline copies of the same RTT pattern with no shared helper. Worth doing in one changeset rather than
discovering the H1 side later.
FlorentinDUBOIS commentedon Sep 24, 2026
Maintainer decision on all three questions. They were answered together, as the issue asks, so the perimeter is drawn once rather than three times.
Q6 — routing is inside the core
The core includes
Router, and backend selection is expressed as a returned request rather than performed in place: the core decides, and the embedder fulfils. Dialling, theL7Proxyhandle and the session handle stay outside.This is the larger of the two options and deliberately so. It is chosen for determinism: with selection inside, a simulator can drive load-balancing decisions reproducibly, which it cannot do while the decision happens behind an
Rc<RefCell<dyn L7Proxy>>the harness does not control. The cost is accepted — every entry point's return vocabulary grows, andRouter::connect's two trait-object parameters (Rc<RefCell<dyn ProxySession>>,Rc<RefCell<dyn L7Proxy>>) have to be dissolved rather than threaded through.Q7 — listener configuration is snapshotted per stream, at HEADERS
Not frozen at construction, and not live-borrowed on the datapath. A stream captures the listener configuration it needs when its HEADERS arrive and runs to completion on that snapshot.
The staleness window is exactly one request. An operator reload mid-connection does not disturb streams already in flight; they finish on the configuration they started with, and the next stream on that connection sees the new one. The issue asked for this window to be explicit rather than emergent — this is that answer, and it is being written into
LIFECYCLE.mdalongside the implementation rather than left to be inferred.A construction-time freeze was rejected because hot reconfiguration is the reason this proxy exists. Live borrows were rejected because they keep configuration inside the core while leaving it impure, which is the worst of both.
Q12 — opaque backend id, borrowed view in, accounting deltas out
Position::Clientholds an opaque backend id. The core never holdsRc<RefCell<Backend>>.Because Q6 puts routing inside, the core needs mutable backend load state to select at all —
active_connections,active_requests,failures,connection_time: PeakEWMA,health,status. It gets them as a read-only view the embedder supplies at each selection point, and returns the chosen backend together with the LIFECYCLE invariant-14 accounting deltas for the embedder to apply.Two alternatives were considered and rejected:
Rc<RefCell<Backend>>and moving it inside with the router. Rejected because the core would still mutate shared registry counters from the datapath, so the perimeter would move outward without the core becoming pure — Q6's determinism argument would buy nothing.The mechanism deliberately matches Q7's: a view in with a defined staleness, a result out. One discipline, applied twice, rather than two inventions.
Sequencing
Q7 needs nothing from the socket-boundary extraction and is in progress now. Q6 and Q12 both need S7 — "a request the embedder fulfils" and "deltas for the embedder to apply" each presuppose an embedder distinct from the core, and S7 is the step that creates one (
H2Shell { core, socket },ConnectionH2dropping itsFrontparameter).S3 landed in #1507. The remaining sequence is S4 and S6 in parallel, then S5, then S7. S5 is the highest-risk step: it lifts
writable's(H2State::Error, Position::Server)and(H2State::GoAway, _)arms, and the GoAway arm's nested check fuses "rustls has buffered records" with "did the kernel accept the flush" — its own comment names it the primary truncation vector under HAProxy chaining. #1484's sixConnectionH2<FrontRustls>tests are the net for that step and must be run unchanged across it, never adapted to it.FlorentinDUBOIS commentedon Sep 24, 2026
Correction to the Q7 paragraph above, found while implementing it in #1513.
"The staleness window is exactly one request" is true for H2 and false for H1. I wrote it as an unqualified decision; it is not one.
Context::create_streamis called once per connection on the H1 path —lib/src/http.rs:168,lib/src/http.rs:355andlib/src/https.rs:688, all at handshake — not once per request.HttpContext::reset(lib/src/protocol/kawa_h1/editor.rs:1202) then deliberately preserves the listener-scoped fields across every keep-alive and pipelined request in that slot. Its own comment says so — "set once at handshake, reused across every keep-alive request" — and it enforces the property withdebug_assert!s onstrict_sni_binding,elide_x_real_ipandsend_x_real_ip, alongside the session and request identity.So the contract is:
The asymmetry is pre-existing behaviour, not something #1513 introduces, and widening into the H1 keep-alive reset would be a separate behaviour change rather than the capture-point move Q7 asked for. It is documented in
LIFECYCLE.md§2.5,doc/configure_admin_ops.md§1.1 and the CHANGELOG so the headline does not overstate.Two further things the implementation established, both of which sharpen the original question:
Three of the eleven datapath sites were already the rejected extreme.
Context::strict_sni_binding,elide_x_real_ipandsend_x_real_ipwere frozen atContext::newwith field docs saying so, and all three are patchable — so before this change a reload never reached an already-open connection at all. Moving them to the capture point is what makes the second half of the contract ("the next stream picks up the new configuration") true; without it, only the first half held.A per-stream handle is not by itself a snapshot.
update_configrewrote*self.answers.borrow_mut()in place, so anRccaptured at HEADERS was a renamed live borrow, not a snapshot of anything. Making it real required the listener to publish a new registry on reload. That was blocked byTemplate: !Clone— it owns akawa::Kawa, upstream, no derive — and was resolved by putting theRcon the template rather than the map (HashMap<ClusterId, BTreeMap<String, Rc<Template>>>), so cluster overrides copy into the published registry instead of being moved out of the one in-flight requests still hold.fix(mux): capture listener configuration per request, not per connection
fix(mux): capture listener configuration per request, not per connect…
FlorentinDUBOIS commentedon Sep 25, 2026
Correction to the record: Q6 has two contradictory decisions on this issue, and the later one stands
This issue carries two decision comments that say opposite things about Q6. Both are still above. Flagging it explicitly because an implementer read the earlier one as authoritative and was right to ask, and because the next reader will hit the same thing.
lib/src/protocol/udp/already emitsOutput::SelectBackendfrom the core and does the load balancing in the shell, in production today.ConnectionH2ceasing to needFront, which is Q10. That is now done, in refactor(mux-h2): drop ConnectionH2's Front parameter into an H2Shell (#1339, Q10) #1516.Rc<RefCell<dyn L7Proxy>>the harness does not control.The later decision stands. Routing goes inside the core. The earlier comment is superseded on Q6 and should be read as historical from here.
Two things that decision does not change, and one it extends:
udp/precedent is not being left as a counter-example.udp/is to be brought to the same shape rather than standing as the one protocol that does it the other way. A repository that routes inside the core for H2 and outside for UDP has two architectures and no rule, which is worse than either choice made consistently.What stage 2 actually costs, recorded before it is written
Router::connectsplits into a pure decision and an embedder-performed effect, the same protocol used four times in the socket-boundary extraction: the core answersReuse { token } | Dial { cluster_id, backend, h2 } | Err, the embedder performs the dial,add_session,register_socketand the gauge block, then calls back. That is what dissolvesRc<RefCell<dyn ProxySession>>andRc<RefCell<dyn L7Proxy>>rather than threading them through.Two wrinkles found while implementing stage 1, neither anticipated by this issue:
(cluster, source-IP)gate (track_cluster_ip) is a registry mutation sitting between two in-core steps — cluster resolution and backend selection. It becomes either a second returned step or part of the view.Backend::try_connectboth dials and callsinc_connections(). The view-in/request-out split has to pull those apart, or the view is stale by one for the very selection that caused the dial.refactor(mux): hold backends as an opaque id and return accounting de…
refactor(mux): split Router::connect into a plan and an embedder-perf…
refactor(mux): split Router::connect into a plan and an embedder-perf…
refactor(mux): read cluster configuration from a borrowed routing view
refactor(mux): make the per-IP limit gate a returned step
refactor(mux): split Router::connect into a plan and an embedder-perf…
refactor(mux): read cluster configuration from a borrowed routing view
refactor(mux): make the per-IP limit gate a returned step
refactor(udp): move backend selection into the manager (#1529)
FlorentinDUBOIS commentedon Sep 25, 2026
Q6's UDP half landed in #1529, merged as
747128ea. Selection now happens inside the manager, from aBackendSourceview the embedder supplies.Two findings from the implementation are worth keeping here, because both reframe what the inversion was.
Establishednever meant "socket open".on_backend_resolvedsetEstablishedbefore emittingOutput::OpenUpstream, so it has always meant "backend chosen". That is whyFlowPhase::AwaitingBackendhad nothing left to wait for once the core chose the backend — the waiting state was waiting on a decision, not on a socket.Output::OpenUpstreamwas already the Q6 shape: the core decides, the embedder fulfils. The inversion collapsed a two-step into the one-step H2 already had. It was a simplification, not a demolition, which is not how it looked from the issue.Behaviour change, accepted deliberately and documented as such. The retired wait window is also what the newest-wins one-slot buffer existed for. Today a client's opening burst of three datagrams reaches the backend as one — #1 buffered then overwritten by #2, overwritten by #3. After this change all three are forwarded. Fewer silently dropped datagrams on a bursty first exchange; recorded in
CHANGELOG.md,udp/LIFECYCLE.md's phase diagram anddoc/testing.md's worked example as behaviour rather than as an internal note.Library API break. Five public items removed:
Output::SelectBackend,ManagerInput::BackendResolved,ManagerInput::ClientDatagram's shape,UdpFlow::pending_payload,FlowPhase::AwaitingBackend. Deprecation was considered and rejected on measurement: supplying a borrowed view to the core requires changing either a public signature or a public variant's shape, and no deprecation avoids that one, so the break was unavoidable and taking it plainly produced a considerably smaller change than working around it.Test accounting: 24 of 24 tests kept, none deleted, assertions 92 → 85, with 21 tests unchanged in assertion count — which is the evidence that retargeting the plumbing tests cost nothing, rather than a claim that it did not. Every removed assertion is labelled with a subject that demonstrably no longer exists.
Model::check's four harness assertions never referred to the retired machinery, so every simulator assertion survives unchanged.Seed→interleaving identity is lost for
sim/tests/udp_simulation.rs, stated plainly in the PR so a differing seed result is not later read as a regression. It was never preservable by re-weighting the action table alone: the sim consumed a seededrandom_bool(0.6)draw per select, so retiring the output removes draws from the RNG stream whatever the table does.Action::ChangeBackendSettakes index 1 at weight 16 so the cumulative walk keeps its dispatch boundaries, and the fuzz target's seven-way dispatch stays at seven.Recommendation left for a maintainer, measured but not implemented: none of the 11 public types in
lib/src/protocol/udp/carries#[non_exhaustive].OutputandMetricEventcould take it today — they are produced by the core and only matched outside it.ManagerInput,ConfigEvent,ClusterConfigandFlowKeycannot without constructors, becausesimandfuzzbuild them directly. A major boundary is the natural moment for that, and this one has passed.refactor(mux): read cluster configuration from a borrowed routing view (
refactor(mux): make the per-IP limit gate a returned step
refactor(mux): make the per-IP limit gate a returned step (#1527)
FlorentinDUBOIS commentedon Sep 25, 2026
Q6's H2 half is complete. #1527 merged as
223a4511, closing the sequence #1517 → #1519 → #1525 → #1527, with the UDP half in #1529.Router::plan_connectnow takes noL7Proxyhandle at all. It answersConnectStep::CheckIpLimit(ConnectResume), the embedder performs the consult and the track, andRouter::plan_connect_resumefinishes on the verdict.Two properties the types enforce rather than comments.
ConnectResumeis taken by value, so a parked decision cannot be resumed twice. And the resumed call returnsConnectPlan, notConnectStep, so a second gate consultation is unrepresentable. Both entries share oneRouter::decide_after_gatebody, so the gated and ungated paths cannot drift. This is the same discipline asH2WritableStateTarget::Flushcarrying nobool: make the bug impossible to write rather than document it.Counts across the H2 half,
mux/router.rs, production code references:Rc<RefCell<dyn ProxySession>>4 → 0,L7Proxy5 → 3.It stops at 3, not 0, and that is a further stage rather than a shortfall. The remaining three are the import plus
Router::backend_from_requestandRouter::get_backend_for_sticky_session, which still reachL7Proxy::backends. Reaching zero requires giving selection a borrowed view of backend load state — Q12 part 2, a fourth stage in an arc originally scoped as two, and a smaller prize than the stages before it. Recording it here so nobody reads a count stalled at 3 as work left undone.The seen-red test targets the resume ordering, not the gate's verdict.
an_admitted_stream_is_counted_before_the_decision_resumesdrives the real sequence for two different frontend tokens from one source IP against a limit of one. Two tokens because the gate is idempotent within a token, so a same-token retry could never trip it and would have proved nothing — the obvious single-token version would have passed for the wrong reason.consult_ip_gateis a free function precisely so the test drives production code rather than a copy.One citation was converted to a symbol rather than renumbered:
Mux::timeout_inner's, because the number was one this changeset reused for different code — the #1447 class. That fix has since landed, so the gate would now pass either way; the symbol citation stays because citing a symbol the prose already names is better than citing a number.Q6 and Q7 are answered and shipped. Q12's first half shipped in #1517. What remains under this issue is Q12 part 2 alone, unscheduled.
FlorentinDUBOIS commentedon Sep 25, 2026
Q6, Q7 and the first half of Q12 are shipped. Q12 part 2 is the only thing left, and it needs your call.
Measured against
origin/mainatfa11f549c02722a378b983a0b3cb716187f54e14. Symbols, not linenumbers — the citations in this arc's issue bodies have drifted once already.
What landed
Router::connectsplit into a plan and an embedder-performed dial (Q6)Router::connectwas 511 lines that decided, dialled and committed in one breath. It is nowRouter::plan_connect, which decides and returns aConnectPlan;Mux::dial_backend, whichperforms; and
Router::commit_dialed, which records. The per-IP gate becameConnectStep::CheckIpLimit(ConnectResume), answered byconsult_ip_gateand resumed throughRouter::plan_connect_resume.Two shapes there are worth keeping, because they are the part that a later refactor could silently
undo:
ConnectResumeis taken by value. A parked decision cannot be resumed twice.plan_connect_resumereturnsConnectPlan, notConnectStep. A second gate consultation isnot merely forbidden, it is unrepresentable.
Where the perimeter actually sits now
Rc<RefCell<dyn ProxySession>>inrouter.rs: 0 production uses. The single remainingoccurrence of the type name is a doc comment recording why the router no longer needs one.
Rc<RefCell<dyn L7Proxy>>: 3, and it is worth naming them precisely rather than quoting acount, because two of the three are the same call chain — the import,
Router::backend_from_requestand the
Router::get_backend_for_sticky_sessionit delegates to. The handle survives for exactlyone purpose: reaching
proxy.borrow().backends()to pick a backend.Q12 part 2 — proposed, not scheduled
That one purpose is the whole of what remains: a borrowed view of backend load state for
selection, the same shape #1525 gave cluster configuration. It would take
router.rsfrom 3 to 0and remove the last
L7Proxyhandle from the routing path.I have deliberately not started it, and I would rather you ruled on it than have me assume:
than the one before it;
is stable; backend load is read once per connect and is inherently live, so a borrowed view has
to answer what staleness is acceptable between the borrow and the dial — a question the
configuration view never had to answer;
come back to.
Q6 and Q7 are answered, so nothing else in this issue is waiting on anyone. Keeping it open for
that one decision.
refactor(mux): select and dial through a BackendDialer lent for one call
refactor(mux): select and dial through a BackendDialer lent for one c…
refactor(lib): remove L7Proxy::deregister_socket (#1618)
FlorentinDUBOIS commentedon Sep 29, 2026
Q6, Q7 and both halves of Q12 are shipped (#1517, #1519, #1525, #1527, #1529, and #1550 for Q12 part 2, with #1516 as the Q10 prerequisite).
router.rsno longer holds any productionL7Proxyhandle. The arc, including the deliberateBackendDialershape chosen in #1550 instead of a read-only load view, is summarised in #1684. Closing as completed.docs(mux): name the remaining L7Proxy::backends caller (#1693)