Skip to content

fix(mux): replay an idempotent request on a fresh backend when its pooled upstream was stale - #1460

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
fix/http-retry-stale-upstream
Sep 23, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
fix/http-retry-stale-upstream

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Closes #1442.

A pooled keep-alive upstream that the origin has already closed is answered with
a 502 naming the stopped backend, instead of being retried on another one. The
cause is at lib/src/protocol/mux/shared.rs: any front.consumed EOF was
classified SendDefault(502), with no distinction between "the upstream
answered and then closed" and "the upstream was already dead when we wrote to
it".

Mechanism

A new EndStreamAction::ReplayOnFreshBackend, gated by
Stream::can_replay_on_fresh_upstream, which requires all three of:

  • the upstream came from the pool (a freshly dialled connection that fails
    was not stale — that is a real error),
  • the method is idempotent, via Method::is_idempotent — an exhaustive
    match over all nine Method variants with no _ arm, so a new verb is a
    compile error rather than a silent default,
  • no response byte has been seen, buffered or forwarded.

Bounded by the existing retry budget: Router::connect refuses at
attempts >= CONN_RETRIES (= 3). The capture is bounded by the front kawa's
storage.capacity(), dropped whole on overflow and on the first upstream byte.
The replayed bytes are prepended ahead of the unwritten tail, so a partial write
remainder stays ordered.

What a reviewer should weigh

The counter and the replays are not the same number. incr! fires at
h1.rs:1130, before pending_links.push_back at :1139, and therefore before
router.rs:156 can refuse on an exhausted budget. So the metric can increment up
to three times while at most two replays are actually written to a
backend; the third increment is immediately followed by the exhausted-budget 503.
Both facts are now stated in doc/configure.md and the commit body. An earlier
draft documented only "up to three times", which was true of the counter and
false of the behaviour.

Three of the eight new unit tests discriminate; five are veto pins. The five
that assert SendDefault(502) are asserting what end_stream_decision returned
unconditionally for every front.consumed case before this change, so they
pin the veto — worth keeping — but they are not evidence the fix works. The
discriminating three are a_stale_pooled_upstream_that_never_answered_is_replayed_not_502,
a_replay_is_queued_ahead_of_the_unwritten_tail, and the first four assertions of
queueing_a_replay_moves_the_captured_bytes_into_the_front_buffer. The CHANGELOG
says so in those terms rather than claiming eight.

Four documented paths carry no unit coverage and are named as such rather
than implied covered: the capture loop's budget check and its overflow→None
(h1.rs:645-668), both ReplayRefused paths (router.rs:202, :248), and both
None fallbacks (h1.rs:1144, h2.rs:6196).

Accepted risk, tracked as #1451. Method::new compares case-insensitively,
so get parses to Method::Get and is judged idempotent while the origin
receives literal get and may treat it as an extension method with its own
semantics. Harmless until now; this change makes it decide whether a request is
re-issued. #1451 is the fix; this changeset records the exposure.

The e2e check is a stability check, not a retry. run_stability_check stops
at the first non-Success trial, so an interrupted 100-run check has performed
fewer than 100 trials and has not measured the property — State::Success is
the only assertion that means what the test says, and Undecided buys the
INTERRUPTED diagnosis rather than tolerance. At the measured 4.3% per-trial rate,
(1 − 0.043)^100 ≈ 1.2% of runs end without exercising the race, which is why
the deterministic unit tests carry the real gate. That number is in the
CHANGELOG and beside the test rather than left for "25 of 25" to imply
determinism.

The regression was seen red, on its own assertion

Removing the retry_buffer.is_some() conjunct from
Stream::can_replay_on_fresh_upstream:

thread '...::a_request_written_to_a_freshly_dialled_upstream_is_not_replayed' panicked at
lib/src/protocol/mux/mod.rs:2971:9:
assertion `left == right` failed
  left: ReplayOnFreshBackend
 right: SendDefault(502)
test result: FAILED. 0 passed; 1 failed

Restored: test result: ok. 1 passed; 0 failed.

The previous "TO SEE THIS RED" recipe named ConnectionH1::writable's
reused_from_pool guard, which cannot redden that test — it never calls
writable, staging the capture directly and clearing it with
forget_upstream_replay(). The recipe now names the conjunct the test actually
pins, and says why a write-path recipe cannot work.

Citation repairs carried by this changeset

The rebase surfaced a pinned block and several stale anchors; all were
re-derived by content against the rebased tree, not by arithmetic:

  • doc/h2_mux_internals.md pinned stream.rs:444-447; real target stream.rs:588-591
  • kawa_h1/LIFECYCLE.md cited h1.rs:337 for the kawa.is_error() check; real site h1.rs:383
  • doc/h2_mux_internals.md cited h1.rs:466-476 for the peer-readiness re-arm; there are three such sites (375, 514, 522), so the range is replaced by the symbol
  • the StreamState::Link transition list was a hand-maintained index of six numbers while grep returns eight sites; it now cites the symbols and the grep, with no numbers at all

Two further half-applied renumberings were found and fixed, one of which no rule
in the script can see — a bare `:574` continuation carries no path, so it is
never extracted. Filed as #1459.

Verification

CI's own per-crate commands, FLAGS='--no-default-features --features crypto-ring,opentelemetry,splice,simd':

check result
cargo +nightly fmt --all -- --check 0
cargo build --locked $FLAGS 0
cargo clippy --all-targets --locked $FLAGS -- -D warnings 0
cargo test -p sozu-lib --locked $FLAGS 0 — 1000 passed, 0 failed
cargo test -p sozu --locked $FLAGS 0 — 110 passed, 0 failed
cargo test -p sozu-e2e --locked $FLAGS -- --skip tests::fuzz_tests:: 0 — 445 passed, 0 failed
cargo test -p sozu-sim (udp + tcp preread) 0
check_doc_citations.py --root . and --base 0
git merge-tree --write-tree origin/main <head> 0, gate re-run inside the extracted tree: 0

CHANGELOG: exactly one entry added under 🐛 Fixed, no duplicates, headings byte-identical.

@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the fix/http-retry-stale-upstream branch 2 times, most recently from b387798 to fd8a6f8 Compare September 23, 2026 04:36
…oled upstream was stale

An H1 keep-alive backend connection parked in `Router::backends` can be closed
by its peer while idle, with no event sozu has processed yet. The next request
routed to that cluster is written onto the dead socket, the backend read
returns EOF, and `end_stream_decision` classified that as `SendDefault(502)` on
the sole ground that `front.consumed` was set — that the request had left the
front buffer. `Router::connect` already bounded HTTP retries through its
`stream.attempts >= CONN_RETRIES` gate; what was missing was a path that
*decided* to retry this shape, not a bound on how often it may be retried.

Measured 2026-09-22 on this tree with only the replay decision reverted to a
bare `SendDefault(502)` and everything else identical: 25 red `test_issue_806`
runs out of 25, 25 failures over 576 pooled trials (4.3% per trial), the
failing iteration ranging from 1 to 81, every one answering 502 from the
stopped backend with `"backend_id": "cluster_0-0"` and
`"parsing_phase": "Error"` while the surviving backend served nothing. With the
replay in place, 25 green runs of 25. `repeat_until_error_or` stops at the
first failure, so a run performs between 1 and `n` trials rather than `n`,
which is why 25 runs pool to 576 trials and not 2500. The 502 arrives in well
under a millisecond, so no latency budget detects it.

