Skip to content

refactor(mux-h2): return the shared leaves' metrics as MetricEvents (#1341 Q4) - #1537

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

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

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

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. h2 sans-io: metrics and log context across the boundary (Q4, Q5) #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 aaf2a6aa / --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]

`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. 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, and `impl Position` holds none.

The return is bounded and lives on the stack, with no container at all.
`bytes_in_event`/`bytes_out_event` return exactly one `MetricEvent` —
both match arms emit one — and `generate_access_log` returns
`[Option<MetricEvent>; 2]`. That matters because `generate_access_log`
is allocation-free today, measured: zero `to_owned`, `to_string`,
`format!`, `String::`, `Vec::`, `vec!`, `collect`, `clone` or `Box::`
across its 164-line body. A `Vec` return would have introduced the first
allocation, 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.

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.

`#[must_use]` on both returns makes the eight callers a compiler
obligation rather than a convention; it found all ten call sites at
once. `ConnectionH2::complete_server_stream` is static — its `stream`
borrows `context.streams` — so it propagates through its own return.

Three sites in `generate_access_log` stay `incr!` macros, documented at
the site: they carry cluster/backend labels, and carrying those in an
event means owned `Option<String>`s — `size_of::<MetricEvent>()` 24 ->
48 bytes for every queued event, and the enum loses `Copy` — for sites
that fire on every access log. Eight sites moved, three documented.

`http.active_requests` is now deliberately split across two mechanisms.
That is safe because each PATH balances, not because the pair travels
together, and two e2e tests pin it per path.

The reference sweep on the rebased base found one stale prose hit: a
comment in `e2e/src/tests/h2_tests.rs` naming the removed
`Position::count_bytes_in_counter`. It now names
`Position::bytes_in_event` and says the event is queued on the core and
recorded by the shell. Line-count-neutral; nothing cites that file.

Part of #1341 Q4.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the refactor/mux-metric-events-shared branch from 5278e6c to 0d7986b Compare September 25, 2026 19:32
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 23626b1 into main Sep 25, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the refactor/mux-metric-events-shared branch September 25, 2026 20:30
FlorentinDUBOIS added a commit that referenced this pull request Sep 25, 2026
)

## The bypass

The per-`(cluster, source-IP)` limiter has no concept of a subnet. Someone on an
IPv6 `/64` — the standard residential allocation — bypasses it **entirely** by
taking a fresh address for every connection: the per-address counter never
reaches 2. Reported by @jpds in #1270 from reading the release notes and the
limiter code.

## The shape: two independent limiters

Per @FlorentinDUBOIS in the issue:

> I think we need both as the current rate limit is for handling rate limit by
> ip as an api gateway, and the subnet aware will be there for ddos purposes.

So this adds a **second, independent counter** rather than changing the first.
`cluster_ip_at_limit`, `track_cluster_ip`, `effective_max_connections_per_ip` and
both per-IP maps are untouched — same fields, same semantics, same bodies. What
did change around them: the two call sites now go through a combined gate, and
`untrack_all_cluster_ip` also drains the subnet slots (it is the single release
point all three protocols already call on close, and a second entry point would
be one more thing each could forget). Both gates are consulted on every admission
and **both must admit**, which is what makes "10 per IP **and** 100 per /64"
expressible:

```toml
max_connections_per_ip     = 10     # existing, untouched
max_connections_per_subnet = 100    # new
subnet_ipv4_prefix         = 24
subnet_ipv6_prefix         = 56
```

The conjunction lives in exactly one place, `SessionManager::cluster_connection_at_limit`,
so the H1+H2 mux and raw TCP cannot drift on what "admitted" means.

## The defaults leave current behaviour intact

`max_connections_per_subnet` defaults to `0` (disabled) and the prefixes default
to `/32` and `/128`, which mask nothing. An upgrade is inert until an operator
opts in. `/24` and `/56` are **documented recommendations**, not defaults —
matching what the reporter did in the equivalent Caddy module (default left at
single IPs, those prefixes highly recommended in the docs). They are written up
in `doc/configure.md` and `doc/rate-limit-design.md` §7.1.1.

Stronger than inert: while the cap is `0` the subnet bookkeeping is **not written
at all**, so a deployment that never enables the feature allocates nothing for it.
`an_unset_subnet_cap_leaves_the_admission_path_untouched` asserts both maps stay
empty. This is a **deliberate divergence from the per-IP twin**, which tracks
unconditionally — flagging it explicitly as the point where you may want to
decide otherwise. The cost is that enabling the cap at runtime does not
retroactively count sessions already in flight; the counter converges as they
close.

## New configuration surface

Global TOML keys (`command/src/config.rs`):

| Key | Type | Default |
|---|---|---|
| `max_connections_per_subnet` | integer, 0 = unlimited | `0` |
| `subnet_ipv4_prefix` | integer 0-32 | `32` |
| `subnet_ipv6_prefix` | integer 0-128 | `128` |

Plus a per-cluster `max_connections_per_subnet` override with the same
`None` inherits / `Some(0)` explicit-unlimited / `Some(n)` overrides semantics as
its per-IP twin. Out-of-range prefixes are **rejected** at config-load time
(`ConfigError::InvalidSubnetPrefix`), never silently clamped.

### Additions to `command.proto`, named explicitly

| Message / field | Tag |
|---|---|
| `Request.set_max_connections_per_subnet` (uint64) | 60 |
| `Request.query_max_connections_per_subnet` | 61 |
| `message QueryMaxConnectionsPerSubnet {}` | — |
| `message MaxConnectionsPerSubnetLimit { limit, ipv4_prefix, ipv6_prefix }` | — |
| `ResponseContent.max_connections_per_subnet_limit` | 18 |
| `Cluster.max_connections_per_subnet` (optional uint64) | 17 |
| `ServerConfig.max_connections_per_subnet` | 26 |
| `ServerConfig.subnet_ipv4_prefix` | 27 |
| `ServerConfig.subnet_ipv6_prefix` | 28 |

`command/src/proto/command.rs` is generated and was not edited.

### CLI

New `sozu subnet-connection-limit {set|remove|show}`, mirroring
`sozu connection-limit`. `show` reports the two prefixes alongside the limit:
they are boot-time only, so that reply is the only runtime surface that can tell
an operator what the live cap is a cap *on*. Like its twin the setter is
non-sticky — workers reset to the TOML value on restart.

The prefixes have no runtime setter on purpose: the mask is part of the counter
key, so patching it live would re-key every counter in flight.

## Masking

`Ipv4Addr` / `Ipv6Addr` have no standard masking method and no dependency was
added. Both shift-overflowing bounds are branched explicitly — `u128::MAX << 128`
panics under `debug_assertions` and wraps silently in release, so a full-width
prefix must never reach the shift; a zero prefix is branched from the other end.

**IPv4-mapped IPv6 sources are canonicalised first.** A dual-stack `[::]` listener
reports an IPv4 client as `::ffff:a.b.c.d`; masking that with an IPv6 prefix would
collapse the entire IPv4 internet into one `::/56` bucket, so it is converted to
IPv4 and charged to `subnet_ipv4_prefix`. The per-IP counter is deliberately left
un-canonicalised — part of what keeps its behaviour untouched.

## To SEE THIS RED

Delete the `|| self.cluster_subnet_at_limit(...)` disjunct from
`SessionManager::cluster_connection_at_limit` in `lib/src/server.rs`, leaving
every other piece — config keys, proto fields, masking, tracking — in place:

```
cargo test -p sozu-lib --locked --no-default-features \
  --features crypto-ring,opentelemetry,splice,simd subnet
```

```
test ...::a_subnet_cap_refuses_a_fresh_address_from_an_already_counted_subnet ... FAILED
panicked at lib/src/protocol/mux/router.rs:
a fresh address from an already-counted /24 must be refused — an Admitted
verdict here is the #1270 bypass: a new address per connection defeats the cap
```

The test drives the real `plan_connect` → `consult_ip_gate` → `plan_connect_resume`
sequence for four **distinct** addresses in one `/24`, under a per-IP cap of 10 that
no single address comes near — so only the subnet counter can refuse the fourth.
A fifth address in a *different* `/24` is asserted admitted, so the refusal is the
subnet key and not a blanket cap on new addresses.

Restoring the disjunct returns it to green; the cycle was run twice.

## Tests added

- `a_subnet_cap_refuses_a_fresh_address_from_an_already_counted_subnet` — the regression above.
- `an_unset_subnet_cap_leaves_the_admission_path_untouched` — the default changes nothing, and allocates nothing.
- `a_cluster_override_dropping_to_zero_after_a_track_is_a_no_op` — a cluster override can drop to `Some(0)` after a session was tracked under a positive limit (`AddCluster` is an upsert and clears no counters; only the *global* `SetMaxConnectionsPerSubnet(0)` drains). An earlier revision asserted that could not happen and panicked on it.
- `masking_handles_both_shift_overflowing_prefix_bounds` — prefixes 0, full width, and over-wide.
- `masking_groups_addresses_at_the_recommended_prefixes` — /24 and /56, including the issue's own `/64`-holder scenario.
- `an_ipv4_mapped_source_is_charged_to_the_ipv4_prefix` — including the negative case where two mapped `/24`s must not collide.
- `subnet_connection_limit_keys_round_trip_from_toml` and `an_out_of_range_subnet_prefix_is_rejected_not_clamped` — the config plumbing and its validation.

## Known limitation

A subnet refusal currently surfaces as `BackendConnectionError::TooManyConnectionsPerIp`
and increments the shared `connections.rejected_per_cluster_ip` counter, so an
operator cannot tell the two caps apart in metrics. Kept shared to hold this
changeset to the feature; a distinct error variant and counter are a reasonable
follow-up.

## Validation

All run locally at the tip of this branch, rebased onto `main` at `42ed1111`
(after #1537 and #1540 landed); CI is the verdict.

The rebase over #1537 conflicted only on line citations, in `doc/testing.md` and
`lib/src/protocol/mux/LIFECYCLE.md` (13 hunks). Each was resolved by locating the
text the citation named at the merge base inside the merged tree, never by
arithmetic; the resulting diff on those two files is citations only — every
removed line has an identical added counterpart once the digits are stripped, so
none of #1537's prose was altered.

| Command | Result |
|---|---|
| `cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd` | pass |
| `cargo +nightly fmt --all -- --check` | pass |
| `cargo clippy --all-targets --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -- -D warnings` | pass |
| `cargo test -p sozu-lib …` | 1147 passed, 0 failed |
| `cargo test -p sozu …` | pass |
| `cargo test -p sozu-command-lib --locked --no-default-features` | 171 passed, 0 failed |
| `cargo test -p sozu-e2e … -- --skip tests::fuzz_tests::` | 449 passed, 0 failed |
| `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked` | pass |
| `RUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets --locked -- -D warnings` | pass |
| `check_doc_citations.py --self-test / --root . / --base / --audit --root .` | all pass |
| `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` | pass |

> **Note on the two config tests — resolved since this PR was opened.**
> `subnet_connection_limit_keys_round_trip_from_toml` and
> `an_out_of_range_subnet_prefix_is_rejected_not_clamped` live in
> `command/src/config.rs`. When this PR was first pushed, CI ran `cargo test` for
> `sozu-lib`, `sozu`, `sozu-e2e` and `sozu-sim` but **never** for
> `sozu-command-lib`, and there was no workspace-wide `cargo test` anywhere — so
> these two would have landed without ever running. That gap was reported as
> [#1539](#1539), and
> [#1540](#1540) landed the step that shut it;
> it is now in `main`.
> This branch is rebased on top of it, so CI does exercise both tests.

Docs updated in the same changeset: `doc/configure.md`, `doc/rate-limit-design.md`
(§3.1, §3.2, §3.3, §3.7, §3.8, §7.1.1), `bin/config.toml`, `CHANGELOG.md`. Line
citations displaced by the insertions were renumbered and each renumbered bound
verified against the text it named at the base.

> **On the renumbering, for `check_doc_citations.py`'s own record.** The first
> automated pass produced **three wrong ranges** on lines whose text is ambiguous
> (a bare `}`), two of them inverted. The checker caught two. The third —
> `lib/src/server.rs:1060-1068`, which should have been `1056-1064` — **passed
> silently, because a citation this changeset re-anchored is exempt from the
> base comparison and is never checked at all** (the run reports this honestly:
> "39 re-anchored spans were exempt from the comparison"). It was only found by
> auditing all 29 renumbered bounds content-against-content, resolving each one
> through the text it named at the base. Another agent hit the same mechanism on
> a different changeset today, so this is an independent confirmation that the
> re-anchoring exemption is a real hole, not a theoretical one: the rule cannot
> guard precisely the citations a changeset touches, which are the ones most
> likely to be wrong.

Closes #1270

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 26, 2026
…ed after (#1541)

`e2e/src/tests/mux_tests.rs` carried three tests named after `http.active_requests` — "H1 idle
timeout does not underflow", "H1 malformed request does not underflow", "H1 100 Continue does not
double-decrement" — under a file header advertising "P0: close() stream cleanup
(http.active_requests gauge leak)". **None of the three read the gauge.** The first opened five
connections, waited out their 408s, then asserted that a *later* request answered 200 — an assertion
that holds identically with or without an underflow.

## Why they could not have been written in that shape

`AggregatedMetric::update` clamps a negative `GaugeAdd` to exactly 0 and logs an `error!`. The clamp
is deliberate and correct: a `clear()` under live traffic can legitimately drive a paired decrement
below a freshly reset baseline. Its consequence here is that "does not underflow" is **not
observable from the gauge's value** when the gauge starts at zero.

```
correct            0 -> 1 -> 0
parasitic -1       0 -> 0        indistinguishable from the line above
```

The property the three tests were named for is one their shape could not express. They were written
for a change whose regression they therefore never witnessed.

## The shape that makes it observable

`http.active_requests` is per worker process, not per connection. `hold_one_request_in_flight` puts
ONE legitimate request in flight on its own connection — held at the backend between
`backend.receive` and `backend.send`, an ordering guarantee rather than a sleep — and proves the
gauge reads exactly `1`. The scenario under test then runs on *other* connections, and the assertion
is that the gauge still reads exactly `1`. A parasitic decrement takes it to `0`, which is
observable. Releasing the held request afterwards takes the gauge to `0` and pins the decrement a
charged stream does owe.

```
correct            1 -> 1 -> 0
parasitic -1       1 -> 0        (the unchanged-gauge assertion fails)
```

Built on #1537's tooling rather than beside it: `query_proxy_gauge` and `await_active_requests_h1`
are reused as they are, including the property that `None` is never folded into `0` — "the key does
not exist" and "the gauge reads zero" stay two observations, which is exactly what the three hollow
tests could never distinguish. Two helpers are added:

- `expect_active_requests_h1` takes a SINGLE sample, deliberately not a poll. A poll for a value the
  gauge already holds returns on its first iteration without ever observing the scenario — the
  vacuity this changeset is about.
- `raw_read_until_eof` is the barrier that earns that single sample. A stream's access log, and with
  it the `-1`, is emitted before sozu shuts the frontend socket down, so a client that has read EOF
  has already been passed by every decrement that connection can emit. A deadline is reported as an
  error rather than folded into the bytes read.

`setup_short_timeout_test` now shortens `request_timeout` and nothing else. Which one is shortened is
load-bearing, not frugality: `request_timeout` is the timeout a frontend is armed with before its
first request links, so it alone decides how fast a silent connection collects its 408, while a
two-second `front_timeout` or `back_timeout` would answer the *held* request 504 and emit a
perfectly legitimate `-1`. The gauge would then read zero for a correct proxy, which is
indistinguishable from the underflow the test exists to catch.

## The reds — there are two, not three

Each was obtained by removing one production guard on otherwise unmodified code. The production diff
of this branch is empty: `git diff --name-only` is `CHANGELOG.md`, `doc/testing.md` and
`e2e/src/tests/mux_tests.rs`.

**Dropping the `if self.request_counted` condition in `Stream::generate_access_log`**
(`lib/src/protocol/mux/stream.rs`), leaving `events[0] = Some(MetricEvent::ActiveRequestFinished);`
and `self.request_counted = false;` unconditional:

```
test tests::mux_tests::test_100_continue_no_double_decrement ... ok
test tests::mux_tests::test_malformed_request_no_underflow ... FAILED
test tests::mux_tests::test_idle_timeout_no_underflow ... FAILED
malformed: the 400s moved the gauge - wanted 1, sample Some(0)
idle-timeout: the 408s moved the gauge - wanted 1, sample Some(0)
test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 450 filtered out
```

The idle-timeout and malformed tests fall **together**, and that is the structure of the code rather
than a shortcut. Both scenarios reach the same access log on the same never-charged stream, and
there is no second guard between "no `+1`" and "no `-1`" to remove — two scenarios through one
guard, not two guards. No third distinct red was invented to disguise it.

**Deleting the `kawa::StatusLine::Response { code: 100, .. }` arm in `ConnectionH1::writable`**
(`lib/src/protocol/mux/h1.rs`), so a 100 falls through to the generic completion path:

```
test tests::mux_tests::test_malformed_request_no_underflow ... ok
test tests::mux_tests::test_idle_timeout_no_underflow ... ok
test tests::mux_tests::test_100_continue_no_double_decrement ... FAILED
100-continue: the interim response released the charge - wanted 2, sample Some(1)
test result: FAILED. 2 passed; 1 failed; 0 ignored; 0 measured; 450 filtered out
```

That red is isolated, and it is observable only **between the 100 and the 200**: once the final
response has landed the gauge is back at the held baseline in the correct tree *and* in the mutated
one, because `request_counted` makes a second access log harmless. So the test samples while the
client holds its 100 and the backend still holds the 200.

**A third candidate was measured and rejected.** Removing the `self.request_counted = false;` clear
reddens nothing *by the gauge*: it trips its own `debug_assert!` at the same site first
(`generate_access_log must leave request_counted false (gauge-underflow guard)`), killing the worker
in all three tests. It could not have reddened them by the gauge anyway — no production path calls
`generate_access_log` twice on one stream, because the completion path clears `metrics.start`
through `stream.metrics.reset()` and `Mux::close` skips every stream whose `metrics.start` is
`None`. The 100-Continue test's doc comment records that, so its closing assertion is not read as
covering an idempotency guard no end-to-end test can reach.

After each red the mutated file was restored from `git show HEAD:<path>` and compared byte for byte
against a pre-mutation copy with `cmp`, and the three tests were re-run green.

## Also

The file header no longer advertises a property it did not cover, and `doc/testing.md`'s gauge
section gains the held-baseline technique together with its two rules — hold the baseline longer
than the scenario, and sample once after a barrier instead of polling.

Closes #1535

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