Skip to content

test(sim): drive backend selection deterministically under moonpool - #1710

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
test/h2-deterministic-backend-selection
Sep 30, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
test/h2-deterministic-backend-selection

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

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:

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 Rcs, 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 refactor(mux): selection reserves, a failed dial releases #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.

Add sim/tests/backend_selection_sim.rs. It drives
Router::backend_from_request through a BackendSelector the harness owns,
over a real BackendMap::with_seed whose backends are built with
Backend::new_at, and plays the embedder's half of the reservation rule:
dials connect or fail, a failure is released with release_failed_dial,
connections close, and the harness keeps its own clock, advanced only by
seeded draws. After every step each backend's active_connections must
equal the harness's shadow count, and the final drain must bring every
count to zero. The sweep runs 64 seeds by default and becomes a step of
the per-PR simulation job.

backend_selection_simulation_is_deterministic runs eight seeds twice and
requires byte-identical traces of every decision (cluster, backend,
BackendId slot, sticky answer, reservation, release, close; no instant),
plus absolute checks: work happened, a map-seeded policy was drawn, and
a fresh backoff window closes one second later on the harness's clock,
which a leaked wall-clock read fails.

Also remove BackendMap::backend_from_sticky_session, whose only callers
were its own tests since the mux reserves through reserve_sticky_backend;
the tests now exercise reserve_sticky_backend with no affinity key. The
harness selector forwards the affinity key Router::backend_from_request
derives to reserve_backend and reserve_sticky_backend, as the mux
RegistrySelector does. Document the simulator recipe in doc/testing.md
section 5.

Closes #1684

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the test/h2-deterministic-backend-selection branch from ac4160e to e51dfd7 Compare September 30, 2026 09:22
@FlorentinDUBOIS
FlorentinDUBOIS merged commit b714b7d into main Sep 30, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the test/h2-deterministic-backend-selection branch September 30, 2026 10:22
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.

h2 sans-io core perimeter: recap of Q6, Q7 and Q12 (from #1340)

1 participant