Skip to content

fix(mux): render the session peer in the MUX log envelope - #1536

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

FlorentinDUBOIS merged 1 commit into
mainfrom
fix/mux-log-context-peer

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

The defect

log_context! and log_context_lite! (lib/src/protocol/mux/mod.rs) built their peer= slot as:

peer = $self.frontend.socket().peer_addr().ok(),

$self.frontend is a Connection<Front>, and Connection::socket()
(lib/src/protocol/mux/connection.rs) returns a mio &TcpStream, obtained through
SocketHandler::socket_ref. A concrete &mio::net::TcpStream has an inherent peer_addr, and an
inherent method wins method resolution over a trait method — so that slot resolved to mio's live
getpeername(2) returning io::Result<SocketAddr>, and never reached
SocketHandler::peer_addr at all.

Measured on the tree, both symptoms reproduce:

  • after the peer's RST, getpeername(2) answers ENOTCONN, so .ok() yields None and the
    error! lines an operator reads during an incident render peer=None;
  • on a PROXY-protocol frontend the advertised source (cached in configured_peer /
    FrontRustls' field) is ignored, so the MUX line names the load balancer while the HTTPS and
    SOCKET lines name the real client — for the same ULID.

This is the same defect class already corrected three times — by #1360 for the h2.rs macros, 504f0528
for log_socket_context! in lib/src/socket.rs, and #1524 for the h1.rs macros. mod.rs was
left behind by all three, because it holds a Connection rather than a core and Connection
exposed no route to the snapshot the cores already carry.

The fix

ConnectionH1::peer_address and ConnectionH2::peer_address already exist — an
Option<SocketAddr> filled once at construction from SocketHandler::peer_addr. The only thing
missing was an accessor on Connection. New Connection::peer_address, built on the existing
forward! macro exactly like readiness() and position():

pub fn peer_address(&self) -> Option<SocketAddr> {
    *forward!(&self, peer_address)
}

Both macro definitions now interpolate $self.frontend.peer_address(). All 52 expansions —
34 log_context!, 18 log_context_lite! — go through those two definitions, so no callsite
changed
.

Reading the field rather than calling the trait per line preserves the property
log_context_reads_the_peer_address_once_per_connection pins one layer down: rendering a MUX
line now costs no socket access at all, and it cannot drift from what the per-protocol envelopes
print for the same session.

Why the h2.rs hunk is one keyword

lib/src/protocol/mux/h2.rs carries one line, zero line delta: peer_address widens from
private to pub(super), the visibility ConnectionH1::peer_address already carried.
Connection::peer_address is its only reader outside h2.rs.

It is kept to a single keyword with no added doc comment on purpose. Any line inserted in h2.rs
shifts the pinned code blocks in doc/h2_mux_internals.md and breaks check_doc_citations.py —
measured on this branch: a 5-line doc comment broke 8 of 16 pinned blocks. The rationale lives on
the accessor in connection.rs instead.

For the same reason the production hunks in lib/src/protocol/mux/mod.rs are three one-line
substitutions
with zero line delta: LIFECYCLE.md and doc/testing.md pin 33 citations into
that file, and a 5-line bullet shifted every one of them.

This branch was rebased onto fa11f549 (#1534) after that merged; the rebase was clean and the
whole battery below was re-run on the rebased tree, not carried over from the earlier base.

Behaviour change

This changes rendered log content. A rule matching peer=None on a MUX line to detect a reset
stops firing, and grouping a dashboard by peer= may see a large cardinality increase behind a
PROXY-protocol frontend. No wire byte, metric, control-flow decision or log layout changes.
doc/observability.md and CHANGELOG.md are updated in the same changeset.

Regression tests, seen red

Two tests in lib/src/protocol/mux/mod.rs:

  • log_context_renders_the_snapshotted_peer_not_a_live_lookup
  • log_context_lite_renders_the_snapshotted_peer_not_a_live_lookup

Both assert the rendered value, not a call count. A counting SocketHandler cannot
discriminate here: before the fix the macros never reached SocketHandler::peer_addr, so a counter
reads zero on both sides of the change and the test would be green either way. The frontend
snapshots 10.0.0.42:12345 while its socket is genuinely connected to a live loopback listener,
and each test asserts that healthy, disagreeing live lookup as an explicit premise so it cannot
pass for the wrong reason.

To SEE THIS RED (the recipe is also a comment on each test): in log_context! /
log_context_lite! (mod.rs), put peer = $self.frontend.socket().peer_addr().ok(), back in place
of peer = $self.frontend.peer_address(),.

Both were run red before the fix, green after, red again with production reverted to the base
revision, and green again on restore:

# before the fix
log_context_renders_the_snapshotted_peer_not_a_live_lookup ... FAILED
  the MUX peer= slot must render the snapshotted address; rendered:
  [01M3CS1YZNCC63SVXQPMDGE942 - - -]	MUX	Session(frontend=0, peer=Some(127.0.0.1:39001), streams=0, ...)
log_context_lite_renders_the_snapshotted_peer_not_a_live_lookup ... FAILED
  the lite MUX peer= slot must render the snapshotted address; rendered:
  [01M3CS1YZNA4S0XVJZ0WVX0H4Q - - -]	MUX	Session(frontend=0, peer=Some(127.0.0.1:37353), readiness=...)

# after the fix
test result: ok. 2 passed; 0 failed

A grep of the production diff (connection.rs + h2.rs + the mod.rs hunks above the tests module) for
every literal shared with the test fixture — 10.0.0.42, 12345, SNAPSHOT_PEER, the two test
names, connected_loopback_stream, mux_with_snapshotted_peer, live_peer, 127.0.0.1,
SessionTcpStream, TestListener, Pool::with_capacity — returns 0 for each. peer_address
appears on both sides by necessity: it is the field and accessor under test, not a shared fixture.

Validation

Base: fa11f549c02722a378b983a0b3cb716187f54e14 (#1534, merged).

Command Result
cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd exit 0
cargo +nightly fmt --all -- --check exit 0
cargo clippy --all-targets --locked --no-default-features --features … -- -D warnings exit 0
cargo test -p sozu-lib --locked --no-default-features --features … 1141 passed, 0 failed
cargo test -p sozu --locked --no-default-features --features … 113 passed, 0 failed
cargo test -p sozu-e2e --locked --no-default-features --features … -- --skip tests::fuzz_tests:: 447 passed, 0 failed
RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked 30 passed, 0 failed
RUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets --locked -- -D warnings exit 0
check_doc_citations.py --self-test exit 0
check_doc_citations.py --root . exit 0
check_doc_citations.py --base fa11f549c02722a378b983a0b3cb716187f54e14 exit 0, 0 of 256 citations drifted
check_doc_citations.py --audit --root . exit 0
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked exit 0

Scope

This PR closes no issue. It handles one part of the MUX-family log-context work; #1341 remains
open
, and its remaining Q4 item is a different piece of work — #1534 landed one instalment of it
and the rest continues on its own branch.

`log_context!` and `log_context_lite!` (`lib/src/protocol/mux/mod.rs`) built
their `peer=` slot from `$self.frontend.socket().peer_addr().ok()`.
`Connection::socket()` hands back a `&mio::net::TcpStream`, whose *inherent*
`peer_addr` wins method resolution over `SocketHandler::peer_addr`, so the slot
was a live `getpeername(2)` and never reached the trait at all.

Two consequences, the same ones df52d83 fixed for `MUX-H2`, 504f052 for
`SOCKET` and #1524 for `MUX-H1`. After the peer resets, `getpeername(2)` answers
`ENOTCONN`, so the `error!` lines an operator reads during an incident rendered
`peer=None`. 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 practical symptom was that one session ULID rendered two different peers
depending only on which envelope emitted the line.

`mod.rs` was the one envelope those three changes left behind, because it holds
a `Connection` rather than a core and `Connection` exposed no route to the
snapshot the cores already carry. New `Connection::peer_address`
(`lib/src/protocol/mux/connection.rs`), built on the existing `forward!` macro
like `readiness()` and `position()`, returning `ConnectionH1::peer_address` or
`ConnectionH2::peer_address`; both macros interpolate it. The latter field
widens from private to `pub(super)`, the visibility `ConnectionH1::peer_address`
already carried, and that accessor is its only reader outside `h2.rs`.

Reading the field rather than calling the trait keeps the property
`log_context_reads_the_peer_address_once_per_connection` pins one layer down:
rendering a `MUX` line now costs no socket access at all, and it cannot drift
from what the per-protocol envelopes print for the same session. All 52
expansions — 34 `log_context!`, 18 `log_context_lite!` — go through the two
definitions, so no callsite changed.

This changes rendered log content: a rule matching `peer=None` on a `MUX` line
to detect a reset stops firing, and grouping a dashboard by `peer=` may see a
large cardinality increase behind a PROXY-protocol frontend. No wire byte,
metric, control-flow decision or log layout changes.

Two tests, each seen red under its own named substitution:
`log_context_renders_the_snapshotted_peer_not_a_live_lookup` and
`log_context_lite_renders_the_snapshotted_peer_not_a_live_lookup`. Both assert
the rendered VALUE rather than a call count: before this change the macros never
reached `SocketHandler::peer_addr`, so a counting handler reads zero on both
sides and would stay green either way. The frontend snapshots `10.0.0.42:12345`
while its socket is genuinely connected to a live loopback listener, and each
test asserts that healthy, disagreeing live lookup as an explicit premise so it
cannot pass for the wrong reason.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit aaf2a6a into main Sep 25, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/mux-log-context-peer branch September 25, 2026 19:06
FlorentinDUBOIS added a commit that referenced this pull request Sep 25, 2026
…1537)

Addresses **#1341 question 4** — the shared leaf helpers the H2 core reaches through, after the
gauges (#1530), the counters (#1532) and the H2-only helpers (#1534). **#1341 reste ouverte** /
**#1341 stays open**: what Q4 still leaves is listed at the bottom.

## What changed

`Position::count_bytes_{in,out}_counter` and `Stream::generate_access_log` are leaf helpers reached
from the split H2 core **and** from `ConnectionH1`, `Mux` and `Router`, which are shells by
construction — `Router` holds `BTreeMap<Token, Connection<SessionTcpStream>>`, i.e. concrete
sockets. Both now **return** their events; each caller handles them. A core caller queues them; a
shell records them at once, because `METRICS` is legitimately a shell's.

**`impl ConnectionH2` holds one metric-macro site**, down from 41 at the start of this series.
`impl Position` holds none.

### The return is bounded and lives on the stack — no container at all

`bytes_in_event` / `bytes_out_event` return exactly one `MetricEvent`: both arms of their match emit
one, never zero, never two. `generate_access_log` returns `[Option<MetricEvent>; 2]`.

That shape was chosen over a `Vec` on a measurement: **`generate_access_log` is allocation-free
today** — zero `to_owned`, `to_string`, `format!`, `String::`, `Vec::`, `vec!`, `collect`, `clone`
or `Box::` across its 164-line body. A `Vec` return would not have added an allocation to a path
that already had some; it would have introduced the **first**, per request. A fixed array also needs
no queue on the caller, which matters because **four of the eight callers are shells and have none**
— giving `ConnectionH1` and `Mux` a queue would have been inventing core machinery for types that
do not need it.

Slots are filled **by explicit index, never through a `push` helper**. A `push` overflowing a fixed
array would silently drop an event, and a dropped `-1` drifts the aggregate upward forever — an
aggregate that only drifts up never underflows, so nothing logs and nothing saturates. The bound is
documented at the site with the two events that saturate it; a third is a compile error at every
call site rather than a truncation.

### `#[must_use]` makes the eight callers a compiler obligation

It found **all ten call sites at once** (8 production, 2 tests). None was found by hand. This is the
first `#[must_use]` under `lib/src/protocol/mux/`, and it is deliberately **not** applied
retroactively to the `MetricEvent` returns of #1530, #1532 or #1534.

`ConnectionH2::complete_server_stream` is **static** — its `stream` borrows `context.streams`, so it
can hold neither `&mut self` nor a queue — and therefore propagates through its own return, which
becomes `(Option<mio::Token>, [Option<MetricEvent>; 2])`.

### Three sites stay macros, with the measurement on the line

`names::http::ERRORS` and the two computed status-bucket keys carry `cluster_id`/`backend_id`
labels. Carrying those in an event means owned `Option<String>`s: measured,
`size_of::<MetricEvent>()` goes **24 → 48 bytes** for every queued event, and the enum loses `Copy`
— for sites that fire on **every access log**. Same trade as `names::backend::RETRY_STALE_UPSTREAM`,
and worse, because that one fires only on a stale-upstream retry. **Eight sites moved, three
documented.**

`names::http::REQUESTS` folds into `MetricEvent::RequestStarted` with the in-flight gauge's `+1`
because the two are adjacent and unconditional in the same `if`, **with nothing fallible between
them** — the criterion that allowed `RstStreamSent` to fold and forbade folding the GOAWAY pair,
where `gen_goaway` intervenes and the second `incr!` lives in its `Ok` arm.

## BREAKING: three publicly reachable items change or leave the public surface

`lib.rs` declares `pub mod protocol`, `protocol/mod.rs` declares `pub mod mux`, `mux/mod.rs`
declares `pub mod stream`, and `Position` is a `pub enum` — so all three were reachable from outside
the crate. This is declared as a break in `CHANGELOG.md`'s `Removed` section, in the same form #1529
used for its five removed `sozu_lib::protocol::udp` items.

- **Removed:** `Position::count_bytes_in_counter`, `Position::count_bytes_out_counter`.
  `Position::count_bytes_in` / `count_bytes_out` — different methods, taking `&mut SessionMetrics` —
  are untouched and stay public.
- **No longer public:** `Stream::generate_access_log` becomes `pub(super)`, and its signature gains
  a `#[must_use]` return. A downstream caller was recording nothing; there is no public replacement,
  because the returned type is not public either.
- **Additive, called out separately so it is not read as a third removal:**
  `protocol::mux::h2::record_metric` widens from module-private to `pub(super)`.

Nothing on the wire, no metric key, no log line, no configuration key, no CLI flag.

## `http.active_requests` is deliberately split across two mechanisms

H2's `+1` is an event; H1's two `+1` stay macros where they already correctly sit; the single `-1`
is an event that both record. The pair no longer travels together — and that is safe **because each
path balances**, not because the rule stopped applying. Two e2e tests pin it, one per path, and both
were seen red.

### Why the tests sample in flight rather than at the end

`AggregatedMetric::update` **saturates a gauge at zero**, so a test that only checked the value
returned to its starting point could not see a missing increment: the unpaired decrement takes 0 to
0 and reads exactly like a balanced request. Both tests hold the response at the backend and sample
twice:

```
correct            0 -> 1 -> 0
`+1` missing       0 -> 0 -> 0   (the in-flight assertion fails)
`-1` missing       0 -> 1 -> 1   (the post-completion assertion fails)
```

### Five reds, and the contrast between them is the argument

**Before this changeset**, only three were constructible, because the `-1` was a single shared site:

```
A  remove the H1 `+1`   -> H1 "in flight: wanted 1, last sample None"   H1 FAILED, H2 ok
B  remove the H2 `+1`   -> H2 "in flight: wanted 1, last sample None"   H2 FAILED, H1 ok
C  remove the `-1`      -> H1 "after completion: wanted 0, last sample Some(1)"
                           H2 "after completion: wanted 0, last sample Some(1)"   BOTH FAILED
```

**After it**, the two that only the separation makes possible:

```
D  drop the H1 shell's recording   -> "after completion: wanted 0, last sample Some(1)"  H1 FAILED, H2 ok
E  drop the H2 core's drain        -> "after completion: wanted 0, last sample Some(1)"  H2 FAILED, H1 ok
```

C, D and E fail the **same assertion with the same diagnostic**. What differs is that C takes both
paths down together and D/E take them down separately. That is the demonstration, in one line, that
the separation is real and not merely compilable.

Source files were restored byte-for-byte after every red (`cmp` verified) and the suite re-run green,
so each red came from its mutation and not from environment drift.

`last sample None` rather than `Some(0)` is not a detail: with no `+1` the key is never created, so
the gauge is **absent**, not zero. The poller returns `Option<u64>` and does not fold one into the
other.

### What these tests do NOT cover, and why that is acceptable

They exercise **one H1 caller and one H2 caller of the eight**, and the H1 one exercises
`ConnectionH1::readable`, not the pipelined `writable` site. Both limits are written in the test
headers. The other six callers have **no step of their own to forget**: `#[must_use]` obliges every
caller to handle the return, and on the core side the events are drained at a single point rather
than recorded per caller.

Eleven occurrences of `active_requests` exist under `e2e/`: ten in `mux_tests.rs`, all `//` comments
or test-title strings, and one in `h2_correctness_tests.rs` referring to `Backend::active_requests`,
the load-balancer field rather than the gauge. None of them reads the gauge — these two tests are
the first that do. The three hollow H1 tests in `mux_tests.rs` remain to be repaired; that is #1535,
a separate changeset and not this one.

## Citations

Re-measured against the new base after the rebase, not carried over: 58 citation spans re-anchored,
83 line endpoints among them, 74 distinct. Audited on both keys — byte-identical line text and
identically-named enclosing `fn`.

- **Span audit** (every citation whose number my diff moved): 1 text mismatch, 0 enclosing-`fn`
  changes. The one mismatch is the pinned block in `doc/h2_mux_internals.md` that quotes code this
  changeset **changed** (`stream.generate_access_log(` became `let events =
  stream.generate_access_log(`). It was re-quoted by hand rather than renumbered, its prose updated
  to say the method is now `#[must_use]` and that `complete_server_stream` propagates through its
  return, and its range corrected from 8 lines to the 7 the block shows.
- **Full audit** (every citation pointing into any `.rs` this changeset touches, moved or not):
  110 endpoints, **0 mismatches**, 2 no-inverse — and both no-inverse hits are that same re-quoted
  block, which by construction has no counterpart line in the base.

## Still left in Q4

- `names::backend::RETRY_STALE_UPSTREAM` — the last macro site in the core, with its 24 → 48
  measurement on the line.
- The three labelled sites in `generate_access_log`, for the same reason.
- `ReplayCapture`'s `Drop` and `Stream::arm_upstream_replay` are **already correct**: their only
  production caller is `ConnectionH1::start_stream`, which is its own shell. #1341's claim that
  `ConnectionH2`'s was the only metrics `Drop` in `lib/src/` is inaccurate — there are two — but the
  one it missed sits where a metrics `Drop` belongs. That should be recorded as closed, not open.

`mux/mod.rs`'s two `log_context!` / `log_context_lite!` peer reads were on this list until #1536
landed; they are no longer open and the item is struck from it.

## Rebased onto `aaf2a6aa` (#1536)

This branch was rebased from `fa11f549` onto `aaf2a6aa` after #1536 merged, and every number below
was re-measured there — a result obtained on the old base is not a result on the new one.

#1536 changed five files. Measured with `comm -12` over the two file lists rather than assumed,
exactly three of them are also changed here — `lib/src/protocol/mux/h2.rs`,
`lib/src/protocol/mux/mod.rs` and `CHANGELOG.md` — and the rebase resolved with no conflict in any
of the three. In `h2.rs` it widened `ConnectionH2::peer_address` to `pub(super)` on a single line,
which shifts nothing. In `mod.rs` it rewrote the two log macros and added tests, in regions my diff
does not enter. In `CHANGELOG.md` its entry went to the head of `### 🐛 Fixed` while mine sit at the
tails of `### 🔄 Changed` and `### ➖ Removed`. Its other two files are untouched here:
`connection.rs`, which gains the `Connection::peer_address` accessor that is the whole reason
`ConnectionH2::peer_address` had to widen, and `doc/observability.md`.

The reference sweep was re-run on the new base and found one hit it had missed: a comment in
`e2e/src/tests/h2_tests.rs` naming `Position::count_bytes_in_counter`, a method this changeset
removes. It now names `Position::bytes_in_event` and says the event is queued on the core and
recorded by the shell. The edit is line-count-neutral, and nothing cites a line in that file. Every
other surviving reference names `generate_access_log` as a symbol without asserting its return type,
its visibility, or that it emits the metric itself — `lib/src/http.rs`, `lib/src/https.rs`,
`lib/src/metrics/mod.rs`, `lib/src/metrics/local_drain.rs`, `doc/observability.md`,
`doc/lifetime_of_a_session.md`, `kawa_h1/{answers,editor}.rs` and two `LIFECYCLE.md` — so each is
unaffected: the three labelled `incr!` sites those comments describe are exactly the three that stay
macros.

## Validation

All re-run at `0d7986b8b494d2a9af28efdca406b6dbbfc4d229` on the new base, not carried over from the
old one. Exit codes read directly, never through a pipe.

- `cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd` — 0
- `cargo +nightly fmt --all -- --check` — 0
- `cargo clippy --all-targets --locked --no-default-features --features … -- -D warnings` — 0
- `cargo test -p sozu-lib …` — **1148 passed, 0 failed, 5 ignored**; no test deleted, no `#[ignore]`
  added, and the `#[test]` count is unchanged in all five `lib/src/protocol/mux/` files touched
  (`h1.rs` 5, `h2.rs` 105, `mod.rs` 24, `stream.rs` 6, `router.rs` 29 — identical to `aaf2a6aa`)
- `cargo test -p sozu …` — 226 passed, 0 failed
- `cargo test -p sozu-e2e … -- --skip tests::fuzz_tests::` — **449 passed, 0 failed** (447 + the two
  new balance tests), run under a three-criterion guard evaluated and launched in ONE statement: no
  `sozu_e2e` child, no `cargo test -p sozu-e2e` parent, 1-minute load average **3.94** at launch.
  The guard is a start condition: load rose to 21.9 mid-run under a concurrent `cargo` build in a
  different checkout, while the `sozu_e2e` child count stayed at 1 throughout, so the port-sensitive
  criterion held for the whole run and the pass is not a pass under port contention
- `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked` — 30 passed, 0 failed
- `RUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets --locked -- -D warnings` — 0
- `check_doc_citations.py` `--self-test` / `--root .` / `--base aaf2a6a` / `--audit --root .` — all 0.
  The advisory audit reports 7 of 80 on this branch; a detached checkout of `aaf2a6aa` reports the
  same 7 of 80, at the same citing lines, differing only in the four `h2.rs` numbers my diff moved
  (2324→2364, 3302→3343, 3909→3951, 5114→5160) — each verified to land on a byte-identical line.
- `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` — 0
- `cargo bench -p sozu-lib --bench h2_stream_table -- --test` — 0

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.

1 participant