Skip to content

fix(h1): keep the Connection options while shutting down - #1696

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
fix/h1-shutdown-connection-options
Sep 29, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
fix/h1-shutdown-connection-options

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

While Sōzu shuts down (HttpContext::closing, set by Mux::shutting_down_inner), HttpContext::on_request_headers and HttpContext::on_response_headers (lib/src/protocol/kawa_h1/editor.rs) overwrote every Connection value with close. That dropped the other options: a field the peer nominated as hop-by-hop (Connection: x-custom) was forwarded as end-to-end (RFC 9110 §7.6.1), a request's Upgrade field reached the backend without the upgrade option that must accompany it (§7.8), and, on the response side, the backend's own close was no longer recorded in keep_alive_backend. An HTTP/1.1 final response without a Connection line got no close at all.

Fix

  • Both header loops now always record the close decision from the original value (keep_alive_frontend / keep_alive_backend); nothing is rewritten inside the loop.
  • The HTTP/1.0 merge from fix(h1): forward HTTP/1.0 backend responses as HTTP/1.1 #1683 moves into merge_connection_options_into_close: every Connection line is elided and one line is pushed with the other options followed by a single close; keep-alive (and an already listed close) is dropped. A lone close stays a static value (no allocation).
  • Request side: under closing, the merge runs (it replaces the old push-if-absent), so Connection: close is still added when the client sent none.
  • Response side: the merge runs for every final response under closing (HTTP/1.1 as well as HTTP/1.0), and as before for a non-persistent HTTP/1.0 response. A 1xx is left alone, as the HTTP/1.0 branch already did.
  • Docs: lib/src/protocol/kawa_h1/LIFECYCLE.md (both callbacks), CHANGELOG.md (Unreleased / Fixed).

Decision: a request asking for Upgrade during shutdown

Options: (a) keep Connection: Upgrade, close and let the backend decide; (b) refuse the upgrade. This PR takes (b): the upgrade option is dropped along with every Upgrade field (a nominated field must not go end-to-end, §7.6.1). The backend then answers in HTTP/1.1, which a server may always do (§7.8: accepting an upgrade is optional), and the client gets a normal response with Connection: close and can retry the upgrade on a new connection.

Why not (a): ConnectionH1::writable (lib/src/protocol/mux/h1.rs) checks stream.context.closing before the 101 arm, so while draining Sōzu never completes an upgrade. Under (a), a 101 would reach the client and the connection would close right after it. Refusing is the only choice consistent with the existing drain semantics (finish in-flight work, start no long-lived work). Before this PR the request already went out as Connection: close + Upgrade: websocket (see RED below), which was broken in its own way. If you would rather keep the upgrade, writable has to change too; please say so on this PR.

lib/src/protocol/kawa_h1/answers.rs whole-value Connection: close match: left as is

That match (in the template parser) sets the template's own keep_alive flag. It reads operator-authored answer templates, not peer traffic, and every shipped default template carries a lone Connection: close line (checked: all 15 Connection: lines of the built-in default templates in answers.rs, outside its test module, are exactly Connection: close), so no default answer is affected. It is the same kind of defect as #1687 (a list such as x, close would read as keep-alive), but it is outside this shutdown fix. It deserves its own small follow-up that exposes has_connection_option to answers.rs.

Tests

New unit tests in editor.rs, run with closing = true:

  • a_shutting_down_request_keeps_its_connection_options: no Connection → close; x-custom → x-custom, close; keep-alive, x-custom → x-custom, close; close stays a single close and clears keep_alive_frontend; two lines merged; HTTP/1.0.
  • a_shutting_down_request_does_not_upgrade: Upgrade → close with no Upgrade: field; keep-alive, Upgrade, x-custom → x-custom, close.
  • a_shutting_down_response_keeps_its_connection_options: the same matrix on HTTP/1.1 responses plus a persistent HTTP/1.0 one; the backend close clears keep_alive_backend.
  • a_shutting_down_interim_response_is_left_alone: a 101 keeps Connection: Upgrade; a 100 gets no line.

RED (tests added on origin/main 3ed6e8a before the fix, cargo test -p sozu-lib --lib a_shutting_down):

