Repository navigation
refactor(mux-h2): return the connection gauges as MetricEvents (#1341 Q4) - #1530
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 25, 2026 13:35
FlorentinDUBOIS
force-pushed
the
refactor/mux-metric-events
branch
from
September 25, 2026 13:50
83572d4 to
f09562a
Compare
`ConnectionH2::gauge_connection_state` and `ConnectionH2::release_connection_gauges` no longer call `gauge_add!`. They push a signed-delta `MetricEvent` onto the core, and `H2Shell` records it into the worker-local `METRICS` aggregator through `record_metric`. The keys, the deltas and the aggregate a dashboard reads are unchanged; what changed is which layer writes them. The metric macros borrow a `thread_local!` aggregator, which is exactly the ambient process reach a byte-in / byte-out core gave up, and which a deterministic simulator has no way to observe. The in-repo precedent is `protocol/udp/`, whose core has zero metric-macro sites and emits `Output::Metric(MetricEvent)` for `crate::udp` to fold into `METRICS` and for `sim/tests/udp_simulation.rs` to fold into a shadow model. `impl Drop` moves from `ConnectionH2` to `H2Shell` with it, one layer up where `METRICS` legitimately lives. RAII is not given up: the shell owns the core, so the core cannot outlive the release, and because `H2Shell` now implements `Drop` the compiler additionally refuses to move `core` out of it. Losing that impl is the one failure with no symptom, so `dropping_a_connection_releases_its_ready_incremental_contribution` pins the round trip and its "To SEE THIS RED" recipe now names the new site. A second test, `the_core_queues_gauge_deltas_instead_of_writing_the_metrics_registry`, pins who writes, which no assertion on the aggregate's value can distinguish. Measured over `lib/src/protocol/mux/` at 6d6640b, counting code references rather than grep lines: 102 production metric-macro sites across the seven macros `lib/src/metrics/mod.rs` declares (`incr!` 57, `gauge_add!` 26, `count!` 17, `gauge!` 2; `decr!`, `time!` and `record_backend_metrics!` have none), none inside a `#[cfg(test)]` span, and 41 inside `impl ConnectionH2`. This changeset moves the eight in `gauge_connection_state` and `release_connection_gauges`; the remaining core sites keep calling the macros and both mechanisms end in the same aggregator. Part of #1341 Q4. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
refactor/mux-metric-events
branch
from
September 25, 2026 14:16
f09562a to
3a8f626
Compare
This was referenced Sep 25, 2026
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]>
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.
Addresses #1341 question 4 only — the H2 connection-level gauges and the
Dropthatrebalances them. It does not close #1341: Q4's remaining metric sites are listed below as
follow-up slices, and Q5 shipped in #1360.
What changed
ConnectionH2::gauge_connection_stateandConnectionH2::release_connection_gaugesno longercall
gauge_add!. They push a signed-deltaMetricEventonto the core, andH2Shellrecords itinto the worker-local
METRICSaggregator throughrecord_metric. The keys, the deltas and theaggregate a dashboard reads are unchanged; what changed is which layer writes them.
The metric macros borrow a
thread_local!aggregator, which is exactly the ambient process reacha byte-in / byte-out core gave up — and which a deterministic simulator has no way to observe, so
a core that wrote there could not be driven by one. The binding precedent is in-repo:
protocol/udp/'s core has zero metric-macro sites and emitsOutput::Metric(MetricEvent), whichcrate::udpfolds intoMETRICSandsim/tests/udp_simulation.rsfolds into a shadow modelinstead.
impl Dropmoves fromConnectionH2toH2Shellwith it, one layer up whereMETRICSlegitimately lives. RAII is not given up: the shell owns the core, so the core cannot outlive the
release, and because
H2Shellnow implementsDropthe compiler additionally refuses to movecoreout of it.Recording moves from the emit site to the end of the shell's step —
H2Shell::settled, so afterevery
readable,writable,start_streamandcancel_timed_out_streams— or toDrop. Thequeue is FIFO and its values are signed deltas, so a step that reaches neither records the same
sum at the next drain rather than losing it. In this changeset the only producer is
gauge_connection_state, reached only through the write pass, so every event is recorded at theend of the pass that produced it.
The leak this had to not introduce
Losing the
Dropis the one failure with no symptom: every live connection's contribution wouldleak upward permanently, with no resync and no underflow to notice. Two tests pin it, both seen
red before they were trusted.
dropping_a_connection_releases_its_ready_incremental_contribution(pre-existing) still pinsthe round trip through
METRICS. Its "To SEE THIS RED" recipe now names the new site: deletingself.core.release_connection_gauges();fromimpl Drop for H2Shellfails it withleft: 3, right: 0. Applied and observed, restored and observed green.the_core_queues_gauge_deltas_instead_of_writing_the_metrics_registry(new) pins who writes,which no assertion on the aggregate's value can distinguish — a core that emitted directly and a
shell that records what the core queued leave the aggregate identical. Its recipe (put
gauge_add!(names::h2::STREAMS_READY_INCREMENTAL_BY_URGENCY, dr);back ingauge_connection_state) fails it withleft: 5, right: 0. Applied and observed too.lib/tests/metric_names.rs's own recipe was repointed atrecord_metricand re-verified the sameway: it reports
src/protocol/mux/h2.rs:73: gauge_add!("h2.streams.ready_incremental.by_urgency", …).Measurement
Two figures in #1341 do not reproduce, so both were re-measured at
6d6640bf, counting codereferences (comments, doc comments and prose excluded by masking them out;
#[cfg(test)]spansclassified separately) rather than grep lines.
lib/src/protocol/mux/holds 102 production metric-macro sites across the seven macroslib/src/metrics/mod.rsdeclares —incr!57,gauge_add!26,count!17,gauge!2, anddecr!,time!,record_backend_metrics!zero each. Zero are inside a#[cfg(test)]span.The naive line count over the four macros the issue named is 115; the 15-site gap is entirely doc
comments and line comments quoting a macro. The "roughly 236" figure does not reproduce under any
macro list.
By owning type: 41 in
impl ConnectionH2, 16 inMux, 9 inConnectionH1, 8 inH2BlockConverter, 8 inStream/ReplayCapture, 5 inRouter, 4 inPosition, 4 inanswersfree functions, 4 in
pkawafree functions, 3 inConnection. This changeset moves the eight ingauge_connection_stateandrelease_connection_gauges, leaving 33 inimpl ConnectionH2.The issue's "roughly fifteen sites need the peer address supplied into the core" is zero for
h2.rstoday: bothlog_context!andlog_context_stream!already read$self.peer_address, afield
ConnectionH2snapshots at construction, across 113 production expansions. The tworemaining live
peer_addr()reads inmux/aremod.rs's two macro definitions, which sit inMux— the shell — so they cross no core/shell boundary; they are the same Q5-class observabilitydefect and belong in their own changeset.
Follow-up slices (not in this PR)
impl ConnectionH2counter sites. Mechanical, except for the six computed keys(
metric_for_rst_stream_sent,metric_for_goaway_sent,h2_frame_rx_metric_key, …) whichbecome event payloads, and
names::backend::RETRY_STALE_UPSTREAM, whose cluster/backend labelsare borrowed
&str.http.active_requests: its+1is inConnectionH2::handle_headers_frameand its paired-1in
Stream::generate_access_log, so the pair should move together rather than be split here.impl ConnectionH2:Position::count_bytes_{in,out}_counter(called from
handle_read/handle_write/consume_zero_flush),Stream::generate_access_log(called from four
ConnectionH2methods),pkawa::metric_reject/handle_trailer(reachedthrough
pkawa::handle_headerfromhandle_headers_frame), andH2BlockConverter.ReplayCapture'sDrop(stream.rs) is a second metricsDropinlib/src/. h2 sans-io: metrics and log context across the boundary (Q4, Q5) #1341 recordsthe
ConnectionH2one as the only one; that is not true at this tree, and the correction isrecorded here rather than acted on.
mod.rs's twolog_context!/log_context_lite!peer reads.This changeset deliberately touches neither
lib/src/protocol/mux/mod.rsnorlib/src/protocol/mux/router.rs, which is where #1525 and #1527 make their changes. It doesshare three files with them, measured against their current file lists:
CHANGELOG.md,doc/testing.mdandlib/src/protocol/mux/LIFECYCLE.mdwith both #1525 and #1527, andCHANGELOG.md+doc/testing.mdwith #1529; no overlap at all with #1528. The CHANGELOG entryis appended at the END of the Unreleased
Changedsection rather than the top, so it does notcollide with theirs. In
LIFECYCLE.mdanddoc/testing.mdthe hunks are one prose paragraphplus re-anchored
h2.rscitations; neither of those PRs editsh2.rs, so their own citationsinto it are untouched. Whichever of us lands second must reset those two files to the merged
base and re-derive the re-anchoring from
git show <merged-base>:lib/src/protocol/mux/h2.rs,never re-apply a remap on already-remapped numbers.
Validation
All run locally at
83572d4d, exit codes read directly.cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd— 0cargo +nightly fmt --all -- --check— 0cargo clippy --all-targets --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -- -D warnings— 0cargo test -p sozu-lib …— 1133 passed, 0 failed (+1 vs base, the new test);metric_namesandlog_layoutgreencargo test -p sozu …— 113 passed, 0 failedcargo test -p sozu-e2e … -- --skip tests::fuzz_tests::— 447 passed, 0 failed (run with no othersozu_e2eprocess and a 1-minute load average of 4.39)RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked— 30 passed, 0 failedRUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets --locked -- -D warnings— 0python3 .github/scripts/check_doc_citations.py--self-test/--root ./--base 6d6640bf/--audit --root .— all 0. 45 re-anchored spans (43 distincth2.rsendpoints, two of them cited twice) were exempted from the drift comparison; every one was audited on both keys (byte-identical line text and identically-named enclosingfn) with zero failures, and the advisory audit's seven findings are byte-identical to the base tree's.RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked— 0cargo bench -p sozu-lib --bench h2_stream_table -- --test— 0No production numeric literal in the diff is shared with the tests: the only literals added outside
comments (
16384,2,4,5) are all inside the new test body, so the change is not test-shaped.