Skip to content

test(sim): deterministic H2-core simulation - #1485

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
test/h2-simulation
Sep 24, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
test/h2-simulation

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Delivers step C4 of #1359: the deterministic H2 simulator. C1–C3 landed in #1369; sim/tests/h2_simulation.rs did not exist.

Byte-in/byte-out of ConnectionH2 as a server, from the preface through HEADERS/DATA/RST_STREAM/PING/SETTINGS/WINDOW_UPDATE, under a seeded action grammar with swarm subsets and two orthogonal adversarial axes redrawn every pass — read fragmentation down to one octet, partial writes down to one octet — plus a 1% buggify wire truncation.

Four properties, each seen red

property production reverted measured red
determinism remove the harness's re-anchor of the connection deadline onto the injected clock FAILED 3 runs of 3 — same structure, forked fingerprint
tick boundary deadline = stream_idle_timeout - 100ms (one tick, the wheel's max earliness) FAILED at the first probe: early_ms=0: the core retired stream 1 at deadline-0ms
stream ceiling admission gate >= → > FAILED: 4 live streams after opening 4 exceeds the configured ceiling 3
credit attribution queue_window_update(1, wire_payload_len) FAILED: left: {1: 19970} / right: {1: 1280, 3: 5120, 5: 10240, 7: 3330}

Determinism is checked both ways: same seed twice must be equal, and four seeds must produce ≥2 distinct fingerprints, so a constant trace cannot pass vacuously. Writing that guard found a real clock leak: ConnectionH2::new makes the one wall-clock Instant::now() the core still performs, and the connection deadline inherited it — microseconds against the harness's own clock, enough to flip a millisecond boundary. Re-armed through the public Connection::set_timeout_duration at the injected base.

The tick-boundary property takes duration_to_tick as ground truth rather than re-testing it, computes (delay_ms + tick_ms/2) mod tick_ms itself, and probes every millisecond of [0, 99].

Three production defects found — reported, not fixed here

No lib/ change is included; #1479, #1456 and #1462 are in flight in h2.rs. Each is in the file's doc, the CHANGELOG and the commit body with its reproduction.

1. A short read of 25..=32 octets disconnects a valid client. ConnectionH2::handle_read's early-preface guard does b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n".starts_with(i) on the whole accumulated window, while the window offered is CLIENT_PREFACE_SIZE = 24 + 9. A 24-octet constant cannot start with a 25-octet slice, so the test is unconditionally false. Measured at fixed chunk sizes: 1, 25, 26, 32 → CloseSession, 0 frames emitted; 12, 23, 24, 33, 64 → handshake completes. Any TCP or TLS read landing mid-SETTINGS-header kills the session. Guard dates to de87c9450. One-line fix: compare &i[..i.len().min(24)].

2. No connection-level inbound receive window is enforced. H2FlowControl::window is the send window; the receive side is only account_received_bytes, a counter deciding when to hand credit back. Measured: 106496 DATA octets accepted against an advertised 98303, no GOAWAY. RFC 9113 §6.9.1 makes that a MUST. Stated as measured, not as a verdict — back-pressure currently comes from the buffer pool, and whether that is the intended boundary is a design call.

3. A PING-only peer holds a stuck session open indefinitely. poll_read_target documents that PING/WINDOW_UPDATE/SETTINGS must not reset the timeout, "otherwise a peer sending periodic PINGs prevents timeout detection on stuck sessions" — but write_streams opens with an unconditional arm_timeout, so any pass with something to send reaches it. Measured with a 600 s timeout: PING@10s → 10 s, SETTINGS@40s → 40 s, PING@500s → 500 s; empty and WINDOW_UPDATE passes correctly do not move it. The three that move are exactly the three that queue an acknowledgement. front_timeout therefore never fires on a PING-only Slowloris.

Property 3 was rewritten from "window never overcommitted" to per-stream credit attribution rather than loosened to pass around finding 2.

One dependency line, and it is not a production one

sozu-sim gains mio under [target.'cfg(tokio_unstable)'.dev-dependencies]; Cargo.lock grows by exactly one line. SocketHandler::socket_ref/socket_mut return &mio::net::TcpStream, and sozu_lib::testing re-exports mio::{Poll, Registry, Token, net::UnixStream} but not net::TcpStream, so the in-memory socket's signature cannot be written without naming the crate. It disappears when the Q10 byte-in/byte-out extraction removes the remaining Front touch points. lib/ diff is 0 files.

Deviations from the sim/ precedent, each justified

Follows udp_simulation.rs — action grammar, shadow model, cross-step check_invariants, SwarmConfig, FingerprintSink/ConfigSink, run_budget, the same env-var namespace and replay-knob contract; borrows tcp_preread_sim.rs's hand-rolled-wire rationale and fnv1a.

  • Workload::run contains no .await. moonpool_sim::Workload is #[async_trait] without ?Send, and the H2 core is Rc-based by design, so holding the harness across a yield point does not compile. The alternatives were an unsafe impl Send lie or this. Nothing is lost: the workload is a single sequential task, so moonpool never had an interleaving to choose, and the clock the core sees was always Context::now, which the harness owns. The determinism property checks that claim rather than assuming it.
  • The preface bootstrap is delivered whole, because of finding 1 — documented at its single call site with the measured chunk-size table. Every byte after the handshake goes through the fragmentation axis.
  • The encoder/decoder is hand-rolled rather than reusing mux::parser, which is public and would have worked: feeding the core its own parser's inverse makes the oracle a function of the code under test. The only shared values are RFC-assigned wire constants.

CI

The UDP simulation (moonpool) job names each file explicitly, so a new sim/tests/ file is not picked up automatically — metrics_lease_sim is in-tree and unrun today. One 3-line step added after the TCP-preread step in that job; it already sets RUSTFLAGS: '--cfg tokio_unstable'. Defaults (256 seeds × 400 actions) run in ~4 s. No nightly sweep job added, matching the metrics_lease_sim precedent.

Verification

cargo +nightly fmt --all -- --check                                  exit 0
cargo build  --locked --no-default-features --features crypto-ring,… exit 0
cargo clippy --all-targets --locked … -- -D warnings                 exit 0
cargo test -p sozu-lib --locked …      1092 passed; 0 failed         baseline unchanged
RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked
    h2_simulation      10 passed; 0 failed
    metrics_lease_sim   6 passed   tcp_preread_sim 6 passed   udp_simulation 6 passed
check_doc_citations.py --root . / --base c0f01021    exit 0, 0 exempt spans

The literal cargo test -p sozu-sim reports 0 passed for every sim target — the files are #![cfg(tokio_unstable)], so the flag is what runs them. Likewise cargo clippy as specified never compiles them; running it with the flag caught a real clippy::while_let_loop in the frame decoder, fixed by restructuring rather than an allow.

Also removed on review: an #[allow(dead_code)] (renamed _keepalive), and the harness pool buffer raised 16384 → 16384 + 9, the documented H2 floor — a latent misconfiguration found by grepping the test's own literals against lib/. That sweep found only 0x7fff_ffff and the FNV-1a offset basis shared with production, so the test is behaviour-shaped.

What C4 does not cover

The adapter half of the timer (Mux::sync_timeout's re-validation): ready_inner/timeout_inner read Instant::now() and Timer::poll_to is private, so driving it from sim/ would be a host-clock read wearing a virtual clock's clothes. Responses and the outbound DATA path, because frontend_from_request is only reached through Mux::ready_inner. Connection-level inbound flow control and the connection idle deadline — findings 2 and 3; there is nothing to assert without certifying the gap. HPACK depth beyond static indices plus one literal :authority. TLS: socket_wants_write() is always false.

Every assertion reads frames off the wire, Connection::poll_timeout, or ConnectionH2::stream_count, so the layer survives the Q10 extraction: only H2Harness::pump is rewritten and the mio line disappears.

`sim/tests/h2_simulation.rs` drives `ConnectionH2::readable` /
`ConnectionH2::writable` under a moonpool-sim seeded workload, on the pattern
`udp_simulation.rs`, `tcp_preread_sim.rs` and `metrics_lease_sim.rs`
established. This is step C4 of the `poll_timeout` series; C1-C3 landed in
`95c5f379`.

It is the first simulator here whose core is not yet byte-in / byte-out:
`ConnectionH2` is still generic over `Front: SocketHandler`, so the harness
supplies an in-memory `SocketHandler` and drives the public entry points. The
clock the core reads is whatever the harness assigns to `Context::now`, which
is what makes the run a pure function of the seed. When the remaining `Front`
touch points go, `SimSocket` and the `mio` dev-dependency disappear and the
scenario and assertion layer is untouched.

Four named properties, each seen red before it was trusted:

- Determinism. One seed replayed twice yields a byte-identical trace of frames
  out, live stream count, published deadline and `MuxResult`; four other seeds
  produce more than one trajectory. Removing the harness's re-anchor of the
  connection deadline onto the injected clock reddens it 3 runs out of 3 --
  which is how the real leak it guards, the one wall-clock `Instant::now()`
  `ConnectionH2::new` still takes, was found.
- Tick-boundary timing. `duration_to_tick` (`lib/src/timer.rs`) rounds to the
  nearest tick, so an entry armed for `D` is delivered from `D - tick/2` and
  the earliness is `(delay_ms + tick_ms/2) mod tick_ms`, [0, 99] ms at the
  default tick. Driven at every millisecond of that window the core leaves the
  stream alone, and retires it exactly once strictly past the deadline.
  Shortening the core's idle deadline by one tick reddens it at the first probe.
- Concurrent-stream ceiling. Twelve opens against a configured ceiling of three
  refuse exactly nine, under whole-frame delivery and again under one octet per
  `socket_read` and one per `socket_write`. Relaxing the admission gate from
  `>=` to `>` reddens it at the fourth open.
- Per-stream inbound credit. Four streams fed uneven DATA round-robin, every
  read capped at 17 octets and every write at 257, so frame headers straddle
  reads: the per-stream WINDOW_UPDATE credit returned equals exactly the octets
  spent on that stream. Attributing every credit to stream 1 reddens it.

Three behaviours measured while writing it are recorded in the module doc and
deliberately not asserted, because an assertion loose enough to pass would
certify them.

`ConnectionH2::handle_read`'s early-preface guard compared the whole accumulated
window against the 24-octet preface while the window offered is 24 + 9, so a
short read settling past 24 octets force-disconnected a valid client -- measured
here at chunk sizes 1, 25, 26 and 32, which ended the connection with zero
frames emitted, against 12, 23, 24, 33 and 64 which completed the handshake.
Since fixed in `fa0b93a4` (#1487), whose own sweep walks the chunk size and pins
a wider band than the sampling above found. `H2Harness::bootstrap` still feeds
the handshake whole, now as a scoping choice rather than a workaround: measured
against `9472cd96`, every chunk size in 1..=40 completes it, so widening the
fragmentation axis over the handshake is possible and left to its own changeset.

No connection-level inbound receive window is enforced -- `H2FlowControl::window`
is the send side and `H2FlowControl::account_received_bytes` only decides when to
hand credit back -- so a peer pushed 106496 DATA octets against an advertised
98303 with no GOAWAY; back-pressure comes from the buffer pool instead (#1488).

`ConnectionH2::poll_read_target` documents that PING/WINDOW_UPDATE/SETTINGS must
not reset the connection idle timer, but `ConnectionH2::write_streams` opens
with an unconditional `ConnectionH2::arm_timeout`, so with a 600 s timeout and
one stream opened at t=10 ms a PING at t=10 s moves the deadline to t=10 s, an
empty pass at t=20 s and a WINDOW_UPDATE at t=30 s leave it, a SETTINGS at
t=40 s moves it, and a PING at t=500 s moves it again -- a PING-only peer holds
a stuck session open indefinitely. The per-stream deadline is immune (#1489).

Reported, not fixed: this changeset touches no `lib/` file.

`sozu-sim` gains one cfg-gated dev-dependency, `mio`:
`SocketHandler::socket_ref`/`socket_mut` still return `&mio::net::TcpStream`
and `sozu_lib::testing` re-exports `mio::net::UnixStream` but not `TcpStream`,
so the in-memory socket's signature cannot be written without naming it.
Test-only, already resolved by `sozu-lib` at the same workspace pin.

`Workload::run` carries no `.await`: `moonpool_sim::Workload` is declared
`#[async_trait]` without `?Send` while the H2 core is `Rc`-based by design, so
the harness accumulates its own `Duration` from the same seeded RNG instead of
`SimContext::time`. The workload is a single sequential task, so moonpool's
scheduler never had an interleaving to choose.

Wired into the existing per-PR `udp-simulation` CI job as one added step; no
deep nightly job is added (proposed, not added -- see `doc/testing.md`).

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