`end_stream_decision` now returns `EndStreamAction::ReplayOnFreshBackend` for
that shape and both H1 and H2 frontends re-link the stream through
`Router::connect`. The boundary is no response byte received — nothing was
observed by the client, so re-issuing is unobservable — narrowed by three
conditions with their precedents: pooled connections only (pingora's
`RetryType::ReusedOnly`), idempotent methods only (nginx's `non_idempotent`
default, pingora's `error_while_proxy` veto), and one front buffer of captured
request (HAProxy: "Requests not fitting in a single buffer will never be
retried").

The pooled-only condition is a policy, not a diagnosis. sozu cannot tell a
stale pool socket from an origin that half-closed after processing the request,
or from one that crashed mid-request: `readable` treats every `size == 0`
alike, and an empty back buffer proves only that no response byte arrived.
Restricting the replay to pooled connections narrows it to the case where an
unobserved idle close is plausible; what licenses re-issuing at all is
idempotence, which RFC 9110 §9.2.2 defines as exactly that permission.

The captured bytes are PREPENDED to `front.out`. `out` need not be empty: a
partial `socket_write_vectored` leaves the bytes the kernel refused still
queued, because `kawa::Kawa::consume` pushes the partially consumed store back
to the front of `out`. Appending behind that remainder would hand the healthy
backend `[tail][head]`, a request mangled mid-token. A replay whose
`cluster_id` did not survive, and one whose cluster switched to `http2` between
attempts, are refused through the new `BackendConnectionError::ReplayRefused`
and answered 502 rather than being left to an assertion that compiles out of
every release build.

The replay is bounded by `CONN_RETRIES` alone. The capture is taken, not
cloned, so it cannot outlive its own replay — but `start_stream` re-arms a
fresh capture on every `KeepAlive -> Connected` transition and
`reused_from_pool` is never cleared, so one request may be replayed more than
once. The counter `backend.retry.stale_upstream` is incremented in
`ConnectionH1::end_stream` / `ConnectionH2::end_stream` *before* the stream is
pushed back onto `pending_links`, so `Router::connect` has not yet had the
chance to refuse it: with `CONN_RETRIES = 3` that is at most three increments
for one client request, of which at most two replays are actually written to a
backend. `doc/configure.md` now states both numbers rather than only the
counter's.

The replayed request is byte-identical to the first attempt, `Sozu-Id`
included, so one client request still yields one access-log line. New counter
`backend.retry.stale_upstream` records each replay against the stale backend.
It reads as "an upstream went away before answering", not "the pool held a
closed socket" — a backend crashing mid-request lands there too — which is what
its remediation note in `doc/configure.md` now says. The capture bound that
document states is the front kawa's `storage.capacity()`, which is what the
code applies: a checked-out buffer holds at least the configured `buffer_size`
(default 16393) and the pool rounds the per-entry extra up to
`align_of::<Entry>`, so that default yields 16400 usable bytes.

What the tests prove, stated as measured rather than as a count. Eight unit
tests land in `lib/src/protocol/mux/mod.rs`, and they are not eight pieces of
evidence that the replay works. THREE discriminate:
`a_stale_pooled_upstream_that_never_answered_is_replayed_not_502`,
`a_replay_is_queued_ahead_of_the_unwritten_tail`, and the first four assertions
of `queueing_a_replay_moves_the_captured_bytes_into_the_front_buffer`. The
other FIVE pin the veto:
`a_non_idempotent_request_is_never_replayed_on_a_stale_upstream`,
`an_unknown_method_is_never_replayed_on_a_stale_upstream`,
`a_request_written_to_a_freshly_dialled_upstream_is_not_replayed`,
`a_buffered_response_byte_forecloses_the_replay` and
`a_forwarded_response_byte_forecloses_the_replay`. Each of the five asserts
`SendDefault(502)`, which is exactly what `end_stream_decision` returned
unconditionally for every `front.consumed` case before this change. They are
kept, because the veto is the part a later change is most likely to widen by
accident, but they are a guard rail and not evidence for the fix. Three
documented paths carry no unit coverage at all and are named rather than
claimed: the capture loop in `ConnectionH1::writable` with its budget check and
its overflow-to-`None`, both `BackendConnectionError::ReplayRefused` refusals,
and the `None` fallbacks in `ConnectionH1::end_stream` and
`ConnectionH2::end_stream`.

`test_issue_806` is corroboration, not the deterministic gate: at the measured
4.3% per-trial rate, `repeat_until_error_or(100, ...)` reaches the end of a run
without ever exercising the race on (1 - 0.043)^100 ~= 1.2% of runs, so "25 of
25 green" is a strong signal and not determinism. Its `State::Success`
assertion is kept strict and the comment above the `State::Undecided` return
now agrees with it: `run_stability_check` stops at the first trial that is not
`Success`, so an interrupted 100-run check has performed fewer than 100 trials
and has not measured the property the test claims. The separate `Undecided`
state buys the diagnosis — an INTERRUPTED message naming the setup that did not
hold — not tolerance.

Accepted risk, recorded at `Method::is_idempotent` and tracked as
#1451 rather than fixed here: `Method::new` matches
case-INSENSITIVELY, so `get` parses to `Method::Get` and is judged idempotent
while the origin receives the literal `get` bytes and may treat them as an
extension method with semantics of its own. That was harmless until this
change; it now helps decide whether a request is re-issued. Narrowing
`Method::new` changes routing, metrics labels and access-log output repo-wide,
so it is its own changeset.

Documentation repairs carried in the same changeset, each re-derived from this
tree's content rather than offset from a stale number: the `StreamState::Link`
transition list in `lib/src/protocol/mux/LIFECYCLE.md` is now cited by symbol,
because it was a hand-maintained index of six line numbers that was
mechanically renumbered while the two new `end_stream` arms were never added to
it — `grep -n 'state = StreamState::Link;'` returns eight sites. Two citation groups
in the same document were renumbered on one half only and are re-derived: the
`unlink_stream` timeout sites, and the `Context::link_stream` pair, whose first
half went `router.rs:394` -> `:442` while its second stayed at `:574`, a line
that now reads `socket_ref,`. That second half was spelled as a bare `` `:574` ``
carrying no path, so no rule in `.github/scripts/check_doc_citations.py` could
see it; both sites are now `router.rs:442/622`, the `/` continuation form the
resolver does read. `doc/h2_mux_internals.md`'s pinned
`opentelemetry` block follows the lines it quotes. The re-anchor in
`lib/src/protocol/kawa_h1/LIFECYCLE.md` for the post-parse `kawa.is_error()`
check, and the one in `doc/h2_mux_internals.md` for the peer-readiness re-arm
in `ConnectionH1::readable`, both landed on unrelated lines and are corrected —
the second by symbol, since no single range covers its three
`peer.arm_writable()` sites.

Closes #1442

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the fix/http-retry-stale-upstream branch from fd8a6f8 to 4d87d9c Compare September 23, 2026 06:47
@FlorentinDUBOIS
FlorentinDUBOIS merged commit d8b8546 into main Sep 23, 2026
24 checks passed
FlorentinDUBOIS added a commit that referenced this pull request Sep 23, 2026
… 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 added a commit that referenced this pull request Sep 23, 2026
… them (#1470)

`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]>
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.

http: a stale keep-alive upstream connection is answered with 502 instead of being retried on another backend

1 participant