Skip to content

h2 sans-io: metrics and log context across the boundary (Q4, Q5) #1341

Description

@FlorentinDUBOIS

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 getpeername syscall 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
    are error!, 9 warn!, 1 info!, 22 debug!, 25 trace! — 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 $args is evaluated.
  • It said 176 call sites of h2.rs:69. That figure is all of mux/; h2.rs has 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

  1. FlorentinDUBOIS commented on Sep 19, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Q5 is being fixed (#1360); Q4 stays decided-and-blocked. Plus some count corrections.

    Q5 — the live getpeername(2) in the H2 log macros

    Fixed in #1360. SocketHandler gains peer_addr(), FrontRustls gains the configured_peer field 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!(' over h2.rs returns 1, and that 1 is a test. The macro carries #[allow(unused_macros)]. So "two lines" is literally true but only log_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.
    • The symptom list was incomplete. Beyond the two listed, backend-facing H2 connections improve too: router.rs:449 already seeds configured_peer with the cluster-configured backend address, so an H2 error line after a failed connect() now names the backend where it previously rendered peer=None. That is the exact case SessionTcpStream::configured_peer was 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 MuxClear PROXY path changed too. It does not. Connection::new_h2_server has 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 a MuxClear session has no MUX-H2 frontend line at all. Its frontend renders through MUX-H1 (h1.rs:54, :83), untouched. The draft had even cited http.rs:330 as its evidence — a line whose immediate neighbour, new_h1_server at http.rs:328, refutes it.

    A known divergence remains, documented rather than papered over: the SOCKET line of a TLS frontend still shows the kernel's peer, so on a PROXY frontend it disagrees with the MUX-H2 line. That is an artefact of FrontRustls having carried no cached address until now, not a layer boundary — every other SOCKET line already prefers configured_peer (socket.rs:177). Aligning socket.rs:133 is a one-word change that compiles and leaves the suite green, but nothing asserts the peer= slot of a SOCKET line, 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:

    • No metric is read back to drive behaviour. grep METRICS lib/src/protocol/ returns 2 hits, both in h2.rs test code. Production reads: zero.
    • The Drop gauge rebalance is real and is the sole decrement site (h2.rs:1864-1867 → release_connection_gauges), and it is the only metric-macro Drop in lib/src/ — the others (backends.rs, pool.rs, splice.rs, timer.rs, metrics/writer.rs) use push_event, an atomic, libc::close and debug! respectively.
    • The in-repo precedent is real: lib/src/protocol/udp/ has zero metric macro sites and emits Output::Metric(MetricEvent) instead, consumed by the shell.

    Count corrections while here: 39 production metric-macro sites in h2.rs (12 count! + 18 incr! + 9 gauge_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 in h2.rs are error 53 / warn 13 / info 2 / debug 23 / trace 29, against the 51/9/1/22/25 recorded here.

  2. FlorentinDUBOIS commented on Sep 21, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    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 MetricEvent enum, 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 that h2.rs:1849 performs today, one layer up where METRICS legitimately 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 existing SocketHandler trait — the same shape as SocketHandler::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:

    • the performance argument is void. Zero of the 109 expansions in h2.rs are unconditional per-frame or per-request, 47 do not exist in a release binary, and _log_enabled! returns before $args is evaluated, so a filtered line costs nothing. There is also no clock read in the macro.
    • the real defect is observability. getpeername returns ENOTCONN after a peer RST, so the error lines an operator reads during an incident render peer=None. 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=<backend>. h2.rs:80 reaches past that cache to the raw TcpStream. That is an inconsistency, not a deliberate choice, which is why this is worth fixing independently of the extraction.

    Scope as recorded: SessionTcpStream returns configured_peer or the live lookup, FrontRustls gains the peer field it is the only handler missing, ~25 lines, zero of the 174 call sites touched, lib/tests/log_layout.rs unaffected.

  3. FlorentinDUBOIS commented on Sep 21, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    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/main at f798fdf5:

    $ grep -n "fn peer_addr" lib/src/socket.rs
    84:    fn peer_addr(&self) -> Option<SocketAddr>;
    442:    fn peer_addr(&self) -> Option<SocketAddr> {
    534:    fn peer_addr(&self) -> Option<SocketAddr> {
    1164:    fn peer_addr(&self) -> Option<SocketAddr> {
    

    socket.rs:84 is the trait method; the three implementations are the raw TcpStream (live lookup), SessionTcpStream (configured_peer with a live fallback) and FrontRustls (the field it was the only handler to lack). The log_context! / log_context_stream! macros in h2.rs now read $self.socket.peer_addr(); no socket_ref().peer_addr().ok() remains in either. It shipped exactly as the decision specified, including the FrontRustls field seeded from HttpsSession::peer_address rather than stream.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 (9ef85148 vs f798fdf5), so grep found no fn peer_addr and the h2.rs macro still showed the live getpeername(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 against f798fdf5.

    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 SOCKET line of a TLS frontend still renders the kernel peer. Every other SOCKET line already prefers configured_peer. That is an artefact of FrontRustls having 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 SOCKET divergence. No outstanding decision.

  4. FlorentinDUBOIS commented on Sep 21, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Q4 is unblocked; Q11's answer changes the trait Q4's accounting travels through

    Measured against origin/main at 7be659544163f0d780f8eb0666a25d992f5f8e23.

    Q4's decision — (c), a MetricEvent the core emits rather than mutating a shared registry from the
    datapath — 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's log_context! interpolates $self.socket.peer_addr() alongside the
    connection'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 the
    cached configured_peer over a live getpeername(2), with the documented reason that getpeername
    returns ENOTCONN once the peer has reset — precisely when an operator is reading the error log. The
    byte-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 SOCKET line of a TLS frontend still shows the kernel's peer, so on a PROXY
    frontend it disagrees with the MUX-H2 line — an artefact of FrontRustls having carried no cached
    address 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 a SOCKET line, 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 MetricEvent work actually lands.

  5. FlorentinDUBOIS commented on Sep 25, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    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 main at 6d6640bf, lib/src/socket.rs:146 now reads:

    peer = crate::socket::SocketHandler::peer_addr($self),
    

    fully qualified, so a TLS frontend's SOCKET line prefers configured_peer like every other one. The concern that nothing asserted that slot was also addressed — socket.rs carries log_socket_context_renders_the_cached_peer_when_the_live_lookup_fails, with a "To SEE THIS RED" recipe naming the exact substitution back to peer = $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:64 and :91 — log_context! and log_context_lite! render peer = $self.frontend.socket().peer_addr().ok(), which resolves to mio's inherent method rather than SocketHandler::peer_addr. Two production sites that a socket_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's Debug still hands mio's Debug a 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 in mod.rs — which is the file the core/shell split has been moving. Worth folding into the MetricEvent changeset'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. Counting count!, incr!, gauge_add! and time! over lib/src/protocol/mux/ at 6d6640bf gives 116. The gap is large enough that whoever takes Q4 should re-measure with the macro list stated, rather than inherit either number.

  6. FlorentinDUBOIS commented on Sep 25, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    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:

    It does not close #1341: Q4's remaining metric sites are listed below as …

    That sentence was written to prevent this close. GitHub's keyword parser does not understand negation — it sees close #1341 and 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.rs declares seven metric macros, not four: count!, incr!, decr!, gauge!, gauge_add!, time!, record_backend_metrics!. Over lib/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. Both log_context! and log_context_stream! already read $self.peer_address, a field snapshotted at construction, across 113 production expansions — that landed in 4eb51741, the first commit of #1471. (A separate correction: an earlier comment here attributed that hoist to #1501. #1501 is the Debug field swap and never touches log_context!.) The only live peer_addr() reads remaining in mux/ are mod.rs:64 and :91, which resolve to mio's inherent method rather than SocketHandler::peer_addr — two production sites a socket_ref().peer_addr() grep cannot find, which is why every survey has missed them. They sit in Mux, the shell, so they cross no core/shell boundary and are a Q5-class observability defect rather than Q4 work.

    ReplayCapture's metrics Drop is not a defect — record it as closed. This issue and its 2026-09-19 comment both say ConnectionH2's is the only metrics Drop in lib/src/. That is inaccurate: there are two, the second at lib/src/protocol/mux/stream.rs:167. But it is reached in production only from ConnectionH1::start_stream, and ConnectionH1<Front: SocketHandler> owns socket: Front — it is already its own shell. So it is a metrics Drop sitting exactly where one belongs. The claim is wrong; the thing it missed is right.

    What has shipped

    One deliberate non-move, with its measurement: names::backend::RETRY_STALE_UPSTREAM stays a macro call in the core. Its Option<&str> labels would have to become owned, and size_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. Copy is 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) and Stream::generate_access_log (6), reached from 7 ConnectionH2 call sites, plus the http.active_requests pair. 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 a Front).

    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_requests carries an extra condition. Its +1 exists twice, once per protocol, against a single shared -1, and H1's +1 is 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.

  7. FlorentinDUBOIS commented on Sep 26, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Q4 and Q5 are both shipped. Closing, with the measurements that decided what stays a macro.

    Verified against origin/main at 747bc3a817a690f00906c69103458e297bd19a2d.

    Q5 — shipped, in four places rather than one

    The decision was to snapshot the peer through a SocketHandler::peer_addr method. 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:

    where what read the socket live
    h2.rs macros #1360
    log_socket_context! in socket.rs a one-word change, with the assertion it lacked
    ConnectionH1 + mux/mod.rs's two macros #1526, then #1536
    impl Debug for ConnectionH1 #1542

    The last one is worth recording: ConnectionH1 was the final Debug in mux/ still handing
    mio::net::TcpStream's own Debug a socket field through SocketHandler::socket_ref. Its twin
    ConnectionH2 had already rendered peer_address. #1360's own comment said it: leaving twin
    macros on different clocks is how they drift apart
    — and it was a Debug, not a macro, which is
    why it survived three passes.

    Q4 — shipped as MetricEvent, and the core ends at one macro site

    ConnectionH2's metric-macro sites went 41 → 1 across #1517, #1530, #1532, #1534 and #1537.
    Position is 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, which
      makes size_of::<MetricEvent>() go 24 → 48 bytes, paid by every element of the queue, and
      costs the enum its Copy. One rare site on a stale-upstream retry does not justify doubling the
      queue's element size.
    • The three labelled sites of Stream::generate_access_log — names::http::ERRORS and the two
      computed bucket keys. They carry cluster_id/backend_id as borrowed Option<&str>. Putting
      them in a MetricEvent means two owned Option<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!, collect or clone across its 164 lines). The labelled
      ingestion path is itself allocation-free in steady state — receive_backend_metric takes &str
      and only calls to_owned() on a backend's first sighting — so moving these would introduce the
      first allocations on the path rather than relocate existing ones.

    Stream::generate_access_log therefore stays half-migrated: it returns its unlabelled events and
    still writes METRICS for the three labelled ones. The two mechanisms compose, and a half-migrated
    counter 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}_event emit exactly one, and
    generate_access_log at most two. So the return is MetricEvent and [Option<MetricEvent>; 2] on
    the 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 Vec return would
    have added the first allocation to an allocation-free function; an out-parameter would have needed a
    queue on ConnectionH1 and Mux, which are shells and legitimately have none.

    Nothing left here

    The ReplayCapture Drop noted earlier in this issue is already correct and needed no change. The
    peer-read class is closed on its last site. Q12 part 2 is tracked in #1340, not here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions