Skip to content

fix(mux-h1): bound the stale-upstream replay captures and account for them - #1470

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
fix/retry-buffer-capture-ceiling
Sep 23, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
fix/retry-buffer-capture-ceiling

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Closes #1450.

ConnectionH1::retry_buffer — the stale-upstream replay capture introduced by #1442 — is a plain
Vec on the global allocator, outside sozu's buffer Pool. It is not a leak and it is not unbounded,
but it is unaccounted, and the bound it has is an accident of a different knob.

The bound nobody would guess

A capture can only exist on a live stream, and Stream::new takes exactly two pool.checkout()
calls. So captures are transitively bounded at (max_buffers / 2) × buffer_size.

At stock defaults — max_buffers 1000, buffer_size 16393 — that is ≈8.2 MB carried, not the
~160 MB a naive max_connections × buffer_size estimate gives. That estimate is wrong by a factor of
20, because it assumes 10000 concurrent requests that max_buffers 1000 does not permit. Reaching
160 MB needs max_buffers raised to ~20000.

So the true statement was: pooled idempotent traffic costs up to +50% on the pool's own worst-case
footprint
, in memory no max_buffers accounting can see.

Why the captures are not moved into the Pool

max_buffers defaults to 1000 against max_connections 10000 — deliberately oversubscribed 10:1 and
rationed by parked_on_buffer_pressure / MaxBuffers.

Pool allocation would convert today's graceful degradation — we decline to retry, the client gets the
502 it would have got anyway
— into we refuse new sessions with 503 and park frontends, under
exactly the memory pressure the bound exists to manage.

What this does instead

A worker-wide ceiling that disarms capture past it. Beyond MAX_ARMED_REPLAY_CAPTURES = 512,
arm_upstream_replay installs no buffer; the request proceeds un-replayable and a stale pooled
upstream yields the same 502 it yields today. Nothing is refused, nothing parks.

512 sits just above the 500 concurrent captures stock configuration permits, so the ceiling does not
bite at defaults
— an existing deployment replays exactly what it replayed before. What it removes
is the growth: ≈8.4 MB whatever max_buffers becomes, where before it was linear.

Two metrics, because an invisible heap proportional to a fraction of the pool is not an operational
signal: backend.retry.captures_armed (gauge) and backend.retry.captures_declined (counter).

A non-idempotent request is now refused the charge up front. The method is known at arm time — set in
HttpContext::on_request_headers during the frontend parse, long before Router::connect reaches
start_stream — and only an idempotent method can ever spend a capture. Without that guard, an
80%-POST pooled workload would spend ~4 in 5 of its 512 slots on charges that can never be used,
silently cutting the effective ceiling to ~102. captures_declined deliberately does not count
the method veto: it counts refusals for budget, and a method veto is not one.

The charge is owned by Drop, and that is the whole design

retry_buffer goes Some → None on four functions — forget_upstream_replay, the first response
byte, the one-front-buffer overflow, queue_upstream_replay — and on a fifth path with no code site
at all
: the Stream simply being dropped on a client hangup, an idle timeout or session teardown.

Wired into the four, the counter would climb on every such teardown until the ceiling silently
disarmed replay for the worker's lifetime. So the charge is a field of a ReplayCapture newtype and
is released by its impl Drop. Same reasoning ConnectionH2's gauge teardown and pool::Checkout
already apply.

The counter is a thread_local! Cell, not a process-wide static: a worker is one event-loop thread,
its Pool is an Rc<RefCell<Pool>> that cannot leave it, and METRICS is itself thread_local!. A
shared static would let one worker exhaust another's budget while their gauges disagreed about it.

Memory figure: state the allocated number, not the carried one

h1.rs grows a capture with Vec::reserve, which is amortized, so a capture assembled over several
partial writes holds up to one doubling more capacity than bytes. Measured:

writes=[16393]          len=16393 cap=16393   512x -> carried 8.0 MB / allocated  8.0 MB
writes=[8192, 8192, 9]  len=16393 cap=32768   512x -> carried 8.0 MB / allocated 16.0 MB

Every surface now states 2 × 512 × buffer_size ≈ 16.8 MB allocated against ≈8.4 MB carried, and
doc/configure.md says to size RSS against the larger figure. The slack loosens the constant by a
factor of two; it does not make it depend on max_buffers again, which is the property the ceiling
exists to deliver.

Tests seen red

Each revert produced its own assertion's message, not a debug_assert! and not a sibling's:

mutation test that reddens
delete the ceiling early return in try_arm past_the_ceiling_a_pooled_request_is_armed_with_no_buffer_and_still_completes
delete the arming gauge_add! the_armed_gauge_and_the_declined_counter_track_the_capture_budget
delete the releasing gauge_add! same
replace the declined incr! with {} same
delete the budget release from Drop a_stream_dropped_with_a_capture_armed_releases_its_charge
mem::forget(self) in into_bytes queueing_a_replay_releases_the_capture_charge
drop the idempotence conjunct from the arm guard a_non_idempotent_request_is_never_charged_to_the_capture_budget

The last-but-one is the one that matters most. into_bytes is the single place that has to work
around Drop to move the Vec out, and review found that the natural "simplification" a later
contributor reaches for — mem::take plus mem::forget — leaked a charge per replay while the
entire unit suite stayed green. Exactly one test now fails on it, and it is the one that means to.

Two traps were designed around rather than discovered: the ceiling test also asserts the
under-ceiling case installs a capture, so it cannot pass against an arm_upstream_replay that arms
nothing; and the budget fill is a bounded for 0..MAX, not while try_arm().is_some(), which would
hang instead of failing if the ceiling were absent.

Adding the arm guard made can_replay_on_fresh_upstream's own idempotence conjunct unreachable in
production. The conjunct is kept — it is the one a later widening of the arm guard would silently
undo — and the two tests that pin it were adapted to arm under Method::Get and set the method
afterwards, so they keep observing the conjunct rather than quietly starting to observe the new guard.

Empirical check that the guard did not break arming: test_issue_806, which #1460 measured red 25 of
25 with replay disabled, is green 8 of 8 with the guard in place.

Verification

cargo +nightly fmt --all -- --check                   exit 0
cargo build  --locked …                               exit 0
cargo clippy --all-targets --locked … -D warnings     exit 0   0 warnings
cargo test -p sozu-lib --locked …                     exit 0   1035 passed, 0 failed
cargo test -p sozu     --locked …                     exit 0   113  passed, 0 failed
check_doc_citations.py --root .                       exit 0
check_doc_citations.py --base f2082b6e                exit 0

cargo test -p sozu-e2e is left to CI: the local box was running two concurrent copies of that suite
at load 205 on 20 cores, which is not a condition it is safe to run under — it binds loopback ports.
Prior runs of essentially this code gave 446 passed / 0 failed, and a control run on unmodified
main failed 445/1 on an unrelated test under the same load.

No production dependency growth. No async fn in lib/ or bin/. Metric names go through
names:: constants, which lib/tests/metric_names.rs enforces statically.

Documentation

doc/configure.md states the transitive (max_buffers / 2) × buffer_size relationship on the
max_buffers row itself — where an operator sizing that value will actually look — and a new
"Capture budget" section carries the arithmetic, why pooling was rejected, and the per-worker scope.
lib/src/protocol/mux/LIFECYCLE.md gains the fourth arming condition beside the existing three, and
its claim that "the replay is bounded by CONN_RETRIES alone" is corrected.

… them