test protocol::kawa_h1::editor::tests::a_shutting_down_request_does_not_upgrade ... FAILED
test protocol::kawa_h1::editor::tests::a_shutting_down_request_keeps_its_connection_options ... FAILED
test protocol::kawa_h1::editor::tests::a_shutting_down_interim_response_is_left_alone ... FAILED
test protocol::kawa_h1::editor::tests::a_shutting_down_response_keeps_its_connection_options ... FAILED
websocket: the Upgrade field is not forwarded, got "GET /chat HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\nUpgrade: websocket\r\n..."
nominated field: ... left: ["Connection: close"] right: ["Connection: x-custom, close"]
101: ... left: ["Connection: close"] right: ["Connection: Upgrade"]
no Connection: ... got "HTTP/1.1 200 OK\r\nContent-Length: 4\r\nSozu-Id: ...\r\n\r\nabcd" left: [] right: ["Connection: close"]
test result: FAILED. 0 passed; 4 failed; 0 ignored; 0 measured; 1349 filtered out

GREEN (cargo test -p sozu-lib --lib kawa_h1):

test protocol::kawa_h1::editor::tests::a_shutting_down_request_does_not_upgrade ... ok
test protocol::kawa_h1::editor::tests::a_shutting_down_interim_response_is_left_alone ... ok
test protocol::kawa_h1::editor::tests::a_shutting_down_response_keeps_its_connection_options ... ok
test protocol::kawa_h1::editor::tests::a_shutting_down_request_keeps_its_connection_options ... ok
test result: ok. 71 passed; 0 failed

Why there is no e2e test

The request-side shutdown branch is unreachable today, and no known sequence reaches the response-side one: the fix is defensive. The e2e harness cannot reach either. Mux::shutting_down_inner sets closing only on an Unlinked stream, whose headers were already edited, and an idle keep-alive session is closed rather than marked (see try_msg_close). Measured: with an eprintln! probe in both merge branches, the whole sozu-e2e suite (fuzz skipped) got 0 probe hits (493 passed / 7 failed; the 7 are load flakes, see below). The probe was then removed. This shows only that the harness does not reach the branches; whether production traffic can reach them (for example via a retried or H2 stream) is not established here. The unit tests are the coverage, and LIFECYCLE.md says so.

Validation (each by its own exit code)

  • cargo build --all-features → 0
  • cargo clippy --all-features --all-targets -- -D warnings → 0
  • cargo +nightly fmt --all -- --check → 0
  • RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked → 0
  • cargo test -p sozu-lib → 0 (1363 passed); -p sozu → 0 (238); -p sozu-command-lib → 0 (195)
  • e2e: http10 5/5, close_delimited 12/12, keep_alive 4/4, connection 20/20, upgrade 14/14, websocket 4/4, soft_stop 2/2, all exit 0
  • check_doc_citations.py --self-test, --root ., --base origin/main, --audit --root . → all 0

Flake triage for the 7 failures in the full probe run (host load average 43–63 from concurrent builds): test_h1_smuggling_te_cl_trailing_tab, e2e_h2_flow_per_stream_idle_timeout, test_upgrade and test_upgrade_multiple_in_flight passed on their first isolated rerun. test_h2_graceful_shutdown_completes_large_transfer and test_issue_806 failed once in isolation, then passed 3 more isolated runs. test_h1_to_h2_basic_request (H1 client → H2 backend, closing never set) then went 8/8 on this branch and 8/8 on an origin/main worktree in interleaved runs. None of these paths enter the changed branches: the probe fired 0 times.

