Skip to content

fix(mux-h1): render the cached session peer instead of a live getpeername (#1524) - #1526

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
fix/h1-log-peer-snapshot
Sep 25, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
fix/h1-log-peer-snapshot

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Closes #1524.

MUX-H1's two log-context macros 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; 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) is refactor(mux-h2): render the peer address where Debug named the socket — it swapped Debug's socket field for peer_address and de-duplicated two ensure_tls_flushed tails. Its h2.rs change is +17/-9 and it never touched log_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.rs is where peer = $self.socket.peer_addr(), becomes peer = $self.peer_address, in both macros, alongside the field and peer_address: socket.peer_addr(),. #1524's code anchors are still right — h2.rs:11379 is the count test from 4eb51741, 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.rs seeds configured_peer from sock.peer_addr().ok() at accept and https.rs seeds HttpsSession::peer_address the same way — both Option precisely because that lookup can fail. FrontRustls::peer_addr carries a comment saying its or_else arm is reachable and naming the test that fails without it. 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. 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 decoupling ConnectionH2 from Front — 113 of its 140 Front touch points were the peer= slot — and it paid +169/-4 in h2.rs plus 57 re-anchored citations carrying 79 line numbers across three documents. Nobody is decoupling ConnectionH1 from Front, and it already owns socket: Front with two constructors that already receive it. So there is no H2Shell split, no signature change, and the four other ConnectionH1 { … } sites in http.rs/https.rs are 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 4eb51741 had to be careful about, which I carried over: the live-getpeername(2) fallback arms in SessionTcpStream::peer_addr and FrontRustls::peer_addr are 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 (Some where None used 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 reaches SocketHandler::peer_addr on a bare mio::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

# Symptom Test Pre-fix rendering
1 getpeername(2) returns ENOTCONN after a peer RST log_context_renders_the_peer_when_the_live_lookup_fails peer=None
2 Backend-connect failure; SessionTcpStream::peer_addr is cache-then-live log_context_renders_the_backend_peer_while_the_connect_is_in_flight peer=None
3 PROXY-protocol frontend advertises the client, socket names the LB log_context_renders_the_proxy_advertised_peer_not_the_load_balancer peer=Some(127.0.0.1:35515) — the transport peer

Two more: log_context_stream_renders_the_snapshot_not_a_live_lookup pins the per-stream twin, and log_context_reads_the_peer_address_once_per_connection is the H1 analogue of h2.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 existing unconnected_stream helper 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 SessionTcpStream seeded with the advertised source — that is production, not a stand-in. The TLS PROXY route composes the same macro with FrontRustls::peer_addr, and I did not build a ConnectionH1<FrontRustls>: the FrontRustls fixture needs https.rs's TLS machinery, and the H1 macros are file-local macro_rules! that a test in https.rs cannot see. That half is covered by composition — this PR's tests prove the H1 macro reads the trait method's answer, and front_rustls_peer_snapshot_is_the_session_peer_not_the_accepted_socket already proves what FrontRustls returns 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! — restore peer = $self.socket.socket_ref().peer_addr().ok(),:

test log_context_stream_renders_the_snapshot_not_a_live_lookup ... ok
test log_context_renders_the_peer_when_the_live_lookup_fails ... FAILED
test log_context_renders_the_backend_peer_while_the_connect_is_in_flight ... FAILED
test log_context_renders_the_proxy_advertised_peer_not_the_load_balancer ... FAILED
test log_context_reads_the_peer_address_once_per_connection ... FAILED
test result: FAILED. 1 passed; 4 failed; 1126 filtered out

with the rendered lines naming the defect exactly:

the MUX-H1 peer= slot must survive a failed live lookup:  … Session(peer=None, position=Server, …)
a backend MUX-H1 line must name the configured backend:   … Session(peer=None, position=Client("test-cluster", Connecting(…)), …)
MUX-H1 must render the PROXY-advertised client:           … Session(peer=Some(127.0.0.1:35515), position=Server, …)

Recipe 1 on log_context_stream! (twin only, log_context! restored):

test log_context_stream_renders_the_snapshot_not_a_live_lookup ... FAILED
test result: FAILED. 4 passed; 1 failed; 1126 filtered out
the per-stream MUX-H1 envelope must render the snapshot: … Session(peer=Some(127.0.0.1:46695), …)

Recipe 2 — the option-(1) shape peer = $self.socket.peer_addr(), in log_context!. This is the one that makes (2) non-decorative:

test log_context_renders_the_backend_peer_while_the_connect_is_in_flight ... ok
test log_context_renders_the_peer_when_the_live_lookup_fails ... ok
test log_context_stream_renders_the_snapshot_not_a_live_lookup ... ok
test log_context_renders_the_proxy_advertised_peer_not_the_load_balancer ... ok
test log_context_reads_the_peer_address_once_per_connection ... FAILED
test result: FAILED. 4 passed; 1 failed; 1126 filtered out

assertion `left == right` failed: the peer address must be read once, at construction, not once per log line
  left: 4
 right: 1

left: 4, right: 1 is exactly what the recipe text predicts. The four which-address tests staying green under this substitution is the documented negative result from 4eb51741, 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.rs above the test module, plus connection.rs), non-comment added lines in full:

let peer_address = front_stream.peer_addr();
    peer_address,
let peer_address = front_stream.peer_addr();
    peer_address,
        peer = $self.peer_address,
        peer = $self.peer_address,
pub(super) peer_address: Option<std::net::SocketAddr>,

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 every ConnectionH1 { … } site. grep -rn "peer_address" . with no file-type filter, dispositioned by file:

