Skip to content

refactor(lib): inject the clock and the RNG into backend selection - #1700

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/inject-clock-rng-selection
Sep 29, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/inject-clock-rng-selection

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

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.

@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the refactor/inject-clock-rng-selection branch from 2b82473 to 1671caa Compare September 29, 2026 20:31
Backend selection and backoff read the wall clock and ambient entropy:
ExponentialBackoffPolicy used Instant::now, .elapsed() and rand::rng()
(lib/src/retry.rs), PeakEWMA stamped Instant::now on construction and on
every observation (lib/src/lib.rs), and Random::new and PowerOfTwo::new
seeded from SysRng (lib/src/load_balancing.rs). A simulator could not
drive any of it from its own clock and seed.

Time is now a parameter, as in the UDP core. RetryPolicy::fail(now, rng),
succeed(now) and can_try(now); PeakEWMA::new(now), observe(rtt, now) and
get(active, now); Candidates carries the selection's instant. The
selection entry points of Backend, BackendList and BackendMap, and
BackendSource::select, take `now`. The mux passes Context::now, the UDP
core the admission's instant. ExponentialBackoffPolicy records no instant
before its first attempt; its window is zero until then.

Randomness comes from one StdRng per BackendMap. BackendMap::new seeds it
from the OS once, BackendMap::with_seed from a u64. It seeds every
cluster's Random and PowerOfTwo policy and supplies every backoff jitter.
Random::new, PowerOfTwo::new and the Default impls of Random and PeakEWMA
are removed. Backend::new_at builds a backend at an injected instant;
Backend::new stays the production default. The TCP proxy, which is not
simulated, keeps Instant::now and rand::rng() at its own edge.

No allocation or dynamic dispatch is added: the clock is an Instant by
value and the RNG a generic &mut R. Steady-state selection still
allocates nothing, the pinned pick sequences are unchanged, and a dial
through Mux::dial_backend still makes 6 allocations. BackendMap grows
from 152 to 472 bytes for its generator, once per worker.

The two seed-correlation guards move to backends.rs, where the OS seed
now enters, and the P2C tie-break test replays the sampled pair from its
seed instead of reading wall-clock stamps. New tests pin the backoff
window and its jitter, the connection-time decay, and one map seed
yielding one selection sequence; each was seen red first.

Refs #1684

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the refactor/inject-clock-rng-selection branch from 1671caa to 584c178 Compare September 29, 2026 21:19
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 080351b into main Sep 29, 2026
51 of 52 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the refactor/inject-clock-rng-selection branch September 29, 2026 23:22
FlorentinDUBOIS added a commit that referenced this pull request Sep 30, 2026
Refs #1684. This is the third PR of the sequence the maintainer set in #1684 (comment): G2 = (a), the UDP shape with reservation at selection.

It is based on `origin/main` `4918ad4f`, which includes #1698 (G1), #1700 (G3), #1704 and #1705.

## Design

- **Selection reserves.**
  - `BackendMap::reserve_backend(cluster, now)` and `reserve_sticky_backend(cluster, cookie, now)` choose a backend, then raise its `active_connections` by one (`Backend::reserve_connection`). The raise happens under the same borrow as the choice.
  - The next selection weighs that reservation exactly as it weighed the count `Backend::try_connect` took at the dial.
  - Nothing connects during selection.
  - The empty and no-candidate handling that `backend_from_cluster_id` had moved into a private `BackendMap::select_backend`, which both paths share.
- **The embedder dials.**
  - The router's seam returns a backend and no socket.
  - `Mux::dial_backend` connects to `BackendId::address` after the selection borrow is released. The address travels inside `BackendId`, which is the `(BackendId, SocketAddr)` shape the maintainer asked for.
- **A failed dial releases, through the ledger.**
  - A `connect(2)` error pushes the new `BackendChange::DialFailed(Instant)` and returns `BackendError::ConnectionFailures`.
  - Applying `DialFailed` calls `Backend::release_failed_dial`, which does `dec_connections`, `failures += 1` and `retry_policy.fail(at, rng)`.
  - `BackendRegistry::apply_all` now takes the worker's `&RefCell<BackendMap>`. It borrows it only in the `DialFailed` arm, to draw the backoff jitter from the map's generator; every other change leaves the map alone.
  - The existing drain before each `Router::plan_connect` applies the release before the next selection reads the counters. The backend then sits exactly where a failed `Backend::try_connect` left it.
