Repository navigation
fix(mux-h1): bound the stale-upstream replay captures and account for them - #1470
Merged
Merged
Conversation
… 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
requested review from
Wonshtrum and
llenotre
as code owners
September 23, 2026 11:54
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.
Closes #1450.
ConnectionH1::retry_buffer— the stale-upstream replay capture introduced by #1442 — is a plainVecon the global allocator, outside sozu's bufferPool. 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::newtakes exactly twopool.checkout()calls. So captures are transitively bounded at
(max_buffers / 2) × buffer_size.At stock defaults —
max_buffers1000,buffer_size16393 — that is ≈8.2 MB carried, not the~160 MB a naive
max_connections × buffer_sizeestimate gives. That estimate is wrong by a factor of20, because it assumes 10000 concurrent requests that
max_buffers1000 does not permit. Reaching160 MB needs
max_buffersraised 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_buffersaccounting can see.Why the captures are not moved into the
Poolmax_buffersdefaults to 1000 againstmax_connections10000 — deliberately oversubscribed 10:1 andrationed 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_replayinstalls no buffer; the request proceeds un-replayable and a stale pooledupstream 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_buffersbecomes, 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) andbackend.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_headersduring the frontend parse, long beforeRouter::connectreachesstart_stream— and only an idempotent method can ever spend a capture. Without that guard, an80%-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_declineddeliberately does not countthe 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 designretry_buffergoesSome → Noneon four functions —forget_upstream_replay, the first responsebyte, the one-front-buffer overflow,
queue_upstream_replay— and on a fifth path with no code siteat all: the
Streamsimply 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
ReplayCapturenewtype andis released by its
impl Drop. Same reasoningConnectionH2's gauge teardown andpool::Checkoutalready apply.
The counter is a
thread_local!Cell, not a process-wide static: a worker is one event-loop thread,its
Poolis anRc<RefCell<Pool>>that cannot leave it, andMETRICSis itselfthread_local!. Ashared 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.rsgrows a capture withVec::reserve, which is amortized, so a capture assembled over severalpartial writes holds up to one doubling more capacity than bytes. Measured:
Every surface now states
2 × 512 × buffer_size ≈ 16.8 MB allocatedagainst ≈8.4 MB carried, anddoc/configure.mdsays to size RSS against the larger figure. The slack loosens the constant by afactor of two; it does not make it depend on
max_buffersagain, which is the property the ceilingexists to deliver.
Tests seen red
Each revert produced its own assertion's message, not a
debug_assert!and not a sibling's:try_armpast_the_ceiling_a_pooled_request_is_armed_with_no_buffer_and_still_completesgauge_add!the_armed_gauge_and_the_declined_counter_track_the_capture_budgetgauge_add!incr!with{}Dropa_stream_dropped_with_a_capture_armed_releases_its_chargemem::forget(self)ininto_bytesqueueing_a_replay_releases_the_capture_chargea_non_idempotent_request_is_never_charged_to_the_capture_budgetThe last-but-one is the one that matters most.
into_bytesis the single place that has to workaround
Dropto move theVecout, and review found that the natural "simplification" a latercontributor reaches for —
mem::takeplusmem::forget— leaked a charge per replay while theentire 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_replaythat armsnothing; and the budget fill is a bounded
for 0..MAX, notwhile try_arm().is_some(), which wouldhang instead of failing if the ceiling were absent.
Adding the arm guard made
can_replay_on_fresh_upstream's own idempotence conjunct unreachable inproduction. 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::Getand set the methodafterwards, 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 of25 with replay disabled, is green 8 of 8 with the guard in place.
Verification
cargo test -p sozu-e2eis left to CI: the local box was running two concurrent copies of that suiteat 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
mainfailed 445/1 on an unrelated test under the same load.No production dependency growth. No
async fninlib/orbin/. Metric names go throughnames::constants, whichlib/tests/metric_names.rsenforces statically.Documentation
doc/configure.mdstates the transitive(max_buffers / 2) × buffer_sizerelationship on themax_buffersrow 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.mdgains the fourth arming condition beside the existing three, andits claim that "the replay is bounded by
CONN_RETRIESalone" is corrected.