`Stream::retry_buffer` (added with the replay itself, #1442) is a
plain allocation on the global allocator, outside the buffer `Pool`. It is not a
leak and it is not unbounded, but it was unaccounted, and the bound it had was an
accident of a different knob: a capture can exist only on a live stream and
`Stream::new` takes exactly two `pool.checkout()` calls, so captures were
transitively bounded at `(max_buffers / 2) * buffer_size`. At the defaults
(`max_buffers` 1000, `buffer_size` 16393) that is about 8.2 MB and it is linear in
`max_buffers` from there. The obvious `max_connections * buffer_size` estimate
gives ~160 MB and is wrong by a factor of 20, because `max_buffers` does not
permit 10000 concurrent requests; reaching 160 MB needs `max_buffers` raised to
about 20000. No `max_buffers` accounting could see any of it.

Pool allocation is rejected. `max_buffers` defaults to 1000 against
`max_connections` 10000, oversubscribed 10:1 and rationed by
`parked_on_buffer_pressure` / `MaxBuffers`, so putting the captures in the pool
would convert today's graceful degradation -- "we decline to retry, the client
gets the 502 it would have got anyway" -- into "we refuse new sessions with 503
and park frontends", under exactly the memory pressure the bound exists to
manage.

`MAX_ARMED_REPLAY_CAPTURES` disarms capture past the ceiling instead:
`Stream::arm_upstream_replay` installs no buffer, the request proceeds
un-replayable, and a stale pooled upstream yields the same 502 it yielded before
the replay existed. Nothing is refused and no frontend parks.

512 is chosen against that arithmetic. The defaults can produce at most 500
concurrent captures, which fits under the ceiling, so a stock deployment replays
exactly what it replayed before -- what the ceiling removes is the growth, holding
the capture heap near `512 * 16400` ~= 8.4 MB however high `max_buffers` is
raised. It is a constant rather than a configuration key because the only value it
wants is "high enough not to bite at the stock defaults", because it is a
memory-safety bound rather than a tuning knob, and because
`backend.retry.captures_declined` is the operational signal for the case where it
binds. `CONN_RETRIES` and `MAX_PENDING_RST_STREAMS` are the same class of bound
stated the same way. The cost of the constant is stated rather than hidden: an
operator cannot lower it, only observe it.

The budget counts captures, not bytes, and that is a memory bound rather than a
proxy for one because each capture is already independently bounded -- a write
that would carry one past its front kawa's `storage.capacity()` drops it whole
(`ConnectionH1::writable`), which is HAProxy's "Requests not fitting in a single
buffer will never be retried". A byte budget would have to be maintained on every
`extend_from_slice` of the write path to bound the same product, and would
additionally be able to refuse a capture mid-growth that the code had already
decided to hold.

That guard bounds a capture's LENGTH, not its capacity. `ConnectionH1::writable`
grows the copy with `Vec::reserve`, which allocates `max(2 * old_capacity,
required)`, so the allocated figure can be twice the carried one. Measured on this
tree at the defaults: a single 16393-byte write gives `len/capacity 16393/16393`,
while writes of `[8192, 8192, 9]` give `16393/32768`. The bound is therefore
`2 * MAX_ARMED_REPLAY_CAPTURES * buffer_size`, about 16.8 MB allocated against
8.4 MB carried, and every surface that states a figure now states that one and
says which is which. The factor of two loosens the constant; it does not make it
depend on `max_buffers` again, which is the property the ceiling exists to
deliver.

Only an idempotent request is captured. A capture for a non-idempotent one could
never be spent, since `can_replay_on_fresh_upstream` vetoes the method, so
`arm_upstream_replay` no longer takes a charge for it. Before the ceiling that was
pure waste; with a ceiling it is also a slot a replayable request cannot have --
at 80% POST on a pooled workload only about one armed charge in five would have
been spendable, an effective ceiling near 102, while `backend.retry.captures_armed`
sat at 512 telling an operator nothing about why. The method is known at arm time:
`HttpContext::on_request_headers` sets it during the frontend parse and
`Router::connect` routes on it -- `route_from_request` fails with
`RetrieveClusterError::NoMethod` without it -- before reaching `start_stream`,
this function's sole caller. Confirmed end to end as well: `test_issue_806`, which
#1460 measured at 25 red runs of 25 with the replay disabled, is green on 5 runs
of 5 with the guard in place.

That makes `can_replay_on_fresh_upstream`'s own idempotence conjunct unreachable
in production rather than redundant by accident. It is deliberately KEPT as
defense in depth: it is the conjunct a later widening of the arm guard would
silently undo, and the one the whole feature's justification rests on (RFC 9110
§9.2.2). Its two `mod.rs` tests still redden when it is dropped; their fixture now
arms under `Method::Get` and sets the method under test afterwards, with the
reason stated in place. Measured rather than asserted: with that conjunct
dropped, both redden at `left: ReplayOnFreshBackend / right: SendDefault(502)`.

