Repository navigation
Description
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 4 — metrics
h2.rs:2568 and 38 real metric call sites in h2.rs (30 counters, 8 gauges; ~64 across
h2 + mod + stream + connection). Do they
- (a) stay as thread-local METRICS writes inside the core,
- (b) move behind an injected sink trait, or
- (c) become part of the core's returned output?
Only three logical gauges exist: the ConnectionH2 triple emitted as signed deltas against
last_gauge_snapshot, plus http.active_requests. Timing is already option (c) —
SessionMetrics accumulates in-core and flushes at lib.rs:1455-1487. No metric is read back to
drive behaviour (grep -rn "METRICS" lib/src/protocol/ → 0), so (c) is not blocked on that.
The Drop-time gauge rebalance at h2.rs:1849 is the only metrics Drop in lib/src/; if it is
forgotten the aggregate leaks upward permanently and silently, with no resync and no assertion.
Decision: (c), scoped to a MetricEvent enum — but blocked on #1340 and not to be
implemented before it. Under a core/shell split the shell owns both core and socket, so the shell
wrapper carries the Drop that exists today, one layer up where METRICS legitimately lives; RAII
is not given up. The binding precedent is in-repo, not from other proxies: protocol/udp/ and
tcp_preread/ are already sans-io, have zero metric sites, and return
Output::Metric(MetricEvent) — and sim/tests/udp_simulation.rs:142-144, the deterministic
simulator this extraction exists to enable, consumes those events. (b) is a detour: it adds a
generic to four types, rewrites 38 sites, and must be unwound for (c).
(a) remains correct until the split lands. Nothing to do now.
Question 5 — logging context
h2.rs:69 log_context!, 109 real expansions in h2.rs (174 across mux/). Keep it, or
snapshot the peer address at construction?
Correction to this issue's original text, which was wrong on three counts:
- It claimed a
getpeernamesyscall and a wall-clock read per expansion. The syscall is real
(h2.rs:80→ mio →std→getpeername(2), no memoization). There is no clock read in the
macro;logging::now()belongs to the logger and fires once per emitted line for every log in
the proxy, so this change does not touch it. - It implied a hot path. Zero of the expansions are unconditional per-frame or per-request: 51
areerror!, 9warn!, 1info!, 22debug!, 25trace!— and 47 do not exist in a release
binary at all. The cost is also not paid when the level filters the line, because
_log_enabled!returns before$argsis evaluated. - It said 176 call sites of
h2.rs:69. That figure is all ofmux/;h2.rshas 109.
So the performance argument is void and should not be used to justify this change.
The real defect is observability. getpeername returns ENOTCONN after a peer RST, so error lines —
exactly the ones an operator reads during an incident — render peer=None. Backend-connect failures
do the same. And on a PROXY-protocol frontend the HTTPS line shows the real client while the
MUX-H2 line shows the load balancer, for the same ULID.
The maintainers already ruled on this one layer down: router.rs:444-450 caches the backend address
into SessionTcpStream::configured_peer precisely "so lines fired on ECONNREFUSED still render
peer=". h2.rs:80 reaches past that cache to the raw TcpStream. That is an
inconsistency, not a deliberate choice.
Decision: snapshot, via a peer_addr() method on the existing SocketHandler trait — the same
shape as SocketHandler::session_ulid(), which was added for exactly this kind of log-prefix need.
Not an h2-only field and not a twelfth parameter on a constructor already carrying
#[allow(clippy::too_many_arguments)]. SessionTcpStream returns configured_peer or the live
lookup; FrontRustls gains the peer field it currently lacks, which is the only handler missing one.
~25 lines, zero of the 174 call sites touched, lib/tests/log_layout.rs unaffected.
This ships now, independently of #1340 and of question 4.
Activity
FlorentinDUBOIS commentedon Sep 19, 2026
Q5 is being fixed (#1360); Q4 stays decided-and-blocked. Plus some count corrections.
Q5 — the live
getpeername(2)in the H2 log macrosFixed in #1360.
SocketHandlergainspeer_addr(),FrontRustlsgains theconfigured_peerfield it was the only handler to lack, and both macros read the snapshot.Two corrections to this issue's own framing, both measured:
log_context_stream!has zero production callers.grep -c 'log_context_stream!('overh2.rsreturns 1, and that 1 is a test. The macro carries#[allow(unused_macros)]. So "two lines" is literally true but onlylog_context!is live today; the second was a latent defect, not a shipping one. Both were fixed anyway — leaving twin macros on different clocks is how they drift apart.router.rs:449already seedsconfigured_peerwith the cluster-configured backend address, so an H2 error line after a failedconnect()now names the backend where it previously renderedpeer=None. That is the exact caseSessionTcpStream::configured_peerwas invented for, and the H2 macros were reading past it.And one correction to a claim that was wrong rather than incomplete, worth recording because it nearly shipped: a draft of the changeset told operators the
MuxClearPROXY path changed too. It does not.Connection::new_h2_serverhas exactly one caller,https.rs:702, on the TLS ALPN branch, and h2c is deliberately unimplemented on the cleartext listener (http.rs:710-728), so aMuxClearsession has noMUX-H2frontend line at all. Its frontend renders throughMUX-H1(h1.rs:54,:83), untouched. The draft had even citedhttp.rs:330as its evidence — a line whose immediate neighbour,new_h1_serverathttp.rs:328, refutes it.A known divergence remains, documented rather than papered over: the
SOCKETline of a TLS frontend still shows the kernel's peer, so on a PROXY frontend it disagrees with theMUX-H2line. That is an artefact ofFrontRustlshaving carried no cached address until now, not a layer boundary — every otherSOCKETline already prefersconfigured_peer(socket.rs:177). Aligningsocket.rs:133is a one-word change that compiles and leaves the suite green, but nothing asserts thepeer=slot of aSOCKETline, so it needs its own changeset with its own test.Q4 — metrics across the boundary: decision (c) holds, and the block on #1340 is right
Nothing to do here, and every supporting claim in the issue checks out against
main:grep METRICS lib/src/protocol/returns 2 hits, both inh2.rstest code. Production reads: zero.Dropgauge rebalance is real and is the sole decrement site (h2.rs:1864-1867→release_connection_gauges), and it is the only metric-macroDropinlib/src/— the others (backends.rs,pool.rs,splice.rs,timer.rs,metrics/writer.rs) usepush_event, an atomic,libc::closeanddebug!respectively.lib/src/protocol/udp/has zero metric macro sites and emitsOutput::Metric(MetricEvent)instead, consumed by the shell.Count corrections while here: 39 production metric-macro sites in
h2.rs(12count!+ 18incr!+ 9gauge_add!), not 38 — the counter figure of 30 is exact, the gauge figure is 9 not 8.log_context!(self)expands at 110 sites, not 109. Log levels inh2.rsare error 53 / warn 13 / info 2 / debug 23 / trace 29, against the 51/9/1/22/25 recorded here.FlorentinDUBOIS commentedon Sep 21, 2026
Reviewed with the maintainer on 2026-09-21. Both questions here already carried decisions; this records their status rather than changing them.
Q4 — metrics: decision (c) stands, and the block is now lifted
The recorded decision is (c), scoped to a
MetricEventenum, explicitly blocked on #1340. #1340 was answered on 2026-09-21: narrow core, routing and backend dialling outside, backends held as an opaque id with accounting returned as deltas.That is the condition this decision was waiting on. With the shell owning both the core and the socket, the shell wrapper carries the
Drop-time gauge rebalance thath2.rs:1849performs today, one layer up whereMETRICSlegitimately lives — RAII is not given up, which was the stated worry.Nothing to do before the split lands; (a) remains correct until then. The point is that (c) is no longer waiting on anyone.
Q5 — log context: decision stands, and this one ships now
Snapshot the peer, via a
peer_addr()method on the existingSocketHandlertrait — the same shape asSocketHandler::session_ulid(), which was added for exactly this kind of log-prefix need.This is independent of #1340 and of Q4, and it is the only part of the H2 sans-io decision set that is code rather than architecture. It is now the actionable remainder of this issue.
Restating the two things the original issue text got wrong, since they are the reason this looks like a performance change and is not:
h2.rsare unconditional per-frame or per-request, 47 do not exist in a release binary, and_log_enabled!returns before$argsis evaluated, so a filtered line costs nothing. There is also no clock read in the macro.getpeernamereturnsENOTCONNafter a peer RST, so the error lines an operator reads during an incident renderpeer=None. On a PROXY-protocol frontend theHTTPSline shows the real client while theMUX-H2line shows the load balancer, for the same ULID.The maintainers already ruled on this one layer down:
router.rs:444-450caches the backend address intoSessionTcpStream::configured_peerprecisely so lines fired onECONNREFUSEDstill renderpeer=<backend>.h2.rs:80reaches past that cache to the rawTcpStream. That is an inconsistency, not a deliberate choice, which is why this is worth fixing independently of the extraction.Scope as recorded:
SessionTcpStreamreturnsconfigured_peeror the live lookup,FrontRustlsgains the peer field it is the only handler missing, ~25 lines, zero of the 174 call sites touched,lib/tests/log_layout.rsunaffected.FlorentinDUBOIS commentedon Sep 21, 2026
Correcting my previous comment on Q5. It is wrong, and in the way that matters most: Q5 has already shipped.
I wrote that the snapshot decision "ships now" and is "the actionable remainder of this issue". It landed on 2026-09-19 in #1360, fix(h2): render the session peer, not a live getpeername(2), merged as
c8f8b92f.Verified against
origin/mainatf798fdf5:socket.rs:84is the trait method; the three implementations are the rawTcpStream(live lookup),SessionTcpStream(configured_peerwith a live fallback) andFrontRustls(the field it was the only handler to lack). Thelog_context!/log_context_stream!macros inh2.rsnow read$self.socket.peer_addr(); nosocket_ref().peer_addr().ok()remains in either. It shipped exactly as the decision specified, including theFrontRustlsfield seeded fromHttpsSession::peer_addressrather thanstream.peer_addr()— which is the part that actually fixes the PROXY-protocol case.Why I got it wrong. I read the repository through a working tree that was 65 commits behind
origin/main(9ef85148vsf798fdf5), sogrepfound nofn peer_addrand theh2.rsmacro still showed the livegetpeername(2). Both were true in September but had been fixed since. I have fast-forwarded the checkout and re-verified every fact in my comments on #1336, #1338, #1340 and #1341 againstf798fdf5.The rest of my previous comment stands and was re-checked at the current revision: Q4's decision (c) is unchanged, and its block on #1340 is genuinely lifted now that #1340 is answered.
There is one documented leftover from #1360 worth keeping visible, since it is the kind of thing that gets lost once an issue reads as done: the
SOCKETline of a TLS frontend still renders the kernel peer. Every otherSOCKETline already prefersconfigured_peer. That is an artefact ofFrontRustlshaving carried no cached address before #1360, not a layer boundary. Aligning it is a one-word change that compiles green — which is precisely why it needs its own test rather than a quiet edit, because nothing currently asserts that slot.So this issue's remaining content is Q4, which is architecture gated on the extraction, plus that one-line
SOCKETdivergence. No outstanding decision.FlorentinDUBOIS commentedon Sep 21, 2026
Q4 is unblocked; Q11's answer changes the trait Q4's accounting travels through
Measured against
origin/mainat7be659544163f0d780f8eb0666a25d992f5f8e23.Q4's decision — (c), a
MetricEventthe core emits rather than mutating a shared registry from thedatapath — was recorded as blocked on #1340 being answered. #1340 is answered and #1339 has now
settled the boundary itself, so the block is gone.
Two things from the boundary work bear directly on this issue.
The metric surface is large and mostly mechanical, with a small structural remainder.
mux/carries roughly 236 metric-macro sites and roughly 380 log/log-context sites. The macros themselves
touch no socket, so the bulk moves by mechanical substitution. The structural remainder is the
log-context macros:
h2.rs'slog_context!interpolates$self.socket.peer_addr()alongside theconnection's state, so roughly fifteen sites need the peer address supplied into the core rather
than read live. That is the same class of change Q5 already made once.
Q5's fix is the precedent for how the shell supplies it.
SocketHandler::peer_addr()prefers thecached
configured_peerover a livegetpeername(2), with the documented reason thatgetpeernamereturns
ENOTCONNonce the peer has reset — precisely when an operator is reading the error log. Thebyte-in/byte-out core takes the same value as injected data. No new mechanism is needed; the existing
one moves one layer out.
And a known divergence from Q5 is still open and now has a natural home. My earlier comment
recorded that the
SOCKETline of a TLS frontend still shows the kernel's peer, so on a PROXYfrontend it disagrees with the
MUX-H2line — an artefact ofFrontRustlshaving carried no cachedaddress until #1360, not a layer boundary. Aligning it is a one-word change that compiles and leaves
the suite green, but nothing asserts the
peer=slot of aSOCKETline, so it needs its own test.The differential layer's scenario/oracle machinery is the place that test becomes cheap to write,
because the expected peer value comes from the scenario's own setup rather than from what Sōzu
reports.
Keeping this issue open until the
MetricEventwork actually lands.fix(mux-h1): render the cached session peer instead of a live getpeer…
FlorentinDUBOIS commentedon Sep 25, 2026
Correction to the last comment: the TLS
SOCKET-line divergence is already closed.That comment recorded it as still open and gave it a home in the differential layer's scenario machinery. Verified on
mainat6d6640bf,lib/src/socket.rs:146now reads:fully qualified, so a TLS frontend's
SOCKETline prefersconfigured_peerlike every other one. The concern that nothing asserted that slot was also addressed —socket.rscarrieslog_socket_context_renders_the_cached_peer_when_the_live_lookup_fails, with a "To SEE THIS RED" recipe naming the exact substitution back topeer = $self.socket_ref().peer_addr().ok(),.So this issue's remaining content is Q4 alone.
Two things found while confirming that, both the same defect class as Q5 and neither named anywhere in this issue:
lib/src/protocol/mux/mod.rs:64and:91—log_context!andlog_context_lite!renderpeer = $self.frontend.socket().peer_addr().ok(), which resolves to mio's inherent method rather thanSocketHandler::peer_addr. Two production sites that asocket_ref().peer_addr()grep cannot find, which is why every survey of this defect has missed them.lib/src/protocol/mux/h1.rs:168—ConnectionH1'sDebugstill hands mio'sDebuga socket, rendering a local address, a peer address and a file descriptor. That is exactly what refactor(mux-h2): render the peer address where Debug named the socket #1501 changed on the H2 side and did not carry to H1.The first of those bears directly on Q4's structural remainder: the last comment estimated "roughly fifteen sites need the peer address supplied into the core rather than read live", counted from
h2.rs's macros. These two are additional, and they sit inmod.rs— which is the file the core/shell split has been moving. Worth folding into theMetricEventchangeset's scope rather than discovering mid-way.Also worth recording against the same comment: its "roughly 236 metric-macro sites in
mux/" does not reproduce today. Countingcount!,incr!,gauge_add!andtime!overlib/src/protocol/mux/at6d6640bfgives 116. The gap is large enough that whoever takes Q4 should re-measure with the macro list stated, rather than inherit either number.refactor(mux-h2): return the connection gauges as MetricEvents
refactor(mux-h2): return the connection gauges as MetricEvents
refactor(mux-h2): return the connection gauges as MetricEvents (#1530)
refactor(mux-h2): return the connection counters as MetricEvents
refactor(mux-h2): return the connection counters as MetricEvents (#1532)
refactor(mux-h2): return the H2-only helpers' metrics as MetricEvents
FlorentinDUBOIS commentedon Sep 25, 2026
Reopened. This was closed by accident at 15:11:51 when #1530 merged, and the mechanism is worth recording because it is a trap anyone can walk into.
#1530's body contains the sentence:
That sentence was written to prevent this close. GitHub's keyword parser does not understand negation — it sees
close #1341and acts. Writing "does not close #X" in a PR body closes #X. The safe phrasing is to avoid the keyword entirely: "#1341 stays open", or "addresses part of #1341".Q4 is not finished; the remaining work is listed at the bottom of this comment.
Three measurement corrections, all verified against the tree
The site count is 102, not 116 or 236.
lib/src/metrics/mod.rsdeclares seven metric macros, not four:count!,incr!,decr!,gauge!,gauge_add!,time!,record_backend_metrics!. Overlib/src/protocol/mux/, counting code references with comments, doc comments and string literals masked and#[cfg(test)]spans classified separately: 102 production sites, 0 test sites —incr!57,gauge_add!26,count!17,gauge!2, and zero each for the other three. A naive grep over four macros gives 115; all 15 of the difference are comments quoting a macro name. 236 does not reproduce under any macro list."Roughly fifteen sites need the peer address supplied into the core" is zero for
h2.rs. Bothlog_context!andlog_context_stream!already read$self.peer_address, a field snapshotted at construction, across 113 production expansions — that landed in4eb51741, the first commit of #1471. (A separate correction: an earlier comment here attributed that hoist to #1501. #1501 is theDebugfield swap and never toucheslog_context!.) The only livepeer_addr()reads remaining inmux/aremod.rs:64and:91, which resolve to mio's inherent method rather thanSocketHandler::peer_addr— two production sites asocket_ref().peer_addr()grep cannot find, which is why every survey has missed them. They sit inMux, the shell, so they cross no core/shell boundary and are a Q5-class observability defect rather than Q4 work.ReplayCapture's metricsDropis not a defect — record it as closed. This issue and its 2026-09-19 comment both sayConnectionH2's is the only metricsDropinlib/src/. That is inaccurate: there are two, the second atlib/src/protocol/mux/stream.rs:167. But it is reached in production only fromConnectionH1::start_stream, andConnectionH1<Front: SocketHandler>ownssocket: Front— it is already its own shell. So it is a metricsDropsitting exactly where one belongs. The claim is wrong; the thing it missed is right.What has shipped
impl Dropmoved fromConnectionH2toH2Shell, which makes movingcoreout of the shell a compile error rather than a documented hazard.impl ConnectionH241 → 3.converter.rsandpkawa.rsreach zero metric-macro sites.One deliberate non-move, with its measurement:
names::backend::RETRY_STALE_UPSTREAMstays a macro call in the core. ItsOption<&str>labels would have to become owned, andsize_of::<MetricEvent>()goes 24 → 48 bytes — paid by every element of the event queue, for the variants that carry no labels, on behalf of one site that fires only on stale-upstream retries.Copyis lost on top. The core therefore ends at 1, not 0, and the reason is on the line so nobody "finishes the job" without re-deriving it.What remains, and it is one question asked three times
Position::count_bytes_{in,out}_counter(4 sites) andStream::generate_access_log(6), reached from 7ConnectionH2call sites, plus thehttp.active_requestspair. All three are leaf helpers shared between a split core (ConnectionH2) and unsplit shells (ConnectionH1,Mux,Router— all three verified to own concrete sockets or aFront).The decided shape is that the helper returns its events and every caller handles them, rather than branching on which caller it has: a leaf whose behaviour depends on its context has two paths where a metric can be lost or double-counted, and nothing local can tell you which ran.
http.active_requestscarries an extra condition. Its+1exists twice, once per protocol, against a single shared-1, and H1's+1is already correctly placed. So the pair ends up split across two mechanisms — the thing "a gauge moves with its pair" exists to prevent — and that is only safe because each path balances: H1 is macro-plus-event, H2 is event-plus-event. It ships only with a test proving each path nets to zero across a full request, seen red by dropping one half of one path.refactor(mux-h2): return the H2-only helpers' metrics as MetricEvents (…
fix(mux): render the session peer in the MUX log envelope (#1536)
refactor(mux-h2): return the shared leaves' metrics as MetricEvents
refactor(mux-h2): return the shared leaves' metrics as MetricEvents (#…
FlorentinDUBOIS commentedon Sep 26, 2026
Q4 and Q5 are both shipped. Closing, with the measurements that decided what stays a macro.
Verified against
origin/mainat747bc3a817a690f00906c69103458e297bd19a2d.Q5 — shipped, in four places rather than one
The decision was to snapshot the peer through a
SocketHandler::peer_addrmethod. It shipped in#1360 for
h2.rs's macros, then the same defect turned up three more times because it is a class,not a site:
h2.rsmacroslog_socket_context!insocket.rsConnectionH1+mux/mod.rs's two macrosimpl Debug for ConnectionH1The last one is worth recording:
ConnectionH1was the finalDebuginmux/still handingmio::net::TcpStream's ownDebugasocketfield throughSocketHandler::socket_ref. Its twinConnectionH2had already renderedpeer_address. #1360's own comment said it: leaving twinmacros on different clocks is how they drift apart — and it was a
Debug, not a macro, which iswhy it survived three passes.
Q4 — shipped as
MetricEvent, and the core ends at one macro siteConnectionH2's metric-macro sites went 41 → 1 across #1517, #1530, #1532, #1534 and #1537.Positionis at 0.Two categories deliberately stay as macros, and this is the part worth keeping. Both were
measured, not assumed, and the maintainer's standing constraint — sōzu stays maximally zero-copy on
the hot and data path — confirms both verdicts:
names::backend::RETRY_STALE_UPSTREAM. Carrying it as an event needs the retry reason, whichmakes
size_of::<MetricEvent>()go 24 → 48 bytes, paid by every element of the queue, andcosts the enum its
Copy. One rare site on a stale-upstream retry does not justify doubling thequeue's element size.
Stream::generate_access_log—names::http::ERRORSand the twocomputed bucket keys. They carry
cluster_id/backend_idas borrowedOption<&str>. Puttingthem in a
MetricEventmeans two ownedOption<String>, i.e. two allocations per access log,on a function whose body is allocation-free today (measured: zero
to_owned,to_string,format!,String::,Vec::,vec!,collectorcloneacross its 164 lines). The labelledingestion path is itself allocation-free in steady state —
receive_backend_metrictakes&strand only calls
to_owned()on a backend's first sighting — so moving these would introduce thefirst allocations on the path rather than relocate existing ones.
Stream::generate_access_logtherefore stays half-migrated: it returns its unlabelled events andstill writes
METRICSfor the three labelled ones. The two mechanisms compose, and a half-migratedcounter is not a wrong counter.
The shape that made the unlabelled half free
Worth recording because the first two attempts were worse. The events a helper emits are bounded
and small, not variable:
Position::bytes_{in,out}_eventemit exactly one, andgenerate_access_logat most two. So the return isMetricEventand[Option<MetricEvent>; 2]onthe stack — no
Vec, no allocation, no container for the caller to own, and#[must_use]applies,which is what caught all ten callers at compile time instead of two by test. A
Vecreturn wouldhave added the first allocation to an allocation-free function; an out-parameter would have needed a
queue on
ConnectionH1andMux, which are shells and legitimately have none.Nothing left here
The
ReplayCaptureDropnoted earlier in this issue is already correct and needed no change. Thepeer-read class is closed on its last site. Q12 part 2 is tracked in #1340, not here.