Skip to content

refactor(mux-h2): return the connection counters as MetricEvents (#1341 Q4) - #1532

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/mux-metric-events-counters
Sep 25, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/mux-metric-events-counters

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Addresses #1341 question 4 only — the H2 core's counters, following the gauges in #1530. It
does not close #1341: what Q4 still leaves is listed at the bottom, and Q5 shipped in #1360.

#1530 has merged, so this branch now sits directly on main and the diff below is against it. It
was rebased with --onto, and the delta from its old fork point to main was checked to equal the
intervening merges' file set exactly — #1527's and #1528's eight files, nothing else — which gives
the same guarantee an empty diff would have that the squash altered none of #1530's content.

What changed

Thirty metric-macro sites inside impl ConnectionH2 become MetricEvent pushes that H2Shell
records through record_metric, leaving three macro sites in the H2 core where there were 41.
Same keys, same counts, same aggregate a dashboard reads.

Twenty-three variants are added, named for what happened rather than for the key they map to —
RstStreamSent(H2Error), FrameReceived(FrameType), StreamReapedIdleTimeout — so the mapping
onto h2.* lives shell-side with the aggregator. metric_for_goaway_sent,
metric_for_rst_stream_sent, metric_for_goaway_received, metric_for_rst_stream_received and
h2_frame_rx_metric_key are unchanged as helpers; they are simply called one layer out now.

Two macro lines became one event only where both were unconditional

MetricEvent::RstStreamSent carries the frame-type total and the per-code breakdown, because
ConnectionH2::account_emitted_rst and ConnectionH2::end_stream emit them on consecutive
unconditional lines.

The GOAWAY pair was deliberately not folded. count!(metric_for_goaway_sent(error), 1) fires
before serializer::gen_goaway runs, while incr!(names::h2::FRAMES_TX_GOAWAY) fires inside its
Ok arm — so one event would record a frame on the wire that a serialisation failure never wrote.
MetricEvent::GoAwaySent and MetricEvent::GoAwayFrameSent stay separate for that reason. The two
pairs look identical in a diff; they are not, and checking which is which is most of the care in
this changeset.

The drain widened, because a late counter is wrong in a way a late gauge is not

#1530 drained in H2Shell::settled and in Drop, which is sufficient for gauges: a delta recorded
at teardown still sums to the same value. A counter recorded at teardown is attributed past
however many scrapes the connection outlived — LocalDrain is cumulative and scraped periodically.

So H2Shell::end_stream — the one public entry point that reaches a producer and settles through
neither H2Shell::settled nor H2Shell::settle — now drains, and H2Shell::record_pending_metrics
documents all three drain sites and names the public entry points that reach no producer at all
(close, initiate_close_notify, flush_zero_buffer, has_pending_write,
has_pending_write_full), with the core methods they do call. H2Shell::drive_control_flush is a
producer but has exactly one caller, writable_inner, which settles. Drop remains the backstop,
so the worst case stays deferral rather than loss.

parser::FrameType gains Copy, and parser::Frame a frame_type() accessor

FrameHeader already carried a frame_type field, so an unparsed frame could name its type; a
parsed Frame could not, and h2_frame_rx_metric_key re-derived it by matching all twelve
variants. That match is now written once, in parser.rs, and the metric helper keys on FrameType.

Sweep of FrameType, repo-wide, no file-type filter — 140 hits across 7 files: parser.rs 54
(updated: the derive and the new accessor; every other hit unaffected, a Copy widening
invalidates no existing use), serializer.rs 49 (unaffected, read-only matches),
h2.rs 17 (updated: h2_frame_rx_metric_key's signature and its one caller; the remaining 15
are ==/matches!/struct-literal uses, unaffected), e2e/src/tests/h2_tests.rs 8
(unaffected — including the doc comment naming h2_frame_rx_metric_key, whose claim is that the
table is a bare &'static str match with no names:: constant; still true, only its parameter
changed), converter.rs 6, health_check.rs 4, mux/LIFECYCLE.md 2 (unaffected).

Two checks a reviewer will want before accepting a new Copy derive under -D warnings, both
measured rather than assumed:

  • FrameType::Unknown(u8) is its only payload-carrying variant, and u8 is Copy, so the
    derive compiles rather than failing on a field.
  • No .clone() on a FrameType value exists anywhere in the tree, and there are no
    FrameHeader clone sites either — so clippy::clone_on_copy, which fires the moment a type
    becomes Copy, has nothing to fire on. That is the difference between "this should be safe" and
    "this is safe": one such call would have turned a one-line derive into a cascade.

MetricEvent drops Eq (keeping PartialEq) because H2Error and FrameType derive only the
latter. It is pub(super) with no consumer outside protocol::mux.

handle_flood_violation keeps the &'static str key, and this is the one place the shape bends

MetricEvent::FloodViolation carries metric_key rather than a semantic discriminant. That is a
deferred macro call in the shape of an event, and it is deliberate: H2FloodViolation already holds
metric_key beside reason in one field, chosen at the construction site precisely so the log
line and the counter cannot drift apart
. A semantic variant here would duplicate that mapping and
reintroduce the drift the single field exists to prevent. The key is domain data the core already
receives, not something synthesised at the metric site.

MetricEvent is a second type of that name in this crate, and stays that way

protocol::udp::MetricEvent already exists. The two are deliberately unrelated, and each type's doc
comment now says so and names the other.

name declared at and at
Output protocol/tcp_preread/mod.rs protocol/udp/mod.rs
RejectReason protocol/tcp_preread/mod.rs protocol/mux/pkawa.rs
BackendStatus backends.rs protocol/mux/mod.rs
Router protocol/mux/router.rs router/mod.rs
SessionStatus http.rs protocol/pipe.rs
MetricEvent protocol/udp/mod.rs protocol/mux/h2.rs

Module-scoped name reuse is this tree's existing idiom for "same role, different protocol", and
Output already carries it for the same role at the same sans-io boundary. Convergence is
wrong on the merits, not merely costly: protocol::udp::Output::Metric embeds the type, so a shared
enum would force crate::udp and sim/tests/udp_simulation.rs to match on H2 connection gauges,
and this slice alone adds 23 variants with zero overlap and no prospect of any.

The invariant every later slice leans on

H2Shell implementing Drop (from #1530) makes moving core out of the shell a compile error,
not a documented rule. That is what stops a future refactor from draining events into a core that
then escapes its shell, and it was free.

Seen red before trusted

Two new tests, each with a "To SEE THIS RED" recipe that was applied and observed, then restored and
observed green — the file afterwards byte-identical to the pre-recipe baseline.

a_queued_counter_is_recorded_when_its_entry_point_returns
  recipe: delete `self.record_pending_metrics();` from `H2Shell::settled`
  RED  exit 101 — assertion `left == right` failed: the GOAWAY decision must reach
       METRICS when `graceful_goaway` returns, not at teardown
       left: 0   right: 1
  restored -> GREEN exit 0

one_rst_stream_sent_event_records_both_of_its_counters
  recipe: delete either line from the `MetricEvent::RstStreamSent` arm of `record_metric`
  RED  exit 101 — assertion `left == right` failed: the frame-type total must still tick
       left: 0   right: 1
  restored -> GREEN exit 0

The first is the property the gauges did not need, and it is specifically not satisfied by
asserting the counter eventually moves: Drop would satisfy that. It asserts the counter has moved
before the connection is dropped, which is what distinguishes a drained entry point from the
backstop.

The Frame::frame_type() mapping has live end-to-end coverage rather than a unit test: the H2 e2e
suite polls h2.frames.rx.headers as a synchronisation observable (e2e/src/tests/h2_tests.rs), so
a wrong arm times the poll out and fails loudly.

Citations, and the class of wrongness the gates do not catch

47 re-anchored spans / 45 distinct endpoints (43 in h2.rs, 2 in udp/mod.rs), remapped once
from git show <base>:…, then audited on both keys — byte-identical line text and
identically-named enclosing fn — with 0 failures and 0 endpoints without a mapping.

But a faithful re-anchor of a wrong citation is indistinguishable from a faithful re-anchor of a
right one (#1531). This slice moves metric emission sites, so every document whose prose describes
one is in that category: the gate reports no drift, and that is not the same as reporting it is
right. So each was read rather than trusted, and two were wrong afterwards:

  • lib/src/protocol/mux/LIFECYCLE.md — "cancel_timed_out_streams emits
    h2.streams.reaped.{idle_timeout,window_stall}" → it now returns them as MetricEvents the
    shell records.
  • doc/h2_mux_internals.md — "enqueue_rst queues nothing and emits h2.rst_stream_dropped"
    → same correction.

Dispositioned unaffected, with the reason: doc/configure.md's rows ("GOAWAY emitted by Sozu")
describe what the proxy put on the wire, not which layer wrote the counter; doc/observability.md's
macro table uses incr!("h2.frames.rx.data") to illustrate the macro's shape;
doc/observability.md's metric_for_goaway_sent example shows the h2_error_metric_key! wrapper
pattern, and that helper is unchanged; doc/testing.md's claim that h2.frames.rx.headers "ticks
only on a frame completed and cannot witness one still arriving" survives — recording it at the end
of the pass makes it tick later, which only strengthens the claim.

On the rebase procedure this stack has now exercised five times

Each rebase in this stack reported no conflicts — which is precisely the condition under which a
stale line remap merges silently. The affected documents were reset to the merged base and
re-derived anyway, and on the #1530 rebase the resulting tree hash came out identical to the
auto-merged one, so the step is a proof rather than a precaution. The reason it was safe is
measurable: the bases' h2.rs have the same md5, because none of #1525, #1527, #1528 or #1529
touched that file. Had one of them touched h2.rs, the two would have differed and the clean
auto-merge would have been silently wrong.
That is the whole argument for the procedure.

Still left in Q4 after this

  • names::http::REQUESTS + names::http::ACTIVE_REQUESTS in
    ConnectionH2::handle_headers_frame — the gauge's paired -1 is in
    Stream::generate_access_log, and a gauge moves with its pair or not at all.
  • names::backend::RETRY_STALE_UPSTREAM in ConnectionH2::end_stream — the only labelled site.
    Its Option<&str> cluster and backend labels would have to become owned Option<String>, making
    MetricEvent non-Copy and allocating on the retry path. That is a datapath trade, not a
    mechanical substitution, and it does not belong in the slice whose justification is being
    mechanical.
  • The core-reachable sites outside impl ConnectionH2: Position::count_bytes_{in,out}_counter,
    Stream::generate_access_log, pkawa::metric_reject/handle_trailer, H2BlockConverter.
  • ReplayCapture's Drop (stream.rs) — a second metrics Drop in lib/src/; h2 sans-io: metrics and log context across the boundary (Q4, Q5) #1341 records
    the ConnectionH2 one as the only one, which is not true at this tree.
  • mux/mod.rs's two log_context!/log_context_lite! peer reads — a Q5-class observability
    defect, not a metrics-boundary change, and getting its own PR.

Validation

All at 4dfc31cd3dcb39c7263f022a166d967024980a93, on main 3de6f04a, exit codes read directly.

  • cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd — 0
  • cargo +nightly fmt --all -- --check — 0
  • cargo clippy --all-targets --locked … -- -D warnings — 0 (no clone_on_copy from the new derive)
  • cargo test -p sozu-lib … — 1137 passed, 0 failed
  • cargo test -p sozu … — 113 passed, 0 failed
  • cargo test -p sozu-e2e … -- --skip tests::fuzz_tests:: — 447 passed, 0 failed, run with no other
    sozu_e2e process and a 1-minute load average of 6.12
  • RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked — 0
  • RUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets --locked -- -D warnings — 0
  • check_doc_citations.py --self-test / --root . / --base 3de6f04a / --audit --root . — all 0;
    the advisory audit's 7 findings are the same 7 as the base tree's
  • RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked — 0
  • cargo bench -p sozu-lib --bench h2_stream_table -- --test — 0

The only numeric literals added outside comments are 1 in record_metric's count!(key, 1) —
carried verbatim from the sites being moved — and 16384/2/4 in the new tests' pool sizing. The
tests assert a delta of 1 because one event was recorded; the production 1 is the pre-existing
increment-by-one idiom, not a value shaped to satisfy them.

Thirty metric-macro sites inside `impl ConnectionH2` become `MetricEvent`
pushes that `H2Shell` records through `record_metric`, leaving three macro
sites in the H2 core where there were 41. Same keys, same counts, same
aggregate; what changed is which layer writes them.

Twenty-three variants are added, named for what happened rather than for
the key they map to, so the mapping onto `h2.*` lives shell-side with the
aggregator. `metric_for_goaway_sent`, `metric_for_rst_stream_sent`,
`metric_for_goaway_received`, `metric_for_rst_stream_received` and
`h2_frame_rx_metric_key` are unchanged as helpers, called one layer out.

Two adjacent macro lines were folded into one event only where both were
unconditional: `RstStreamSent` carries the frame-type total and the
per-code breakdown together. The GOAWAY pair was NOT folded —
`metric_for_goaway_sent` fires before `serializer::gen_goaway` runs while
`FRAMES_TX_GOAWAY` fires inside its `Ok` arm, so one event would record a
frame that a serialisation failure never wrote.

The drain widened, because a late counter is wrong in a way a late gauge
is not: a gauge delta recorded at teardown still sums correctly, while a
counter recorded there is attributed past however many scrapes the
connection outlived. `H2Shell::end_stream` — the one public entry point
that reaches a producer and settles through neither `settled` nor
`settle` — now drains, and `record_pending_metrics` documents the three
drain sites and names the entry points that reach no producer.

`parser::FrameType` gains `Copy` and `parser::Frame` gains a
`frame_type()` accessor: `FrameHeader` already carried a `frame_type`
field, and the twelve-arm match callers wrote instead was the workaround
for the missing accessor. `FrameType::Unknown(u8)` is its only
payload-carrying variant, and no `.clone()` on a `FrameType` exists in
the tree, so `clippy::clone_on_copy` has nothing to fire on.

Left behind deliberately: `names::http::REQUESTS` and
`names::http::ACTIVE_REQUESTS`, because the gauge's paired `-1` is in
`Stream::generate_access_log` and a gauge moves with its pair; and
`names::backend::RETRY_STALE_UPSTREAM`, the only labelled site, whose
borrowed labels would have to become owned `Option<String>`.

Part of #1341 Q4.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the refactor/mux-metric-events-counters branch from a451625 to 4dfc31c Compare September 25, 2026 15:26
@FlorentinDUBOIS
FlorentinDUBOIS changed the base branch from refactor/mux-metric-events to main September 25, 2026 15:26
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 6ea04ca into main Sep 25, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the refactor/mux-metric-events-counters branch September 25, 2026 16:41
FlorentinDUBOIS added a commit that referenced this pull request Sep 25, 2026
…#1534)

Addresses **#1341 question 4 only** — the two helpers the H2 core reaches through, after the gauges
(#1530) and the counters (#1532). #1341 stays open; what remains is listed at the bottom.

#1532 has merged, so this branch now sits directly on `main` and the diff below is against it. It
was built on #1532 rather than on `main` deliberately, and that mattered: 3a's additions land in the
`MetricEvent` enum tail and the `record_metric` match body, which #1532 rewrote from 4 variants to
27 — the two places where a bad conflict resolution silently drops or mis-maps a metric, and the two
least amenable to counting occurrences afterwards. Building on `main` would have manufactured
exactly that conflict.

The rebase onto `main` was `--onto` from the old fork point; `git diff` between them is empty, so the
squash altered none of #1532's content, and the rebased tree is byte-identical to the pre-rebase
commit's (`4f9237d0` both). The three documents #1532 touched were still reset to the merged base and
their citations re-derived from `git show <main>:lib/src/protocol/mux/h2.rs` — a rebase reporting no
conflicts is not evidence, it is the condition under which a stale remap survives — and the
re-derived tree reproduced the auto-merge hash exactly, which makes that step a proof rather than a
precaution.

## What changed

`converter::H2BlockConverter` and `pkawa` are reached **in production only from `ConnectionH2`** —
verified by resolving the enclosing `impl`/`fn` of every caller by brace-matching, not grep, and
excluding `#[cfg(test)]` spans. So their metric sites were core-side even though neither type is the
core. Both now return `MetricEvent`s.

**`converter.rs` and `pkawa.rs` hold zero metric-macro sites.** `impl ConnectionH2` holds three,
down from 41 at the start of this series.

### Two different mechanisms, neither of them new

`H2BlockConverter` implements kawa's `BlockConverter<T>`, whose signature this repository does not
own, so a parameter is not available. Its events accumulate on the converter and
`H2ConverterPass::reclaim` hands them out — the **same `mem::take` that already reclaims `out`,
`lowercase_buf` and `cookie_buf`**. The pass lends its `Vec` and takes the allocation back, so a
stream that emits costs no allocation after the first pass, exactly as the three scratch buffers
already work.

`pkawa::handle_header` carries them on its **return**. It already takes ten parameters and an
`#[allow(clippy::too_many_arguments)]`, and #1341 rejected a twelfth parameter for Q5 on exactly
that ground. The return type already crosses the boundary, so the events travel on something that
was already there and the count stays at ten. `Vec::new()` does not allocate, so the path that
rejects nothing — the common one — costs nothing.

### The issue's inventory will mislead the next reader

#1341 lists pkawa as four metric sites. That counts the two `incr!` **inside** `metric_reject`.
The real shape is **23 production rejection call sites across four functions**
(`handle_header` 13, `handle_trailer` 5, `decode_headers_with_budget` 3, one in the
`store_or_reject!` macro body), all funnelling through that single emission point. That is why one
outbox reaches all 23, and why the test below tests the emission point rather than the sites.

`store_or_reject!` takes the outbox as a macro argument rather than referring to a caller-scope
`events`: `macro_rules!` locals are hygienic, so a bare identifier in the macro body would not bind
to the caller's binding.

## `RETRY_STALE_UPSTREAM` stays a macro, and the reason is now on the line

It is the only **labelled** metric site in the core. Carrying its cluster and backend labels in an
event means owned `Option<String>`s, and that was measured rather than estimated:

```
MEASURE  today=24  with_owned_labels=48  size_of::<Option<String>>()=24
```

`size_of::<MetricEvent>()` goes **24 → 48 bytes** — paid by *every* element of
`ConnectionH2::metric_events`, on behalf of a site that fires only on a stale-upstream retry — and
the enum loses `Copy`. Recording it in place is the cheaper half of that trade.

This corrects my own earlier framing of the cost, which said "allocating on the retry path": the
allocation is the smaller half. So the core ends this series at **one** macro site, not zero, and
that is the better outcome — a contorted zero would cost more than a documented one. The comment at
the site states the measurement so nobody re-derives it before "finishing the job".

## Seen red before trusted

```
reclaim_hands_the_converter_events_out_and_the_allocation_back
  recipe: delete `events.append(&mut converter.metric_events);` from `H2ConverterPass::reclaim`
  RED  exit 101 — "reclaim must move the converter's events into the caller's outbox"
       left: 0   right: 2
  restored -> GREEN exit 0

a_header_rejection_is_returned_not_recorded
  recipe: put `incr!(names::h2::HEADERS_REJECTED_TOTAL);` back at the top of `metric_reject`
  RED  exit 101 — "pkawa must not write METRICS: the rejection travels back to
       `ConnectionH2` as a MetricEvent and its shell records it"
       left: 1   right: 0
  restored -> GREEN exit 0   (both files byte-identical to the pre-recipe baseline, md5 checked)
```

The converter test pins **both** halves of `reclaim`'s contract, because they fail differently.
Losing the drain loses every `h2.frames.tx.*` a write pass produced — silently, since a converter
that emitted nothing and a drain that dropped everything are indistinguishable downstream. Losing
the reclaim turns a reusable buffer into a per-stream allocation on the write hot path, which
nothing would report at all.

## Citations

48 citations re-anchored from the fork point, remapped **once**, then audited on both keys —
byte-identical line text and identically-named enclosing `fn`.

One range was flagged by my own audit as having changed span: `mux/LIFECYCLE.md`'s citation of the
`Position::Server` arm of `ConnectionH2::end_stream`. Read rather than waved through, per #1531:
both endpoints still name the same code (`Position::Server => {` and its closing `}`), and the span
grew by exactly the 11 lines of the `RETRY_STALE_UPSTREAM` comment, which sits inside that arm. The
prose describes what the arm dispatches on and is unaffected. Benign, and stated because a
"span changed" that nobody reads is how a wrong citation survives.

## What is left in Q4, and what turned out already correct

Applying the principle that *a metric site whose owners are already shells needs no move* — `Router`
holds `BTreeMap<Token, Connection<SessionTcpStream>>`, i.e. concrete sockets, so it is shell by
construction, as are `Mux` and `ConnectionH1<Front: SocketHandler>`:

- **`ReplayCapture::try_arm`, its `Drop`, and `Stream::arm_upstream_replay` are already correct.**
  `arm_upstream_replay` has exactly one production caller, `ConnectionH1::start_stream`; every other
  caller is a test. #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 in a shell, which is precisely where a
  metrics `Drop` belongs. Not a defect. **This should be recorded as closed, not open.**
- Still open, and one question rather than three: `Position::count_bytes_{in,out}_counter` (4 sites)
  and `Stream::generate_access_log` (6 sites) are leaf helpers shared between the split core and the
  unsplit shells, reached from 7 `ConnectionH2` call sites. The `http.active_requests` pair is the
  same question a third time.
- `mux/mod.rs`'s two `log_context!`/`log_context_lite!` peer reads — a Q5-class observability
  defect, not a metrics-boundary change, getting its own PR.

## Validation

All at `a4940136b66f074e1c52cb5e0645668d1e0b2640`, 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 … -- -D warnings` — 0
- `cargo test -p sozu-lib …` — 1139 passed, 0 failed (+2, the two new tests; no test deleted, no `#[ignore]` added)
- `cargo test -p sozu …` — 0
- `cargo test -p sozu-e2e … -- --skip tests::fuzz_tests::` — 447 passed, 0 failed, with no other
  `sozu_e2e` process and a 1-minute load average of 7.78
- `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked` — 0
- `RUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets --locked -- -D warnings` — 0
- `check_doc_citations.py` `--self-test` / `--root .` / `--base <fork point>` / `--audit --root .` — all 0;
  the advisory audit's 7 findings are the same 7 as the base tree's
- `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]>
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.

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

1 participant