The charge is owned by a new `ReplayCapture` newtype and released by its `impl
Drop`, not by the sites that clear the field. `retry_buffer` goes `Some -> None`
on four code paths -- `forget_upstream_replay`, the first response byte in
`ConnectionH1::readable`, the one-front-buffer overflow in
`ConnectionH1::writable`, and `queue_upstream_replay` -- and on a fifth that has
no code site at all: the `Stream` simply being dropped on a client hangup, an idle
timeout or a session teardown. Wired into the four, the counter would climb on
every one of those teardowns until the ceiling silently disarmed replay for the
rest of the worker's life, with nothing reporting it. This is the reasoning
`ConnectionH2`'s gauge teardown and `pool::Checkout` already apply: teardown in
`Drop` is symmetric whichever path ran.

The counter is a `thread_local!` rather than a process-wide static because that is
the scope of everything it is reconciled against: a worker is one event-loop
thread, its `Pool` is an `Rc<RefCell<Pool>>` that cannot leave it, and the
`backend.retry.captures_armed` gauge it feeds lives in the `thread_local!`
`METRICS`. A shared static would let one worker thread in a multi-worker test
process exhaust another's budget while their gauges disagreed about it.

Two new proxy-level metrics: the gauge `backend.retry.captures_armed` (captures
currently armed on this worker; the heap it implies is `2 * gauge * buffer_size`,
for the `Vec` reason above, and not `gauge * buffer_size`) and the counter
`backend.retry.captures_declined` (an idempotent pooled request refused a capture
for budget). The counter only moves while the gauge sits at the ceiling, and it is
an UPPER BOUND on lost retries rather than a count of them: it counts requests left
un-replayable, and the great majority of those are answered normally by an upstream
that was never stale and would never have used the capture. Only the fraction that
then hits the stale-pool race becomes a 502 the ceiling turned into a lost retry,
so it is read against `backend.retry.stale_upstream`. Non-idempotent requests never
reach it.

Three tests in `lib/src/protocol/mux/stream.rs`, each seen red against a distinct
single-line revert rather than against the tree noticing:
`past_the_ceiling_a_pooled_request_is_armed_with_no_buffer_and_still_completes`
reddens on deleting the ceiling comparison in `ReplayCapture::try_arm`, with
"past the ceiling arm_upstream_replay must install no capture"; its under-ceiling
half is what keeps it from passing against an `arm_upstream_replay` that armed
nothing at all, and its budget fill is a bounded `for` rather than
`while try_arm().is_some()`, which a ceiling-less `try_arm` would never end.
`the_armed_gauge_and_the_declined_counter_track_the_capture_budget` reddens on
deleting either `gauge_add!` and on replacing the declined `incr!` with a no-op --
three reverts, three of its own assertions.
`a_stream_dropped_with_a_capture_armed_releases_its_charge` reddens on deleting
the budget release from `impl Drop` while leaving its `gauge_add!` in place, so
the underflow `debug_assert!` does not fire and the failure is the test's own.