Hit site Disposition
lib/src/protocol/mux/h1.rs (12) updated — the new field, its doc, the two macro slots, tests
lib/src/protocol/mux/connection.rs (5) updated — seeded in new_h1_server / new_h1_client
doc/observability.md (1) updated — bullet generalised to MUX-H1
lib/src/https.rs (26) unaffected — HttpsSession::peer_address, a different owner; it is the source FrontRustls::configured_peer is seeded from and is unchanged
lib/src/protocol/mux/h2.rs (17) unaffected — ConnectionH2::peer_address, the H2 twin, untouched
lib/src/protocol/rustls.rs (4) unaffected — handshake-side session peer, no H1 connection in scope
lib/src/socket.rs (3) unaffected — handler-level configured_peer / peer_addr; this change consumes them and alters neither
e2e/src/tests/h2_log_context_tests.rs (3) unaffected — asserts on MUX-H2 lines only
doc/h2_mux_internals.md (1) unaffected — documents ConnectionH2's Debug, never mentions H1
CHANGELOG.md (8) unaffected — append-only record of the tree as it stood at each release; superseded by the new entry, not rewritten

ConnectionH1 { … } sites: connection.rs:98/:128 updated (the two constructors); http.rs:432/:474 and https.rs:780/:812 unaffected — destructuring patterns carrying .., so a new field does not reach them. Confirmed by cargo build and by reading each site.

Counting note: the per-file numbers above are grep -rn line counts for the string peer_address, given only to show where the name lives; they are not code-reference counts. The load-bearing count in this PR is the six ConnectionH1 { … } sites, which I enumerated and read individually — two literals, four patterns.

Documentation

doc/observability.md's peer bullet was written MUX-H2-only and ended "MUX … and MUX-H1 … still render a live getpeername(2) and are unchanged", which this makes false. It is generalised to both protocols and keeps MUX on the live-lookup side — that macro reaches the raw stream through Connection::socket(), not the handler's accessor, so it is genuinely unchanged. The MUX-H1 row of the prefix table gains the snapshot caveat its MUX-H2 and SOCKET neighbours already carry, and the bullet gains a third consequence for the backend case, which has no MUX-H2 counterpart because only ConnectionH1 is built by both a server and a client constructor. The stale peer bullet in h1.rs's own macro doc ("or None if the socket is gone") is replaced, modelled on its h2.rs sibling.

No new citation was created anywhere. Every reference I wrote is a symbol or a bare path — no file.rs:NNN in prose, and none in a Rust comment, which rule 5 forbids outright.

Four pre-existing citations into h1.rs shifted and were re-anchored by content, keyed on the full repo-relative path (git show <base>:lib/src/protocol/mux/h1.rs aligned against the new file with difflib), never by basename:

Citing document Was Now Cited text
lib/src/protocol/kawa_h1/LIFECYCLE.md:217 h1.rs:385 h1.rs:421 if kawa.is_error() {
lib/src/protocol/mux/LIFECYCLE.md:459 h1.rs:1044-1101 h1.rs:1080-1137 stream.state = StreamState::Unlinked;
lib/src/protocol/mux/LIFECYCLE.md:491 h1.rs:1011 h1.rs:1047 context.unlink_stream(stream);

The --base run 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 enclosing fn (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 later fmt invalidated the numbers.

Verification battery

Every command run from a clean worktree off a3a03b66, each exit code read directly, never through a pipe.

# Command Result
1 cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd EXIT=0
2 cargo +nightly fmt --all -- --check EXIT=0
3 cargo clippy --all-targets --locked --no-default-features --features … -- -D warnings EXIT=0
4 cargo test -p sozu-lib --locked --no-default-features --features … EXIT=0 — ok. 1131 passed; 0 failed; 0 ignored (+ 1, 1, 5 passed/5 ignored)
5 cargo test -p sozu --locked --no-default-features --features … EXIT=0 — ok. 113 passed; 0 failed
6 cargo test -p sozu-e2e … -- --skip tests::fuzz_tests:: EXIT=0 — ok. 447 passed; 0 failed; 4 filtered out (374.18s)
7 RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked EXIT=0 — 12, 6, 6, 6 passed
8 RUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets --locked -- -D warnings EXIT=0
9 check_doc_citations.py --self-test EXIT=0
10 check_doc_citations.py --root . EXIT=0 — 179 citations resolve
11 check_doc_citations.py --base a3a03b66fc180b8fb1964c17e27edc4033785424 EXIT=0 — 283 compared unchanged, 4 exempt (audited above)
12 check_doc_citations.py --audit --root . EXIT=0
13 RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked EXIT=0
14 cargo bench -p sozu-lib --bench h2_stream_table -- --test EXIT=0 — every case Success

sozu-lib test count: 1126 → 1131 (+5, exactly the five tests added). sozu 113 and sozu-e2e 447 unmoved. e2e was run with pgrep sozu_e2e | wc -l at 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 two LIFECYCLE.md re-anchors. pipe.rs untouched (already cache-first). No #[cfg(test)] scaffolding elsewhere touched. No METRICS call site touched. No check weakened, no test skipped, no lint escape, no production dependency added. The CHANGELOG entry sits below the ### 🐛 Fixed head, not at the top of the file.

h2.rs and socket.rs turned out not to need editing — option (2) reached neither — so nothing needs sequencing around this branch on that account. The two LIFECYCLE.md files are the only files here outside mux/h1's immediate orbit, and they moved only because my line shift forced the re-anchor.

Adjacent, reported and not taken

ConnectionH1's Debug still renders .field("socket", &self.socket.socket_ref()) — the exact thing #1501 moved H2 away from, and it now has a peer_address to render instead. That is #1501's change applied to H1 and belongs in its own changeset. Separately, mux/mod.rs's log_context! and log_context_lite! render peer = $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.

…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MUX-H1 log lines still call getpeername(2) directly, bypassing SocketHandler::peer_addr and rendering peer=None after a RST

1 participant