- **A successful dial keeps the reservation** as its connection's count. `ConnectionClosed` releases it, as before.
- **A factory `sim/` can reach:** `pub fn BackendId::new(slot, backend_id, address)`.
  - A slot means something only to the registry that issued it; the mux still mints through `BackendRegistry::id_for`.
  - A selector holds no socket, so a simulator implements one without `mio`. `git grep -q mio -- sim/Cargo.toml` still exits 1.
- **LIFECYCLE §9, invariant 14** gains the bullet "Selection reserves, failure releases". The "Drain before any read" bullet drops its argument for selecting and dialling in one call.
- **Unchanged:** the TCP proxy (`tcp.rs`) still calls `BackendMap::backend_from_cluster_id` and `Backend::try_connect`.

### Renames, for #1706 (#524, `feat/lb-affinity-key-l7-tcp`)

#1706 adds an affinity `key` to `select_and_dial` and `backend_from_cluster_id`. Whichever PR merges second rebases onto the other:
- `router::BackendDialer` → `router::BackendSelector`
- `BackendDialer::select_and_dial` → `BackendSelector::select`, same `(cluster_id, affinity)` parameters
- `router::DialedBackend` → `router::SelectedBackend`, which drops its `socket` field
- crate-private `RegistryDialer` → `RegistrySelector`
- `Router::backend_from_request` now returns `BackendId`, where it returned `(TcpStream, BackendId)`

`BackendMap::backend_from_cluster_id` keeps its signature. The mux now calls the new `reserve_backend` and `reserve_sticky_backend`, so #1706's `key` belongs on those as well.

### Pre-existing `active_connections` leak, not fixed here

Three exits of `Mux::dial_backend` after a successful `connect(2)` drop the new connection without releasing its connection count:
1. `Connection::new_h2_client` returning `None`, when the buffer pool is exhausted (`BackendConnectionError::MaxBuffers`).
2. A refused `Connection::start_stream`, when the backend's maximum concurrent streams is reached.
3. The `register_socket` rollback. It releases the `active_requests` charge and the gauges, but not `active_connections`.

On `main` each of these already leaked the `+1` that `Backend::try_connect` took on success. Now each leaks the reservation, which is the same `+1` taken earlier. **This change does not make it worse:** on each of these paths the count is the same before and after. So I did not fix it here, and LIFECYCLE §9 names the three exits.

**Proposed follow-up:** push `BackendChange::ConnectionClosed` for the reserved slot on all three exits, the same release a closing connection emits. Pin it with one test per exit, asserting `active_connections == 0` after the drain.

### Behaviour

- A successful dial behaves the same.
- A failed synchronous dial leaves the same end state (`active_connections`, `failures`, backoff), applied at the next drain.
- The AllDown → Available availability event now fires after a successful selection rather than after a successful connect.
- The pinned pick sequences (`backend_selection_pick_sequences_are_pinned`) are unchanged.

## Measurements

Measured with a throwaway probe (`size_of`, plus `test_allocations::allocations()` around `Mux::dial_backend`), not committed.

| | before (`080351ba`) | after |
|---|---|---|
| heap allocations per `Mux::dial_backend`, selection to linked stream (3 runs) | 6, 6, 6 | 6, 6, 6 |
| steady-state selection (`backend_selection_allocates_nothing_in_steady_state`) | 0 | 0 |
| router stamping (`stamping_a_dialled_backend_allocates_nothing`) | 0 | 0 |
| `size_of::<BackendChange>()` / `BackendDelta` | 16 / 24 B | 16 / 24 B (`Instant` fits the niche) |
| `Backend` / `BackendList` / `BackendMap` / `MuxClear` | 208 / 72 / 472 / 4984 B | unchanged |

No new allocation, syscall or dynamic dispatch is added on the dial path.
- The `connect(2)` moved from `Backend::try_connect` to `Mux::dial_backend`; it is the same single syscall.
- The `BackendMap` borrow happens only on a failed dial.

## Tests: red, then green

For each mutation below, I changed the production code, quoted the failing assertion, then restored it. All pass green afterwards.

- **Mutation:** `Backend::reserve_connection` returns `Ok(())` without `inc_connections`.
  - `a_second_selection_observes_the_first_selections_reservation`: `the second selection landed on the first one's backend: the first selection did not reserve its connection (first=backend-a active=0, second=backend-a active=0)`
  - `power_of_two_weighs_every_reservation`: `2 selections must hold 2 reservations, got [0, 0]`
  - `a_failed_dial_releases_its_reservation_and_records_the_failure`: `selection reserves`, `left: 0 right: 1`
- **Mutation:** `release_failed_dial` without `dec_connections`.
  - `a_failed_dial_releases_its_reservation_and_records_the_failure` and `a_synchronously_failed_dial_releases_its_reservation` both fail with `a failed dial must release exactly its one reservation (saturating at 0)`, `left: 1 right: 0`
- **Mutation:** `Mux::dial_backend` returns the connect error without pushing `DialFailed`.
  - `a_synchronously_failed_dial_releases_its_reservation`: `the failed dial must release the reservation selection took`, `left: 1 right: 0`
- **Mutation:** an extra `inc_connections` after a successful connect.
  - `a_successful_dial_counts_its_connection_once`: `one dial must hold exactly one connection on its backend`, `left: 2 right: 1`

Notes on the new and changed tests:
- `a_second_selection_observes_the_first_selections_reservation` replaces `a_second_selection_observes_the_first_dials_connection`. It now selects twice with no dial and no drain in between. A `RENAMED_TESTS` entry keeps the #1550 CHANGELOG citation resolving.
- `a_synchronously_failed_dial_releases_its_reservation` dials `255.255.255.255:80`, which fails before any packet leaves (`ENETUNREACH`, or `EACCES` with a default route). It asserts the `Err`, so a host where that connect succeeds fails the test instead of passing it.
- `invariant_14_*` in `h2.rs`: all 6 pass, and every assertion is unchanged. Only two things changed:
  - their `reconcile` helper gains an `unreachable!` arm for `DialFailed`, since no invariant-14 scenario dials;
  - two `registry.apply(delta)` calls now pass a local `BackendMap`.
- `stamping_a_dialled_backend_allocates_nothing` now uses a socket-free `StubSelector` whose id comes from `BackendId::new`. That is the shape a simulator will use.

## Docs

- `lib/src/protocol/mux/LIFECYCLE.md`: §3.2 and §9 invariant 14.
- `router.rs`: the `BackendSelector` doc, rewritten. The old doc argued that selection and dial had to be one call; it now describes reservation and release.
- `doc/lifetime_of_a_session.md` and `doc/benchmark.md`: the dial path.
- `doc/rate-limit-design.md` and `lib/src/server.rs`: they now say where the non-blocking dial lives, `Mux::dial_backend` for HTTP and `Backend::try_connect` for TCP.
- `e2e/src/tests/tests.rs`: a TO SEE THIS RED note now points at the dial's new site and says its measurement was taken at the old one.
- `doc/testing.md` §5: how a simulator's selector mints ids, and the reservation rule it must keep.
- `CHANGELOG.md`: a BREAKING (library API) entry, listing the renames.

## Validation