Two further tests close the paths those three left open.
`queueing_a_replay_releases_the_capture_charge` guards the one release path that
works AROUND `Drop`: a `Vec` cannot be moved out of a type that implements it, so
`into_bytes` must `mem::take` and let the husk drop, and the simplification a
later contributor reaches for -- a `std::mem::forget(self)` to avoid the
"pointless" drop -- leaks one charge per replay until the ceiling disarms replay
for the rest of the worker's life. That mutation passed the entire unit suite
before this test; it now reddens exactly one test, with "queueing a replay must
release the capture's charge". The other three clearing sites are plain `= None`
assignments where drop-on-assign is not something an edit can quietly remove;
this one was.
`a_non_idempotent_request_is_never_charged_to_the_capture_budget` reddens on
deleting the idempotence early return, and its final assertion pins the declined
counter's MEANING rather than its value: a method veto must NOT be counted as a
budget refusal, or the counter would read as lost retries when nothing was lost.

`doc/configure.md` states the transitive `(max_buffers / 2) * buffer_size`
relationship on the `max_buffers` row itself, because that is where an operator
sizing the value looks and the obvious estimate is wrong by 20x, and a new
"Capture budget" subsection carries the ceiling, its arithmetic, the
captures-not-bytes reasoning and both metrics.

`lib/src/protocol/mux/LIFECYCLE.md` -- which `CLAUDE.md` designates the canonical
on-branch mux reference and tells the next author to read first -- gains the
fourth arming condition beside the three it already enumerated, the `Vec` capacity
slack on its "one front buffer" bullet, the double enforcement of idempotence, and
a correction to its "The replay is bounded by `CONN_RETRIES` alone" claim, which
this changeset made false as a statement about whether a replay happens at all.
No citation rule could have caught either: they prove cited lines resolve and have
not drifted, not that prose is still true.

The status-bucket citation in `lib/src/protocol/kawa_h1/LIFECYCLE.md` is now made
by SYMBOL rather than by a line range. It drifted twice inside this one changeset,
and the drift rule deliberately exempts a citation the changeset itself
re-anchored, so its second staleness passed both gates and was caught only by
reading the cited lines back. The prose already names
`mux::stream::generate_access_log`, and a symbol cannot drift. The pinned `opentelemetry` block in
`doc/h2_mux_internals.md` follows the lines it quotes, which this changeset moved,
and two further citations renumbered for the same reason: the status-bucket range
in `lib/src/protocol/kawa_h1/LIFECYCLE.md`, which this changeset pushed down by 141
lines, and `doc/configure_admin_ops.md`'s pointer at the
`https.alpn.rejected.unsupported` row, which the new "Capture budget" subsection
pushed down by 56. Both were caught by
`check_doc_citations.py --base`, neither by `--root`.

The two changed lines in `lib/src/protocol/mux/mod.rs` are both in its test
module: `stage_partially_written_pooled_request` assigned `retry_buffer` directly
and now routes through `arm_upstream_replay`, since a hand-built capture would
release a charge it never took, and `queueing_a_replay_moves_the_captured_bytes_
into_the_front_buffer`'s `.clone()` on a `&ReplayCapture` would resolve to
`<&T as Clone>` and yield another reference, so it reads `.to_vec()`.

A `Recycle` slot is the one place a charge could have escaped, since such a slot
is not dropped. It cannot: the charge is a field of the capture, so the two cannot
part. Both exits from `Recycle` release it anyway -- reuse clears the field
(`Context::create_stream`) and `shrink_trailing_recycle` pops the `Stream` -- and
session teardown drops the whole `streams` vector. A slot parked in `Recycle` still
holding a capture holds its bytes too, so the gauge reports memory that really
exists, exactly as the bare `Vec` did.

Closes #1450

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 1b0c7cc into main Sep 23, 2026
24 checks passed
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.

retry_buffer captures are bounded only transitively by max_buffers, and no accounting sees them

1 participant