Repository navigation
fix(mux-h1): render the cached session peer instead of a live getpeername (#1524) - #1526
Merged
Merged
Conversation
…name (#1524) The two `log_context!` / `log_context_stream!` macros in `lib/src/protocol/mux/h1.rs` built their `peer=` slot from `$self.socket.socket_ref().peer_addr().ok()` — a live `getpeername(2)` on every expansion, reaching past `SocketHandler::peer_addr`, the trait method `df52d83d` added to stop exactly that. `ConnectionH1` now carries a `peer_address` snapshot taken once from `SocketHandler::peer_addr` in `Connection::new_h1_server` and `Connection::new_h1_client`, and both macros interpolate the field. Three rendered slots move, each one a case an operator meets during an incident. After the peer resets, `getpeername(2)` answers `ENOTCONN`, so the `error!` lines being read at that moment rendered `peer=None`; they now carry the address. On a PROXY-protocol frontend the raw lookup reported the load balancer while the rest of the session was logged against the advertised client; the line now names the client. On a backend connection a nonblocking `connect()` still in flight makes `getpeername(2)` refuse, so the slot rendered `peer=None` for the whole window in which an ECONNREFUSED line is emitted; it now names the cluster-configured backend, which the dial path caches for exactly this reason. The case is observability and consistency, not cost. #1341 examined the performance argument for the H2 twin and retracted it in its own text — there is no clock read in the macro, no expansion is unconditional per-frame or per-request, and `_log_enabled!` returns before the arguments are evaluated — and the same reasoning applies here. What this buys is that an operator grepping a single session ULID reads the same `peer=` on the `MUX-H1` and `MUX-H2` lines of one connection, instead of a correct address on one and `peer=None`, or the load balancer, on the other. Snapshot rather than calling the trait method in the macro, which was the issue's other option. Calling it fixes the PROXY and cache-then-live cases immediately, because those live inside the implementors, but it leaves the ENOTCONN case conditional on a cache the direct-accept routes may not hold: `http.rs` and `https.rs` both seed `configured_peer` from a best-effort `peer_addr().ok()` at accept, an `Option` precisely because that lookup can fail, and on those paths a per-line trait call still collapses to `peer=None` after a reset. The snapshot is taken while the connection is established, so it answers wherever the fallback would have answered and additionally survives the reset. The divergence from a live call is one-directional — `Some` where `None` used to appear, never a different address. Both production handlers (`SessionTcpStream`, `FrontRustls`) prefer a cached address but keep a reachable live-`getpeername(2)` fallback, pinned by its own tests. Nothing here licenses deleting those arms. Five tests, each seen red under its own named substitution, lib suite 1126 -> 1131. `log_context_renders_the_peer_when_the_live_lookup_fails`, `log_context_renders_the_backend_peer_while_the_connect_is_in_flight` and `log_context_renders_the_proxy_advertised_peer_not_the_load_balancer` cover the three symptoms; restoring the pre-fix expression renders `peer=None`, `peer=None` and the transport address respectively. `log_context_stream_renders_the_snapshot_not_a_live_lookup` pins the per-stream twin, which has no production expansion and carries `#[allow(unused_macros)]`, so nothing type-checked its body at all before — twins left on different sources are how they drift apart. `log_context_reads_the_peer_address_once_per_connection` pins the read at exactly one per connection through a counting `SocketHandler`; it is the only one of the five that separates the snapshot from the trait call, since a caching handler returns the same address however often it is asked, and under that substitution it fails `left: 4, right: 1` while the other four stay green. `doc/observability.md`'s `peer` bullet was written as `MUX-H2`-only and ended by stating that `MUX-H1` still renders a live lookup, which this makes false; it is generalised to both and keeps `MUX` on the live-lookup side, since that macro reaches the raw stream through `Connection::socket()` rather than the handler's accessor. The `MUX-H1` row of the prefix table gains the snapshot caveat its `MUX-H2` and `SOCKET` neighbours already carry. Four citations into `h1.rs`, across `mux/LIFECYCLE.md` and `kawa_h1/LIFECYCLE.md`, are re-anchored for the line shift and audited against the base blob as byte-identical and identically enclosed. Refs #1341 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 25, 2026 11:01
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #1524.
MUX-H1's two log-context macros built theirpeer=slot from$self.socket.socket_ref().peer_addr().ok()— a livegetpeername(2)on every expansion, reaching pastSocketHandler::peer_addr, the trait methoddf52d83dadded to stop exactly that.ConnectionH1now carries apeer_addresssnapshot taken once fromSocketHandler::peer_addrinConnection::new_h1_serverandConnection::new_h1_client; both macros interpolate the field.A correction to the issue's premise, before anything else
#1524 says "(2) is what H2 ended up with, and only after #1501 hoisted the per-expansion call." That is wrong, and the brief I worked from repeated it. #1501 (
d192407b) isrefactor(mux-h2): render the peer address where Debug named the socket— it swappedDebug'ssocketfield forpeer_addressand de-duplicated twoensure_tls_flushedtails. Itsh2.rschange is +17/-9 and it never touchedlog_context!.The hoist is
4eb51741(refactor(mux-h2): read the log prefix peer from a connection-owned snapshot), the first of eight commits in #1471. I verified this in-tree:git show 4eb51741 -- lib/src/protocol/mux/h2.rsis wherepeer = $self.socket.peer_addr(),becomespeer = $self.peer_address,in both macros, alongside the field andpeer_address: socket.peer_addr(),. #1524's code anchors are still right —h2.rs:11379is the count test from4eb51741, not from #1501. Worth fixing in the issue text, since its "model on this" section rests on it.Option (2), and what moved me
I took (2), the per-connection snapshot. Two things decided it.
The ENOTCONN case is only structurally fixed by (2). Option (1) genuinely fixes the PROXY and cache-then-live cases immediately, because those live inside the implementors — that part of the issue is right. But it leaves the reset case conditional on a cache the direct-accept routes may not hold.
http.rsseedsconfigured_peerfromsock.peer_addr().ok()at accept andhttps.rsseedsHttpsSession::peer_addressthe same way — bothOptionprecisely because that lookup can fail.FrontRustls::peer_addrcarries a comment saying itsor_elsearm is reachable and naming the test that fails without it. On those paths a per-line trait call still collapses topeer=Noneafter a reset. The snapshot is taken while the connection is established, so it answers wherever the fallback would have answered and additionally survives the reset. That is the "merely unlikely vs structurally incapable" distinction, and it is real rather than decorative.The cost here is far below what the issue implies, because
4eb51741's real expense does not exist for H1. What that commit was buying was decouplingConnectionH2fromFront— 113 of its 140Fronttouch points were thepeer=slot — and it paid +169/-4 inh2.rsplus 57 re-anchored citations carrying 79 line numbers across three documents. Nobody is decouplingConnectionH1fromFront, and it already ownssocket: Frontwith two constructors that already receive it. So there is noH2Shellsplit, no signature change, and the four otherConnectionH1 { … }sites inhttp.rs/https.rsare destructuring patterns with.., so they are untouched. The production change is 2 macro lines, 1 field and 2 seeding lines.The argument against (1): it is two lines and trivially reviewable, and it would have been a real improvement — I am not claiming otherwise. I rejected it because it leaves H1 and H2 structurally different for no remaining reason once the cost of matching is this low, and because the operator case the issue is actually about is comparing an H1 and an H2 line for one ULID.
Hazards
4eb51741had to be careful about, which I carried over: the live-getpeername(2)fallback arms inSessionTcpStream::peer_addrandFrontRustls::peer_addrare reachable and pinned by their own tests — its message says "Nothing in this commit licenses deleting those arms", and I touched neither. Its behavioural delta is one-directional (SomewhereNoneused to appear, never a different address); the same holds here. And it had to state, because the loose version is wrong, that no production caller reachesSocketHandler::peer_addron a baremio::net::TcpStream— a claim about call sites, not about the handler.Not argued on performance. #1341 examined that for H2 and retracted it in its own text — no clock read in the macro, no expansion unconditional per-frame or per-request,
_log_enabled!returns before the arguments are evaluated. The case is observability and consistency.The three symptoms and their tests
getpeername(2)returnsENOTCONNafter a peer RSTlog_context_renders_the_peer_when_the_live_lookup_failspeer=NoneSessionTcpStream::peer_addris cache-then-livelog_context_renders_the_backend_peer_while_the_connect_is_in_flightpeer=Nonelog_context_renders_the_proxy_advertised_peer_not_the_load_balancerpeer=Some(127.0.0.1:35515)— the transport peerTwo more:
log_context_stream_renders_the_snapshot_not_a_live_lookuppins the per-stream twin, andlog_context_reads_the_peer_address_once_per_connectionis the H1 analogue ofh2.rs's once-per-connection test, owed because I took (2).Symptom 1 is staged with a never-connected socket, not a real RST, mirroring
socket.rs's existingunconnected_streamhelper and its stated reason: only the former refuses deterministically, and whether the kernel has collected an RST yet is not something a test may assert on. A reset peer is one way to reach the refusing state; what the test pins is the rendering once the socket is in it, which is the part the macro owns.One honest scope limit on symptom 3. The test stages the cleartext expect-proxy route, whose handler really is a
SessionTcpStreamseeded with the advertised source — that is production, not a stand-in. The TLS PROXY route composes the same macro withFrontRustls::peer_addr, and I did not build aConnectionH1<FrontRustls>: theFrontRustlsfixture needshttps.rs's TLS machinery, and the H1 macros are file-localmacro_rules!that a test inhttps.rscannot see. That half is covered by composition — this PR's tests prove the H1 macro reads the trait method's answer, andfront_rustls_peer_snapshot_is_the_session_peer_not_the_accepted_socketalready proves whatFrontRustlsreturns for a PROXY frontend. Stated as composition rather than papered over with a test that would pass for a different reason.Red-then-green transcript
Every recipe below was applied, observed red, and restored — I did not write a recipe I had not run. After the last restore the file was
diff-identical to the pre-revert copy.Recipe 1 on
log_context!— restorepeer = $self.socket.socket_ref().peer_addr().ok(),:with the rendered lines naming the defect exactly:
Recipe 1 on
log_context_stream!(twin only,log_context!restored):Recipe 2 — the option-(1) shape
peer = $self.socket.peer_addr(),inlog_context!. This is the one that makes (2) non-decorative:left: 4, right: 1is exactly what the recipe text predicts. The four which-address tests staying green under this substitution is the documented negative result from4eb51741, reproduced on the H1 side: a caching handler returns the same address however often it is asked, so only a call count can tell the snapshot from the trait call.Restored → green:
test result: ok. 5 passed; 0 failed; 1126 filtered out.Test-shaped-fix check
Production diff (
h1.rsabove the test module, plusconnection.rs), non-comment added lines in full:Literals in those lines: none. Literals shared with the test file: none. The test file's literals (
"10.0.0.42:12345","test-cluster","test-backend","127.0.0.1:0") appear nowhere in production.Reference sweep
Changed: one added field,
ConnectionH1::peer_address. No signature, return shape, config key, route, CLI flag, env var or enum member changed, so the sweep is over that name plus everyConnectionH1 { … }site.grep -rn "peer_address" .with no file-type filter, dispositioned by file:lib/src/protocol/mux/h1.rs(12)lib/src/protocol/mux/connection.rs(5)new_h1_server/new_h1_clientdoc/observability.md(1)MUX-H1lib/src/https.rs(26)HttpsSession::peer_address, a different owner; it is the sourceFrontRustls::configured_peeris seeded from and is unchangedlib/src/protocol/mux/h2.rs(17)ConnectionH2::peer_address, the H2 twin, untouchedlib/src/protocol/rustls.rs(4)lib/src/socket.rs(3)configured_peer/peer_addr; this change consumes them and alters neithere2e/src/tests/h2_log_context_tests.rs(3)MUX-H2lines onlydoc/h2_mux_internals.md(1)ConnectionH2'sDebug, never mentions H1CHANGELOG.md(8)ConnectionH1 { … }sites:connection.rs:98/:128updated (the two constructors);http.rs:432/:474andhttps.rs:780/:812unaffected — destructuring patterns carrying.., so a new field does not reach them. Confirmed bycargo buildand by reading each site.Counting note: the per-file numbers above are
grep -rnline counts for the stringpeer_address, given only to show where the name lives; they are not code-reference counts. The load-bearing count in this PR is the sixConnectionH1 { … }sites, which I enumerated and read individually — two literals, four patterns.Documentation
doc/observability.md'speerbullet was writtenMUX-H2-only and ended "MUX… andMUX-H1… still render a livegetpeername(2)and are unchanged", which this makes false. It is generalised to both protocols and keepsMUXon the live-lookup side — that macro reaches the raw stream throughConnection::socket(), not the handler's accessor, so it is genuinely unchanged. TheMUX-H1row of the prefix table gains the snapshot caveat itsMUX-H2andSOCKETneighbours already carry, and the bullet gains a third consequence for the backend case, which has noMUX-H2counterpart because onlyConnectionH1is built by both a server and a client constructor. The stalepeerbullet inh1.rs's own macro doc ("orNoneif the socket is gone") is replaced, modelled on itsh2.rssibling.No new citation was created anywhere. Every reference I wrote is a symbol or a bare path — no
file.rs:NNNin prose, and none in a Rust comment, which rule 5 forbids outright.Four pre-existing citations into
h1.rsshifted and were re-anchored by content, keyed on the full repo-relative path (git show <base>:lib/src/protocol/mux/h1.rsaligned against the new file withdifflib), never by basename:lib/src/protocol/kawa_h1/LIFECYCLE.md:217h1.rs:385h1.rs:421if kawa.is_error() {lib/src/protocol/mux/LIFECYCLE.md:459h1.rs:1044-1101h1.rs:1080-1137stream.state = StreamState::Unlinked;lib/src/protocol/mux/LIFECYCLE.md:491h1.rs:1011h1.rs:1047context.unlink_stream(stream);The
--baserun reports exactly 4 re-anchored spans exempt from comparison — these and no others. Because an exemption means the rule declined to look, I audited all four on two keys: byte-identical line text (all 4 identical) and identically-named enclosingfn(readable,end_stream,end_stream,end_stream— unchanged on both sides). Sequence was edits →cargo build→cargo +nightly fmt --all(apply) → remap → gates, so no laterfmtinvalidated the numbers.Verification battery
Every command run from a clean worktree off
a3a03b66, each exit code read directly, never through a pipe.cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simdcargo +nightly fmt --all -- --checkcargo clippy --all-targets --locked --no-default-features --features … -- -D warningscargo test -p sozu-lib --locked --no-default-features --features …ok. 1131 passed; 0 failed; 0 ignored(+1,1,5 passed/5 ignored)cargo test -p sozu --locked --no-default-features --features …ok. 113 passed; 0 failedcargo test -p sozu-e2e … -- --skip tests::fuzz_tests::ok. 447 passed; 0 failed; 4 filtered out(374.18s)RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked12,6,6,6 passedRUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets --locked -- -D warningscheck_doc_citations.py --self-testcheck_doc_citations.py --root .check_doc_citations.py --base a3a03b66fc180b8fb1964c17e27edc4033785424check_doc_citations.py --audit --root .RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --lockedcargo bench -p sozu-lib --bench h2_stream_table -- --testSuccesssozu-libtest count: 1126 → 1131 (+5, exactly the five tests added).sozu113 andsozu-e2e447 unmoved. e2e was run withpgrep sozu_e2e | wc -lat 0 and 1-minute load at 4.57.Scope
Six files:
lib/src/protocol/mux/h1.rs,lib/src/protocol/mux/connection.rs,doc/observability.md,CHANGELOG.md, and the twoLIFECYCLE.mdre-anchors.pipe.rsuntouched (already cache-first). No#[cfg(test)]scaffolding elsewhere touched. NoMETRICScall site touched. No check weakened, no test skipped, no lint escape, no production dependency added. The CHANGELOG entry sits below the### 🐛 Fixedhead, not at the top of the file.h2.rsandsocket.rsturned out not to need editing — option (2) reached neither — so nothing needs sequencing around this branch on that account. The twoLIFECYCLE.mdfiles are the only files here outsidemux/h1's immediate orbit, and they moved only because my line shift forced the re-anchor.Adjacent, reported and not taken
ConnectionH1'sDebugstill renders.field("socket", &self.socket.socket_ref())— the exact thing #1501 moved H2 away from, and it now has apeer_addressto render instead. That is #1501's change applied to H1 and belongs in its own changeset. Separately,mux/mod.rs'slog_context!andlog_context_lite!renderpeer = $self.frontend.socket().peer_addr().ok(),, which resolves to mio's inherent method rather than the trait — a third live-lookup surface #1524 does not name and that its grep could not see. Both reported, neither taken.