Run on head `208ed9eb`, rebased onto `4918ad4f`. Each 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 (1865 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 (515 passed)
- `cd fuzz && cargo +nightly fuzz build` -> exit 0
- `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)



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

Closes #1684

This is the fourth and last PR of the sequence the maintainer set in #1684 (comment): a deterministic simulation that drives backend selection through a selector the simulator owns. It builds on:
- #1698, which removed `L7Proxy::backends`;
- #1700, which injects the clock and the RNG into selection;
- #1709, where selection reserves a connection and a failed dial releases it.

It is based on `origin/main` `4420d132`.

## Design

`sim/tests/backend_selection_sim.rs` runs under moonpool-sim, gated on `--cfg tokio_unstable` like every other simulator in `sozu-sim`.

- **The simulator owns the selector.** `SimSelector` implements `router::BackendSelector`:
  - It wraps a real `BackendMap::with_seed`, seeded from moonpool's RNG, and calls `reserve_backend` / `reserve_sticky_backend`.
  - It numbers slots in minting order and mints ids with `BackendId::new`.
  - The harness calls `Router::backend_from_request` with it, exactly as `Mux::dial_backend` calls it with `RegistrySelector`.
- **It plays the embedding proxy's side.** A dial either connects or fails, as the seeded RNG decides:
  - On a connect: `set_connection_time` and `retry_policy.succeed`.
  - On a failure: `Backend::release_failed_dial`, with the map's `rng()`.
  - Open connections close at random.
- **Its clock is its own.** One base `Instant` is captured per run, and every call receives `base + offset`. The offset advances only by seeded draws, sometimes past the longest backoff window.
  - `Workload::run` never awaits, for the same reason as `h2_simulation.rs`: `BackendMap` holds `Rc`s, and moonpool's `Workload` future must be `Send`.
- **Each seed picks a policy for each of the two clusters.** The seven choices are RoundRobin; Random; LeastLoaded on Connections or ConnectionTime; PowerOfTwo on Connections or ConnectionTime; and HRW. So `PeakEWMA` runs on the injected clock.
- **Invariant, checked after every step:** each backend's `active_connections` equals a shadow count the harness keeps (+1 per reservation, −1 per failed-dial release and per close). This is LIFECYCLE §9 invariant 14's "selection reserves, failure releases", observed from outside the core. After the final drain every count is 0.
- **`backend_selection_simulation_seed_sweep`** runs at least 64 seeds (default 64, 400 steps each) and asserts `successful_runs == seeds`.
- **`backend_selection_simulation_is_deterministic`** runs 8 seeds twice each and requires byte-identical traces and equal counts.
  - It also checks absolute values: at least 100 selections, and some failed dials, closes and sticky answers.
  - It requires at least one Random or PowerOfTwo cluster, so the map's own generator is exercised.
  - A fresh backoff window must close exactly one second later on the harness's clock, which a leaked wall-clock read fails.
  - The 8 traces must all differ from each other.
- **The trace records decisions only:**
  - the policy per cluster;
  - per selection: cluster, stick flag, cookie, `BackendId` slot, backend, and sticky answer;
  - each dial outcome (reservation kept, or released);
  - each close and each clock advance, in whole milliseconds of the harness's virtual offset.

  It never holds an `Instant`.
- `git grep -q mio -- sim/Cargo.toml` exits 1: a selector holds no socket, so the simulator needs no `mio`.
- CI: the new sweep is a step of the per-PR `udp-simulation` job, next to the UDP, TCP-preread and H2 sweeps.

Two nits from the #1709 review are folded in:
- The duplicated doc line on `BackendMap::backend_from_cluster_id` is removed.
- `BackendMap::backend_from_sticky_session` is removed. Since #1709 its only callers were its own three tests, which now exercise `reserve_sticky_backend`. The test that finds a recorded backend used to accept any connected result; it now asserts that it reached `mycluster-2` and that the reservation was taken. This is a library API removal (CHANGELOG ➖ Removed), with no runtime change.

## Determinism evidence

I replayed seed `0x1684` twice with `SOZU_BACKEND_SELECTION_SIM_SEED=0x1684 RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked --test backend_selection_sim backend_selection_simulation_seed_sweep -- --nocapture`, then kept the trace lines:

```
$ wc -l trace-1 trace-2
572 trace-1
572 trace-2
$ cmp trace-1 trace-2 && echo TRACES_IDENTICAL
TRACES_IDENTICAL
$ sha256sum trace-1 trace-2
416db0603f4a010027e427f19f7d28196e5c1769c6997d47f393417b538cf55b  trace-1
416db0603f4a010027e427f19f7d28196e5c1769c6997d47f393417b538cf55b  trace-2
```

The trace holds 243 selections, 43 failed-and-released dials, 104 closes and 75 sticky answers. It opens with:

```
cluster cluster-a policy=LeastLoaded metric=ConnectionTime
cluster cluster-b policy=Hrw metric=Connections
select cluster-a stick=true cookie=Some("cluster-a-sticky-2") -> slot=0 backend=cluster-a-2 sticky=Some("cluster-a-sticky-2")
dial slot=0 -> failed, released
select cluster-b stick=false cookie=None -> slot=1 backend=cluster-b-0 sticky=None
dial slot=1 -> connected in 98ms
select cluster-b stick=false cookie=None -> slot=2 backend=cluster-b-1 sticky=None
dial slot=2 -> connected in 198ms
select cluster-b stick=false cookie=Some("no-such-backend") -> slot=3 backend=cluster-b-2 sticky=None
dial slot=3 -> failed, released
```

## Red, then green

For each mutation below I changed the code, quoted the failing assertion, then restored it. Both tests pass afterwards.

- **The harness's `now()` returns `Instant::now()`** (a leaked wall clock):
  - Both tests fail with `seed=0x1684: the window must close one second later on the harness's clock` (and `seed=0x0: …` in the sweep).
  - Two runs that both read the wall clock would still agree with each other, which is why the absolute clock check exists.
- **`BackendMap::new()` replaces the seeded `BackendMap::with_seed`**, with the draw still consumed so every other draw stays aligned:
  - The determinism test fails with `seed=0x1684: one seed must yield one byte-identical trace`.
  - My first version checked one seed only and stayed green under this mutation. That seed drew LeastLoaded/HRW, so only backoff jitter consumed the map's generator. The test now covers eight seeds and requires a map-seeded policy.
- **`Backend::reserve_connection` without its increment** (in `lib/src/backends.rs`):
  - Both tests fail with `seed=0x1684 step=2: slot 1 (cluster-b-0) holds 0 connections, the reservations, releases and closes this harness made add up to 1` (and `seed=0x0 step=0` in the sweep).

## Allocations

This PR changes no code on the dial path. I measured with a throwaway probe (`test_allocations::allocations()` around `Mux::dial_backend`, plus `size_of`), not committed:

| | `origin/main` `4420d132` (as measured for #1709) | this branch |
|---|---|---|
| heap allocations per `Mux::dial_backend`, 3 runs | 6, 6, 6 | 6, 6, 6 |
| steady-state selection (`backend_selection_allocates_nothing_in_steady_state`) | 0 | 0 |
| router stamping (`stamping_a_dialled_backend_allocates_nothing`) | 0 | 0 |
| `Backend` / `BackendList` / `BackendMap` / `BackendChange` / `BackendDelta` / `MuxClear` | 208 / 72 / 472 / 16 / 24 / 4984 B | unchanged |

## Proposed follow-up: the three reservation-leak exits

LIFECYCLE §9 invariant 14 names three exits of `Mux::dial_backend` past a successful `connect(2)` that drop the connection without releasing its reservation:
1. `Connection::new_h2_client` returning `None`, when the buffer pool is exhausted (`BackendConnectionError::MaxBuffers`).
2. A refused `Connection::start_stream`, when the backend's maximum concurrent streams is reached.
3. The `register_socket` rollback, which releases `active_requests` and the gauges but not `active_connections`.

Before #1709 they leaked the count `Backend::try_connect` took; now they leak the reservation, the same `+1`.

**Proposal: one small PR.**
- On each of the three exits, push `BackendDelta { slot: backend.slot(), change: BackendChange::ConnectionClosed }` before returning. This is the same release a closing connection emits, applied by the drain before the next selection.
- Add one test per exit, each asserting `active_connections == 0` after `apply_all`:
  - pool exhaustion: a pool too small for an H2 client;
  - stream refusal: a connection whose stream limit is already reached;
  - registration failure: a registry that refuses `register_socket`.
- Every test must be seen red before the fix.
- The shadow check of this simulator can then be extended to those exits, once the harness can drive them.

## Validation

Run on head `ac4160e8`, based on `4420d132`. Each 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 (1869 passed, 0 failed, 17 ignored, all ignores already on main)
- `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked` -> exit 0 (33 passed, both new tests included)
- `cargo test -p sozu-e2e --locked -- --skip tests::fuzz_tests::` -> exit 0 (522 passed)
- `cd fuzz && cargo +nightly fuzz build` -> exit 0
- `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 repository's pre-push hook (`cargo build --all-features`, then `cargo clippy --all-features --all-targets -- -D warnings`) passed on push.

Docs: `doc/testing.md` §5 gains the simulator recipe, a taxonomy row and the run command. The sim-harness list in the `sim/Cargo.toml` comment is updated. CHANGELOG has ✨ Added for the simulation and ➖ Removed for `backend_from_sticky_session`.




Signed-off-by: Florentin Dubois <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant