Repository navigation
test(sim): deterministic H2-core simulation - #1485
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 24, 2026 00:30
`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]>
FlorentinDUBOIS
force-pushed
the
test/h2-simulation
branch
from
September 24, 2026 03:06
66791fe to
2fc7494
Compare
This was referenced Sep 24, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Delivers step C4 of #1359: the deterministic H2 simulator. C1–C3 landed in #1369;
sim/tests/h2_simulation.rsdid not exist.Byte-in/byte-out of
ConnectionH2as 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
FAILED3 runs of 3 — same structure, forked fingerprintdeadline = stream_idle_timeout - 100ms(one tick, the wheel's max earliness)FAILEDat the first probe:early_ms=0: the core retired stream 1 at deadline-0ms>=→>FAILED:4 live streams after opening 4 exceeds the configured ceiling 3queue_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::newmakes the one wall-clockInstant::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 publicConnection::set_timeout_durationat the injected base.The tick-boundary property takes
duration_to_tickas ground truth rather than re-testing it, computes(delay_ms + tick_ms/2) mod tick_msitself, 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 inh2.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 doesb"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n".starts_with(i)on the whole accumulated window, while the window offered isCLIENT_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 tode87c9450. One-line fix: compare&i[..i.len().min(24)].2. No connection-level inbound receive window is enforced.
H2FlowControl::windowis the send window; the receive side is onlyaccount_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_targetdocuments that PING/WINDOW_UPDATE/SETTINGS must not reset the timeout, "otherwise a peer sending periodic PINGs prevents timeout detection on stuck sessions" — butwrite_streamsopens with an unconditionalarm_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_timeouttherefore 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-simgainsmiounder[target.'cfg(tokio_unstable)'.dev-dependencies];Cargo.lockgrows by exactly one line.SocketHandler::socket_ref/socket_mutreturn&mio::net::TcpStream, andsozu_lib::testingre-exportsmio::{Poll, Registry, Token, net::UnixStream}but notnet::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 remainingFronttouch points.lib/diff is 0 files.Deviations from the
sim/precedent, each justifiedFollows
udp_simulation.rs— action grammar, shadow model, cross-stepcheck_invariants,SwarmConfig,FingerprintSink/ConfigSink,run_budget, the same env-var namespace and replay-knob contract; borrowstcp_preread_sim.rs's hand-rolled-wire rationale andfnv1a.Workload::runcontains no.await.moonpool_sim::Workloadis#[async_trait]without?Send, and the H2 core isRc-based by design, so holding the harness across a yield point does not compile. The alternatives were anunsafe impl Sendlie 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 alwaysContext::now, which the harness owns. The determinism property checks that claim rather than assuming it.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 newsim/tests/file is not picked up automatically —metrics_lease_simis in-tree and unrun today. One 3-line step added after the TCP-preread step in that job; it already setsRUSTFLAGS: '--cfg tokio_unstable'. Defaults (256 seeds × 400 actions) run in ~4 s. No nightly sweep job added, matching themetrics_lease_simprecedent.Verification
The literal
cargo test -p sozu-simreports0 passedfor every sim target — the files are#![cfg(tokio_unstable)], so the flag is what runs them. Likewisecargo clippyas specified never compiles them; running it with the flag caught a realclippy::while_let_loopin the frame decoder, fixed by restructuring rather than anallow.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 againstlib/. That sweep found only0x7fff_ffffand 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_innerreadInstant::now()andTimer::poll_tois private, so driving it fromsim/would be a host-clock read wearing a virtual clock's clothes. Responses and the outbound DATA path, becausefrontend_from_requestis only reached throughMux::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, orConnectionH2::stream_count, so the layer survives the Q10 extraction: onlyH2Harness::pumpis rewritten and themioline disappears.