Revision 2 (after review)

  • Rebased on origin/main d9ce2a0 (feat(listener): bind listeners to a network interface #1686).
  • MSRV clippy (1.93.1, clippy::nonminimal_bool) flagged the option filter in merge_connection_options_into_close: it is now a named dropped disjunction, with no allow. cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings → 0 (0 warning/error lines); stable clippy → 0.
  • Dropped the tautological shutdown debug_assert! in on_response_headers.
  • LIFECYCLE.md now states that the request-side shutdown branch is unreachable today (Mux::shutting_down_inner sets closing only on an Unlinked, non-quiesced stream whose heads were both edited) and that both branches are defensive.
  • Rerun: build, nightly fmt, doc -D warnings, cargo test -p sozu-lib (1372 passed), kawa_h1 71 passed, e2e http10 5/5, connection 20/20, upgrade 15/15, websocket 4/4, four citation checks → all 0.

Residual risks

Closes #1690

While Sōzu shut down (`HttpContext::closing`), `on_request_headers` and
`on_response_headers` overwrote every `Connection` value with `close`,
turning the fields the peer nominated as hop-by-hop into end-to-end ones
(RFC 9110 §7.6.1) and no longer recording the backend's own `close` in
`keep_alive_backend`.

Both sides now record the close options first, then merge every
`Connection` line into one that keeps the other options and ends in a
single `close`, dropping only `keep-alive` — the approach non-persistent
HTTP/1.0 responses already used, now shared by
`merge_connection_options_into_close`. A final response announces the
close in HTTP/1.1 too; a 1xx is left alone.

A request asking for a protocol upgrade during shutdown loses its
`upgrade` option with its `Upgrade` field: `ConnectionH1::writable` tests
`closing` before it handles a 101, so an upgrade would switch the client
to a connection that closes at once. The backend answers in HTTP/1.1
(RFC 9110 §7.8) and the client retries on a new connection.

Closes #1690

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the fix/h1-shutdown-connection-options branch from 3a74d68 to b606e16 Compare September 29, 2026 19:32
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 5c7f4dd into main Sep 29, 2026
27 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/h1-shutdown-connection-options branch September 29, 2026 20:37
FlorentinDUBOIS added a commit that referenced this pull request Sep 29, 2026
#1695)

Closes #1689

## Problem (reproduced)

kawa's H1 parser pushes a chunked request's trailer fields after its last chunk with no callback, so `HttpContext::on_request_headers` never sees them. On `main` (`3ed6e8a6`) the new e2e test shows the backend receiving them verbatim:

```
TRAILER-SPOOF: backend received "POST /api HTTP/1.1\r\n...X-Forwarded-For: 127.0.0.1\r\n...\r\n\r\n5\r\nHello\r\n0\r\nX-Forwarded-For: 6.6.6.6\r\nForwarded: for=6.6.6.6\r\nX-Real-IP: 6.6.6.6\r\nX-Request-Id: 6.6.6.6\r\nX-Forwarded-Proto: 6.6.6.6\r\nX-Forwarded-Port: 6.6.6.6\r\nX-Forwarded-Host: 6.6.6.6\r\nGrpc-Status: 0\r\n\r\n"
```

A backend that merges trailers into its header view then sees a forged client address (RFC 9110 §6.5.1, CWE-348).

## Fix

- `TRAILER_SPOOF_VECTOR_HEADERS` (`lib/src/protocol/kawa_h1/editor.rs`) is now the **single list** for both frontends: `x-real-ip`, `x-forwarded-for`, `forwarded`, `x-request-id`, `x-forwarded-proto`, `x-forwarded-port`, `x-forwarded-host`. `pkawa::handle_trailer` reads it instead of the inline seven-name `matches!` that #1685 (merged as `5471bfba`) added, so H1 and H2 cannot drift. H2 behaviour is unchanged. This branch is rebased on `origin/main` (`a6419607`), which includes #1685, #1696, #1697 and #1699. The `editor.rs` conflict with #1696 (both appended tests at the end of the test module) keeps both sets of tests, and the `pkawa.rs` comment keeps #1699's mode wording while naming the shared constant. The `pkawa.rs` conflict was resolved in favour of the shared constant, keeping #1685's `forwarded_headers`-mode wording in the doc comments, the test rationale and the `doc/configure.md` paragraph (which now also names the H1 path).
- `elide_request_trailer_spoof_vectors` (same file) runs after both frontend `kawa::h1::parse` sites of `ConnectionH1`: `readable`, and the keep-alive branch of `writable` that parses a pipelined request. Each call site reads `kawa.blocks.len()` just before the parse and passes it as `first_new_block`. The walk goes back only over the blocks that parse appended (closing `Flags` + trailer fields), stopping at the `end_body` marker or at `first_new_block`. It elides matching names in any case with `Pair::elide`.
- **Linear cost (review item):** a parse only appends blocks and `prepare` only drains from the front between parses, so every older field was already examined by the call after the parse that queued it. A client that trickles one trailer line per segment while the backend isn't writable costs one block per line, not an O(n²) re-walk. This holds when earlier trailer fields were already drained to the backend.
- **Framing:** kawa's H1 and H2 converters skip elided pairs. The last chunk and the closing empty line are still written, so the framing stays valid even when every field is dropped. The e2e test asserts `...0\r\nGrpc-Status: 0\r\n\r\n` on the wire.
- **Cost:** the function returns on the `kind` / `body_size == Chunked` / `parsing_phase ∈ {Trailers, Terminated}` checks before reading any block. Requests without trailers pay three field compares.
- **Responses are not filtered.** A response trailer goes to the client, which does not take client attribution from it, so the spoofing risk this issue describes does not apply.
- New counter `http.trailer.spoof_vector_elided` (one increment per elided H1 field), documented in `doc/configure.md`.
- Docs: `doc/configure.md` (anti-spoof paragraph + metric row), `lib/src/protocol/kawa_h1/LIFECYCLE.md` §2.3, `CHANGELOG.md` (Unreleased / Security).

## Tests (red, then green)

New tests: `a_chunked_request_trailer_section_loses_its_spoof_vector_fields`, `a_trailer_section_parsed_after_the_last_chunk_was_forwarded_is_filtered`, `a_trailer_section_split_across_reads_is_filtered_in_each_part`, `a_trailer_walk_stops_at_the_blocks_queued_before_the_parse`, `trailer_elision_leaves_headers_and_responses_alone` (editor unit tests). The e2e tests are `test_h1_trailer_spoof_headers_dropped`, `test_h1_trailer_spoof_headers_dropped_split` (trailers in a separate write), `test_h1_trailer_spoof_headers_dropped_split_inside_trailers` (`X-Forwarded-For` in one write, the rest in the next) and `test_h1_pipelined_trailer_spoof_headers_dropped`. `handle_trailer_drops_each_spoof_header_individually` now iterates the shared list.

RED, e2e on unfixed code:
```
TRAILER-SPOOF: FAIL — a spoofed forwarding trailer reached the backend
test tests::h1_security_tests::test_h1_trailer_spoof_headers_dropped ... FAILED
TRAILER-SPOOF-SPLIT: FAIL — a spoofed forwarding trailer reached the backend
test tests::h1_security_tests::test_h1_trailer_spoof_headers_dropped_split ... FAILED
test result: FAILED. 0 passed; 2 failed; 0 ignored; 0 measured; 504 filtered out
```
RED, unit tests: `elide_request_trailer_spoof_vectors` stubbed to `return 0`, and pkawa restored to its old four-name `matches!`:
```
test protocol::mux::pkawa::tests::handle_trailer_drops_each_spoof_header_individually ... FAILED
test protocol::kawa_h1::editor::tests::a_trailer_section_parsed_after_the_last_chunk_was_forwarded_is_filtered ... FAILED
test protocol::kawa_h1::editor::tests::a_chunked_request_trailer_section_loses_its_spoof_vector_fields ... FAILED
test protocol::kawa_h1::editor::tests::trailer_elision_leaves_headers_and_responses_alone ... ok
trailer with only x-forwarded-proto should leave no surviving block
test result: FAILED. 1 passed; 3 failed; 0 ignored; 0 measured; 1348 filtered out
```
RED, pipelined path: only the keep-alive call site in `mux/h1.rs` disabled:
```
TRAILER-SPOOF-PIPELINED: FAIL — a spoofed forwarding trailer reached the backend
test tests::h1_security_tests::test_h1_pipelined_trailer_spoof_headers_dropped ... FAILED
```
RED, review items after the rebase:

Walk ignoring `first_new_block` (`range_mut(0..)`). The function's own post-condition `debug_assert!` ("only blocks appended by the last parse are elided") fires before the test's assertion:
```
test protocol::kawa_h1::editor::tests::a_trailer_section_split_across_reads_is_filtered_in_each_part ... ok
test protocol::kawa_h1::editor::tests::a_trailer_walk_stops_at_the_blocks_queued_before_the_parse ... FAILED
test result: FAILED. 1 passed; 1 failed
```
Elision disabled (`return 0`):
```
test protocol::kawa_h1::editor::tests::a_trailer_section_split_across_reads_is_filtered_in_each_part ... FAILED
assertion `left == right` failed: the first trailer part is filtered on its own
  left: 0
 right: 1
TRAILER-SPOOF-SPLIT-INSIDE: FAIL — a spoofed forwarding trailer reached the backend
test tests::h1_security_tests::test_h1_trailer_spoof_headers_dropped_split_inside_trailers ... FAILED
```

GREEN:
```
test protocol::mux::pkawa::tests::handle_trailer_drops_each_spoof_header_individually ... ok
test protocol::kawa_h1::editor::tests::a_chunked_request_trailer_section_loses_its_spoof_vector_fields ... ok
test protocol::kawa_h1::editor::tests::a_trailer_section_parsed_after_the_last_chunk_was_forwarded_is_filtered ... ok
test protocol::kawa_h1::editor::tests::trailer_elision_leaves_headers_and_responses_alone ... ok
test tests::h1_security_tests::test_h1_trailer_spoof_headers_dropped ... ok
test tests::h1_security_tests::test_h1_trailer_spoof_headers_dropped_split ... ok
test tests::h1_security_tests::test_h1_trailer_spoof_headers_dropped_split_inside_trailers ... ok
test protocol::kawa_h1::editor::tests::a_trailer_section_split_across_reads_is_filtered_in_each_part ... ok
test protocol::kawa_h1::editor::tests::a_trailer_walk_stops_at_the_blocks_queued_before_the_parse ... ok
test tests::h1_security_tests::test_h1_pipelined_trailer_spoof_headers_dropped ... ok
```

## Validation (each by its own exit code)

- `cargo build --all-features`: 0
- `cargo clippy --all-features --all-targets -- -D warnings`: 0
- `cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings` (MSRV): 0
- `cargo +nightly fmt --all -- --check`: 0
- `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked`: 0
- `cargo test -p sozu-lib`: 0 (1381 passed)
- `cargo test -p sozu`: 0
- `cargo test -p sozu-command-lib`: 0
- `cargo test -p sozu-e2e -- trailer h1_security mux_tests forward connection`: 0 (104 passed)
- `check_doc_citations.py` `--self-test` / `--root .` / `--base origin/main` / `--audit --root .`: all 0 (the audit's three advisory findings are in files this PR does not touch)

## Residual risks

- The advisory `Trailer:` request header still lists the dropped names. It is informational only, and this PR leaves it as sent.
- An H2-frontend request forwarded to an H1 backend goes through `pkawa::handle_trailer`, not this walk. It uses the same list.
- The bounded walk assumes kawa 0.7.2's invariants: parsing only appends blocks, and draining happens only from the front between parses. A debug post-condition guards this.




Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 29, 2026
…1700)

Refs #1684. This is the second PR of the sequence the maintainer set in #1684 (comment): inject the clock and the RNG into `lib/src/retry.rs`, `lib/src/load_balancing.rs` and `PeakEWMA` in `lib/src/lib.rs`, so backend selection is deterministic under a simulator's clock and seed.

Rebased onto `origin/main` `a6419607`, which includes #1698 (`L7Proxy::backends` removed), #1696 and #1699.

**Scope of the determinism proof.** `sozu-sim` does not build a `BackendMap` yet, so today determinism is proven by the library tests below. Wiring the simulator to `BackendMap::with_seed`, `Backend::new_at` and an injected `now` comes with the G2(a) change and the deterministic H2 simulation PR that follows it.

## Design

**The clock is a parameter.** Every entry point that depends on time takes `now: Instant`, a 16-byte value passed by value, following the precedent of the UDP core (`lib/src/protocol/udp/mod.rs`).
- `RetryPolicy`: `fail(now, rng)`, `succeed(now)`, `can_try(now)`.
- `PeakEWMA`: `new(now)`, `observe(rtt, now)`, `get(active, now)`.
- `Candidates::new(.., now)` carries the selection's instant, so the `LoadBalancingAlgorithm` trait signature is unchanged. Only the two policies that read `peak_ewma_connection` use it.
- Selection entry points:
  - `Backend`: `can_open(now)`, `try_connect(now, rng)`, `set_connection_time(dur, now)`, `peak_ewma_connection(now)`.
  - `BackendList`: `next_available_backend(now)`, `next_available_backend_with_key(key, now)`, `available_backends(backup, now)`, `find_sticky(.., now)`.
  - `BackendMap`: `backend_from_cluster_id(.., now)`, `backend_from_cluster_id_with_key(.., now)`, `backend_from_sticky_session(.., now)`.
  - `BackendSource::select(.., now)`.
- Callers:
  - The mux passes `Context::now`, its one clock sample per pass, through `RegistryDialer` and at the `ready_inner` success and failure writes.
  - The UDP core passes the admission's `now`.

**The RNG is lent, not ambient.** `fail` takes `&mut R` with `R: Rng + ?Sized`. That is generic, not a trait object, and has two instantiations: `StdRng` and `ThreadRng`.

**One `StdRng` per `BackendMap`:**
- `BackendMap::new` seeds it from the OS once. `BackendMap::with_seed(u64)` seeds it for a simulator.
- It seeds every cluster's `Random` and `PowerOfTwo` policy, through `BackendList::with_seed`, `set_load_balancing_policy(.., seed)` and `import_configuration_state(.., seed)`.
- It supplies every backoff jitter: `BackendMap::rng()`, and `try_connect` inside selection.
- Every list the map creates draws its seed from it:
  - a policy set with `set_load_balancing_policy_for_cluster`;
  - a cluster `BackendMap::add_backend` creates before any policy is set;
  - every cluster of `import_configuration_state`, seeded in sorted cluster-id order rather than in the `HashMap`'s per-process iteration order. The sort allocates once, on that control-plane replay path only.
- Each worker still draws an independent keystream, which is the property the two seed-correlation guards protect.

**Construction:**
- `ExponentialBackoffPolicy` records no instant before its first attempt (`last_try: Option<Instant>`). This changes nothing: its window is zero until then, and `Option<Instant>` keeps the struct at 48 bytes.
- `PeakEWMA` does need a construction instant, because its first decay is measured from it. So `Backend::new_at(.., now)` takes one, and `Backend::new` stays the production default, stamping `Instant::now()`.

**Removed:** `Random::new`, `impl Default for Random`, `PowerOfTwo::new` and `impl Default for PeakEWMA`.

**No `Box<dyn>` and no new trait object.**
- `Candidates` grows from 32 to 48 bytes, passed by value.
- The mux's failed-connection arm gains one `RefCell::borrow_mut` of the worker's `BackendMap` to take its jitter. That arm is off the dial path, and nothing else borrows the map there.

### Production defaults that remain, stated plainly

The extended criterion covers `retry.rs`, `load_balancing.rs` and the `PeakEWMA` impl. A wider grep finds these, all deliberate:
- `Backend::new` stamps `Instant::now()`. It is the production constructor; a simulator uses `Backend::new_at`.
- `os_rng()` in `backends.rs` is the one `SysRng` read, called by `BackendMap::new` and `BackendList::new`.
- `lib/src/tcp.rs` keeps `Instant::now()` for selection, `succeed` and `set_connection_time`, and `rand::rng()` for backoff jitter. The TCP proxy is not simulated.
- The mux still measures the connection time itself as `start.elapsed()`. Only the decay reference is injected.

### Behaviour

Production uses the same clock and the same entropy, sampled differently in two places:
- The mux reads `Context::now` once per pass instead of the clock at each call.
- Backoff jitter comes from the map's OS-seeded `StdRng` instead of the thread-local generator.

The pinned per-policy pick sequences in `lib/tests/backend_selection.rs` are unchanged and green.

## Success criterion

Criterion: `git grep -nE 'Instant::now|rand::rng|SysRng|\.elapsed\(\)'` over `lib/src/retry.rs`, `lib/src/load_balancing.rs` and the `PeakEWMA` impl in `lib/src/lib.rs`, excluding `#[cfg(test)]` code.

Result: **0 production hits**. The 11 raw hits that remain are all inside `#[cfg(test)]` modules:
- `retry.rs`: 8
- `load_balancing.rs`: 3

## Measurements

Before is `origin/main` `be75f21c`, after is this change. Sizes come from a throwaway `size_of` probe, and dial allocations from `test_allocations::allocations()` around `Mux::dial_backend` in `a_dial_moves_the_planned_cluster_id_into_the_backend_connection`. Neither probe is committed.

| | before | after |
|---|---|---|
| `size_of::<Backend>()` | 208 B | 208 B |
| `size_of::<BackendList>()` | 72 B | 72 B |
| `size_of::<BackendMap>()` | 152 B | 472 B (its `StdRng`, once per worker) |
| `size_of::<PeakEWMA>()` | 32 B | 32 B |
| `size_of::<ExponentialBackoffPolicy>()` | 48 B | 48 B |
| `size_of::<MuxClear>()` | 4984 B | 4984 B |
| heap allocations per `Mux::dial_backend` (3 runs) | 6, 6, 6 | 6, 6, 6 |
| steady-state selection, `backend_selection_allocates_nothing_in_steady_state` (3 tiers × 10 policies × 256) | 0 | 0 |
| router stamping, `stamping_a_dialled_backend_allocates_nothing` | 0 | 0 |
| `backend_selection_pick_sequences_are_pinned` | green | green, sequences unchanged |

## Tests: red, then green

For each test below, I applied the named mutation to the production code, quoted the failing assertion, then restored the code. After restoring, all seven are green (`cargo test -p sozu-lib --lib`).

1. **`retry::tests::the_backoff_window_follows_the_injected_clock`**
   - Mutation: `since_last_try` measures from `Instant::now()`.
   - Failure: `the window closes at t0 + 1s on the injected clock`, `left: Some(WAIT)`, `right: Some(OKAY)`.
2. **`retry::tests::one_seed_yields_one_sequence_of_backoff_windows`**
   - Mutation: `fail` draws its jitter from `rand::rng()` and ignores its argument.
   - Failure: `one seed must yield one sequence`, `left: [1s, 1s, 1s, 4s, 14s, 1s, 16s, 118s, 253s, 362s]`, `right: [1s, 1s, 2s, 1s, 12s, 28s, 12s, 88s, 179s, 212s]`.
3. **`backends::backends_test::one_map_seed_yields_one_selection_sequence`**
   - Mutation: `BackendMap::with_seed` ignores the seed and uses `os_rng()`.
   - Failure: `Random: one seed must yield one sequence of picks`. The two 48-pick vectors diverge from the second pick: `[..:9102, ..:9103, ..]` vs `[..:9102, ..:9101, ..]`.
4. **`backends::backends_test::the_connection_time_average_decays_on_the_injected_clock`**
   - Mutation: `PeakEWMA::observe` takes `now` from `Instant::now()`.
   - Failure: `one second after creation, the average must have decayed by e^-1`, `left: 49997335.421002336`, `right: 18393972.058572117`.
5. **`load_balancing::test::power_of_two_tie_break_is_decided_by_the_coin_flip_not_by_sample_position`** (rewritten, see below)
   - Mutation: the tie-break `random_bool(0.5)` becomes `true`.
   - Failure: `power-of-two resolved 0 of 2000 exact ties in favour of the second-measured sample`.
6. **`backends::backends_test::a_cluster_created_by_adding_a_backend_is_seeded_by_the_map`**
   - Mutation: the code before the fix, where `BackendMap::add_backend` created the list with `or_default()`, which is OS-seeded.
   - Failure: `a list created by add_backend must draw its seed from the map`.
7. **`backends::backends_test::importing_a_state_seeds_its_clusters_in_a_fixed_order`**
   - Mutation: the code before the fix, which drew seeds while iterating the state's `HashMap`.
   - Failure: `import-00: one map seed must give each imported cluster one seed`.
8. **`backends::backends_test::random_policies_seeded_by_the_os_are_not_correlated`** and **`power_of_two_policies_seeded_by_the_os_are_not_correlated`** (moved, see below)
   - Mutation: `BackendMap::new` seeds from a constant.
   - Failure: both fail with `two BackendMap::new() must NOT seed … from a shared/correlated keystream`, on identical 48-pick vectors.

**Moved and rewritten tests.** No check was weakened.
- `random_new_instances_are_not_correlated` and `power_of_two_new_instances_are_not_correlated` guarded `Random::new` and `PowerOfTwo::new`. Those constructors are gone and the OS seed now enters through `BackendMap::new`, so the guards moved to `backends.rs`. They keep their assertion and add one: two clusters of one map must also diverge. `RENAMED_TESTS` in `check_doc_citations.py` forwards the old names, so the historical CHANGELOG line and this PR's entry both resolve.
- `power_of_two_tie_break_is_decided_by_the_coin_flip_not_by_sample_position` read the sampled pair's order from wall-clock `PeakEWMA` stamps. With one injected instant per selection, both stamps are equal. The test now replays the pair from a generator seeded like the policy, one seed per trial. The replay stops before the coin flip, so it agrees with the policy whether the flip is there or not.
  - The replay is checked, not trusted. The test runs over three equally loaded backends and asserts that every pick is one of the two the replay predicts. This replaces the old `decided >= TOTAL / 2` guard, which became vacuous once every trial was decided.
  - The coin-flip assertion and its ±20-point band are unchanged.
  - Red, coin flip replaced by `true`: `resolved 0 of 2000 exact ties in favour of the second-measured sample`.
  - Red, sampler draws one extra value before the pair: `trial 2: picked backend 1, outside the pair (0, 2) the replay predicts; the sampler no longer draws the pair this test replays`.
- `power_of_two_touches_exactly_two_backends` selects at `before + 1ns` on the injected clock instead of spin-waiting on the wall clock. Same assertion.
- The `retry.rs` tests use explicit instants and a seeded generator, and no longer need `#[serial]`.
- `lib/tests/backend_selection.rs` builds its fixture with `Backend::new_at` and `BackendList::with_seed`, and selects at one `now`. Its pinned sequences are unchanged.

Shared-literal check: grepping the production diff for literals shared with the tests (`0x5eed`, `with_seed(7|8)`, `DEFAULT_HASH_SEED`) finds only test code and doc comments. No production logic matches.

## Docs and scope

- `CHANGELOG.md`: a BREAKING (library API) entry under 🔄 Changed, listing the changed and removed API.
- `doc/testing.md` §5: how a simulator supplies time and seed (`Backend::new_at`, `BackendMap::with_seed`), and the two production defaults that remain.
- `lib/src/protocol/mux/LIFECYCLE.md` §9, invariant 14: the health and latency writes take `Context::now` and the map's generator.
- `lib/src/protocol/proxy_protocol/LIFECYCLE.md`: its `lib/src/backends.rs:333` line citation moved with this change, so it now cites `Backend::try_connect`.
- `.github/scripts/check_doc_citations.py`: the two `RENAMED_TESTS` entries described above.
- `lib/src/protocol/udp/manager.rs`, `sim/tests/udp_simulation.rs` and `fuzz/fuzz_targets/fuzz_udp_flow.rs`: the three `BackendSource` doubles take `now`. The fuzz target already drives the UDP core from a virtual clock advanced only by input deltas; its backend set judges nothing against `now`, so the run stays deterministic. A repo-wide grep of `bin/`, `e2e/`, `sim/`, `fuzz/` and `command/` finds no other caller of the changed APIs. There is no `benches/` or `examples/` directory.

## Validation

Run on the final head `584c1787`, rebased onto `a6419607`. Every exit code was checked directly, never through a pipe:
- `cargo +nightly fmt --all -- --check` -> exit 0
- `cargo clippy --all-targets --locked -- -D warnings` -> exit 0
- `cargo clippy --all-targets --all-features --locked -- -D warnings` -> exit 0
- `cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings` -> exit 0
- `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` -> exit 0
- `cargo test --workspace --locked --exclude sozu-e2e` -> exit 0 (1849 passed, 0 failed, 17 ignored, all ignores already on main)
- `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked` -> exit 0 (31 passed)
- `cargo test -p sozu-e2e --locked -- --skip tests::fuzz_tests::` -> exit 0 (510 passed)
- `cd fuzz && cargo +nightly fuzz build` -> exit 0 (all six targets)
- `cd fuzz && cargo +nightly fuzz run fuzz_udp_flow -- -max_total_time=30` -> exit 0 (`Done 698366 runs in 31 second(s)`, `cov: 868 ft: 4978`)
- `python3 .github/scripts/check_doc_citations.py` -> exit 0
- `python3 .github/scripts/check_doc_citations.py --base origin/main` -> exit 0
- `python3 .github/scripts/check_doc_citations.py --self-test` -> exit 0
- `python3 .github/scripts/check_doc_citations.py --root .github/scripts/testdata/citations` -> exit 1 (the broken fixture must fail)

The previous head `1671caac` failed the CI step `Fuzz fuzz_udp_flow`: the fuzz crate still implemented `BackendSource::select` without `now`. My local validation never built `fuzz/`, which is outside the workspace. That build is now part of the checks above.



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.

h1: shutdown overwrites Connection options with close

1 participant