Skip to content

test(udp): drive the early-wheel-fire eviction test from a simulated clock - #1621

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
test/udp-wheel-deterministic
Sep 27, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
test/udp-wheel-deterministic

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Summary

udp::tests::an_early_wheel_fire_still_evicts_the_idle_flow depended on the wall clock in three places: the test slept between steps, Timer::set_timeout added the delay to start.elapsed(), and UdpListenerSession::timeout handed Instant::now() to the manager. Under host load it panicked on either of its two preconditions:

Changes:

  • lib/src/timer.rs: Timer::set_timeout_from(now, delay, state) and Timer::poll_at(now). set_timeout now delegates to set_timeout_from(Instant::now(), ..), which computes the same value; poll is unchanged.
  • lib/src/udp.rs: the listener session's expiry body moves to timeout_at(token, now); ProxySession::timeout calls it with Instant::now().
  • lib/src/udp.rs, production: arm_timer counts the delay from the drain's now (set_timeout_from) instead of a fresh clock read, so the listener's entry lands on the grid point its deadline maps to however late the drain runs. In production now is microseconds old; this removes that drift and nothing else.
  • The test drives the real TIMER and the real session through these at instants derived from one clock read. sleep_until is gone and every assertion is unchanged, including both preconditions, which now hold by construction.
  • lib/src/protocol/udp/LIFECYCLE.md and CHANGELOG.md describe the change.

Verification

  • Before, under load: 20 runs -> 5 passed, 15 failed (wheel must fire EARLY)
  • After, same load: 50 runs -> 50 passed, 0 failed
  • Red check, same load: with self.armed_deadline = None; removed from UdpManager::handle_timeout, 5 runs -> 5 failed on wheel re-armed after the early fire (next wheel date at the TICK_MAX sentinel); restored -> green
  • cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -> exit 0
  • cargo +nightly fmt --all -- --check -> exit 0
  • cargo clippy --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd --all-targets -- -D warnings -> exit 0
  • cargo test --locked -p sozu-lib -> exit 0, 1224 lib tests passed; -p sozu -> exit 0; -p sozu-command-lib -> exit 0
  • RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked --test <udp_simulation|tcp_preread_sim|h2_simulation|metrics_lease_sim> -> exit 0 each (6, 6, 12, 6 passed)
  • check_doc_citations.py: --self-test 0, broken fixture 1 with its report, --base origin/main 0, plain 0
  • RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked -> exit 0

Closes #1619

Signed-off-by: Florentin Dubois [email protected]

…clock

`an_early_wheel_fire_still_evicts_the_idle_flow` slept on the real clock,
and the wheel read that clock on its own twice: `Timer::set_timeout` added
the delay to `start.elapsed()`, and `UdpListenerSession::timeout` passed
`Instant::now()` to the manager. Under host load the arming rounded onto
the next grid point, or the fire landed past the deadline, and the test
panicked on its own precondition (15 red runs out of 20 with eight `yes`
hogs pinned to the test's CPU).

`Timer` gains `set_timeout_from(now, delay, state)` and `poll_at(now)`;
`set_timeout` and `poll` keep their behaviour. The session's expiry body
moves to `timeout_at(token, now)`, which `timeout` calls with
`Instant::now()`. `arm_timer` counts the delay from the drain's `now`, so
the listener's entry lands on the grid point its deadline maps to however
late the drain runs.

The test drives the real wheel and session through these at instants
derived from one clock read, with every assertion unchanged: 50 green
runs out of 50 under the same load, and still red when
`UdpManager::handle_timeout` stops clearing `armed_deadline`.

Closes #1619

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 771c9e9 into main Sep 27, 2026
74 of 76 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the test/udp-wheel-deterministic branch September 27, 2026 13:34
FlorentinDUBOIS added a commit that referenced this pull request Sep 27, 2026
…put queue (#1625)

Closes #1604

## Problem

`zero` was both the frame-header **input** buffer and the control-frame **output** buffer, and stream frames were written from each stream's own `kawa.out`, serialised against `zero` only through `expect_write`. When a partial write parked a stream mid-frame and the stream was then removed (peer RST_STREAM, `end_stream`, expiry, `prune_inactive_streams_while_closing`, any of the `remove_dead_stream` callers), the rest of that frame was dropped, and the next bytes on the connection — a control frame, a GOAWAY, another stream's frame — landed inside what the peer still parsed as that frame.

## Reproduced first (red on `a0785505`, then green)

Three new tests in `lib/src/protocol/mux/h2.rs` parse the wire the way the peer does:

| test | failure on `a0785505` |
|---|---|
| `a_removed_half_written_stream_still_completes_its_frame` (removal, then a PING ACK) | `left: Err("frame type 0x0 announces 65536 bytes, 4 remain")` |
| `a_removed_half_written_stream_does_not_corrupt_the_next_stream_frame` (removal, then another stream's DATA) | `left: Err("frame type 0x0 announces 65536 bytes, 0 remain")` |
| `a_peer_reset_of_a_half_written_stream_still_completes_its_frame` (peer RST_STREAM read while parked) | `left: Err("frame type 0x0 announces 32 bytes, 28 remain")` |

The #1599 and #1601 tests on the edge cases of `zero` (deferred ACK, GOAWAY and initial GOAWAY mid-frame, forced shutdown read, backend `end_stream` RST, orphaned DATA remainders) stayed green on that head and keep their intent here. On this tree, disabling the adoption of the cut frame's rest (`self.output.adopt_tail(kawa, tail)` → `let _ = (kawa, tail);`) reddens the three #1604 tests with the same messages and every #1601 test on the framing invariant's debug assertion.

## Design

One **ordered output queue** per connection, `H2Output` (`lib/src/protocol/mux/h2_output.rs`): every control frame, and the unsent rest of the one stream frame a partial write cut, each **whole** when queued. `zero` is input only.

- **Stream frames stay zero-copy.** A transmit gathers the queue first, then the stream's `kawa.out` blocks as `IoSlice`s into `kawa.storage`, in the same `writev(2)` (`h2_transmit::gather_after`, `ConnectionH2::gather_transmit`).
- **Commit on write.** When the write stops inside a stream frame, `h2_transmit::frame_tail` reads the gathered frame headers and measures the rest of that frame — extended through CONTINUATION up to END_HEADERS for an unfinished header block, since RFC 9113 §6.10 forbids any other frame in between — and `ConnectionH2::handle_write` has the queue adopt it (copied, consumed from the stream, counted to the stream at once). A stream therefore only owns frames the wire has not started; removing it drops whole unsent frames, never half of one.

Why a bounded copy rather than references into `kawa.out` kept alive after removal:

- **HAProxy** owns every committed byte in its `mbuf` ring: control frames are appended with `br_tail` (`h2c_ack_settings`, `h2c_send_ping`, `src/mux_h2.c`), and `h2s_make_data`'s zero-copy path *swaps* the whole stream buffer into the ring, falling back to `goto copy` when the swap cannot apply.
- **h2 (hyperium)** keeps one `FramedWrite` buffer for control frames and frame heads and holds an in-flight DATA payload **by value** in `Encoder::next` until written (`src/codec/framed_write.rs`); `has_capacity()` is false meanwhile. Its payload is a reference-counted `Bytes`, so liveness after the stream goes away is free.
- **Sōzu**'s stream storage is a pool buffer that a removed stream gives back, with no reference count. Keeping references alive would mean deferring the release of every removed stream's buffer (options (a)/(b) of #1604, which touch every removal site and the slot recycling in `Context`). Copying only the in-flight rest keeps the zero-copy path for everything else and bounds the copy to one frame or header block, paid only on a partial write.

The queue holds **128 bytes inline** (a frontend's whole server preface is 79) and spills to the heap only past that, so a connection that never meets backpressure allocates nothing for its output — as the pool buffer `zero` it replaces did not.

### Review fixes (second commit)

- **`frame_tail` is linear in the gathered slices.** It used to rescan from the first slice for every header byte, O(frames × slices), after every transmit; the reviewer measured ~1.9 ms per call for 2700 one-byte DATA frames (an H1 chunked body with tiny chunks). It now walks a forward-only cursor, and the shells call it only when `size < offered`. `the_walk_is_linear_in_the_slices` counts slice steps (≤ 5400 for 5400 slices; the rescan mutation gives 7292700).
- **`H2Output` gives back sent heap bytes while in use.** `consume` only advanced `head`, so a queue that never drained under backpressure kept every sent byte. It now compacts once the sent prefix is past the retained capacity and larger than what is left, and shrinks a capacity over 4× the rest. `a_queue_that_never_drains_stays_bounded` (without it: head 4096000, capacity 4 MiB).
- **Emptying the queue releases the read cap.** `frontend_hung_up_while_draining` cleared the queue but not `reads_wait_for_output`; `ConnectionH2::clear_output` now does both. `clearing_the_output_releases_the_read_cap`.
- Stale `zero` wording in `graceful_goaway` / `send_initial_goaway` fixed.
- **Corrected claim:** dropping a removed stream's unsent frames keeps the *framing* whole, not the HPACK tables — an unsent HEADERS block was already encoded and its insertions stay in the encoder table. `LIFECYCLE.md` invariant 28, `h2_output.rs` and `doc/h2_mux_internals.md` now say so. That desync predates this PR and is **#1627** (reproduced red on `771c9e90`, with a second path in `check_header_capacity`); it is not fixed here.

### Removed mechanisms

`zero_output_deferred`; `queue_zero_output` / `park_zero_output`; the `zero_holds_output` read guard and `handle_header_state`'s assertion; the `ResumeZero` flush stage with `H2ControlFlushStage` and `ControlFlushResume` (the control walk now queues and flushes **once**, `H2ControlFlushTarget::FlushOutput`); `expect_write = Some(Zero)` (only `Other` is ever parked, for scheduling); the reassembly guards of the WINDOW_UPDATE, RST_STREAM and shutdown flushes. `flush_zero_buffer` → `flush_output_buffer`. `expect_write` for `Other` stays: it keeps a parked stream first in line, but no longer carries framing.

### Behaviour changes, deliberately

- **READABLE no longer drops while an ACK waits.** Its only justification was the shared buffer. Reads now stop only once one buffer of output is queued (`output_read_cap`), as HAProxy's demux stops on a full `mbuf` (`H2_CF_DEM_MROOM`); `a_full_output_queue_stops_reading_until_it_drains` pins it.
- **A backend H2 connection turns READABLE on after its preface** in the `(ClientSettings, Client)` arm: the old `ResumeZero` stage did it as a side effect of flushing `zero`, and a client connection starts write-only. Found while removing that stage; `a_backend_connection_reads_once_its_preface_is_out` pins it.
- The deferred initial GOAWAY is sent in the pass that queues it instead of the next one.
- `h2_drain`'s deferral of the initial GOAWAY during header reassembly now protects no buffer; it is kept as drain policy (documented), since removing it changes the drain, not the output.

## Tests

New: the three #1604 tests; `a_cut_header_block_is_completed_before_the_ack` (cut inside HEADERS and exactly on the HEADERS/CONTINUATION boundary); `a_full_output_queue_stops_reading_until_it_drains`; `a_backend_connection_reads_once_its_preface_is_out`; `h2_output` unit tests (order, prepaid accounting, inline→heap spill and back); `h2_transmit` `frame_tail_cases` and `gather_after_offers_the_prefix_first_and_only_when_there_is_one`. Each new or rewritten test's "TO SEE THIS RED" recipe was run and its failure line recorded (2026-09-27).

No test was deleted without a replacement. Rewritten, with the intent kept:

- **Premises that read the old internals** now read the queue: the #1601 fixture's `!is_readable()` premise → `!output.is_empty()` (reads no longer stop); the two stalled-drain tests' and the two liveness tests' `expect_write == Some(Zero)` → queued output; the #1599 orphan tests detected the PING ACK "in `zero`" → in the queue.
- **Fixtures that queued non-frame bytes** as a stream's output (`FIRST_BLOCK`/`SECOND_BLOCK`, the 256 KiB rustls body) now hold real DATA frames of the same lengths: a stream's `kawa.out` only ever holds whole H2 frames, and the write pass now reads their headers. Byte counts and the byte-equality oracle are unchanged.
- `skipping_an_orphaned_payload_keeps_readable_off_while_zero_holds_output` → `skipping_an_orphaned_payload_reads_on_while_output_is_queued`, and `no_frame_header_is_read_while_zero_holds_unflushed_output` → `a_frame_header_read_leaves_queued_output_intact`: both pinned the cure for the shared buffer; the replacements pin the property that replaces it, and the second keeps the original wire assertion (WINDOW_UPDATE, then PING ACK).
- `a_deferred_ack_does_not_strand_reads_when_its_parked_stream_is_removed` asserts the queue drains (the wire is asserted by the new #1604 test it used to say was out of scope).
- `a_legitimate_continuation_survives_a_graceful_goaway` waits on the queue instead of `expect_write`.
- `reassembly_property::qc_h2_header_reassembly_survives_interleaved_control_frame_flushes` sets `TCP_NODELAY` on its loopback peer: the interleaved WINDOW_UPDATE is now really written (it used to be deferred during reassembly), which puts sozu's end in delayed-ACK mode, and the peer's Nagle then held its next small CONTINUATION for up to 40 ms, longer than the yield-bounded read loop waits. Baseline 5/5 green, this tree 0/3 without and 3/3 with.
- `sim/tests/h2_simulation.rs` mirrors the new transmit bracket and control flush.

## Measurements (release, `--no-default-features --features crypto-ring,opentelemetry,splice,simd`)

20 requests, H2 one connection per request (`h2`) and multiplexed on one connection (`h2mux`), 30-byte body, `worker_count = 1`, LOAD1 < 4. Before = `bdc74ecd` (#1620), after = this branch.

| | before | after |
|---|---|---|
| intentrace `h2` writev / total (ANSI stripped, anchored on the syscall name) | 120 / 822 | 120 / 821 |
| intentrace `h2mux` writev / total | 44 / 290 | 44 / 290 |
| fdtrace `h2` writev | 132 | 120 |
| mcount `h2` mallocs / 20 conns, 4 runs | 3601, 3573, 3581, 3560 | 3570, 3578, 3571, 3586 |
| mcount `h2mux` mallocs, 4 runs | 842, 831, 845, 845 | 884, 823, 831, 846 |
| mcount realloc_grow `h2` / `h2mux` | 1181–1214 / 251 | 1202–1217 / 248–251 |

No syscall is added, and allocations are within run-to-run noise; the same held against `a0785505` before #1620 landed. fdtrace `h2mux` writev varies with pacing (44–64 across runs on both trees). A first cut stored the queue in a plain `Vec`, which measured +1.35 malloc and +0.7 realloc per connection. That is why the queue has inline storage.

## Validation (rebased on `0155d40b`, head `16d6aba8`)

Build, `cargo +nightly fmt --check`, clippy `-D warnings` with `crypto-ring,opentelemetry,splice,simd`, `cargo test` for `sozu-lib` (1274), `sozu` and `sozu-command-lib`, `cargo doc -D warnings`, the four `check_doc_citations.py` runs, the sim test and clippy under `--cfg tokio_unstable`: all pass on `16d6aba8`. E2E (`-- --skip tests::fuzz_tests::`): 456 passed, 0 failed, the HPACK e2e tests included. The three #1604 tests still fail without the fix (the `adopt_tail` mutation) on this head, with the same peer parse errors.

H2 e2e, 10 runs, `taskset -c 0 cargo test -p sozu-e2e -- h2 --skip tests::fuzz_tests:: --test-threads=20`. One CPU with 20 threads: without `--test-threads` the pin runs the tests serially, about 5 h per run. The same loop was run on `bdc74ecd`:

| test | this branch | `bdc74ecd` |
|---|---|---|
| `test_h2_continuation_survives_a_graceful_drain_mid_reassembly` (a single GOAWAY, then nothing) | 5 / 10 | 9 / 10 — pre-existing, #1623 |
| `test_h2_settings_ack_timeout_goaways_the_frontend` (client cannot send its preface) | 7 / 10 | 7 / 10 — pre-existing, #1624 |
| `test_h2_large_chunked_7mb_drains_fully` | 1 / 10 | 0 / 10 |
| `test_h1_to_h2_basic_request` | 1 / 10 | 0 / 10 |

`test_h2_large_chunked_7mb_drains_fully` failed once: the client read EOF at 3.13 of 7.76 MB after 1.65 s, with no RST. That is a close, not a stall and not a frame desync; either of those would have left the client reading until its 30 s deadline. No debug assertion or panic from `lib/` appears in any log. I could not reproduce it: `h2_correctness` 5 runs on each tree, pinned to one CPU with 20 threads, 0 failures on both. It is reported here unattributed, not claimed as pre-existing. `test_h1_to_h2_basic_request` failed once in the same way (a stability iteration under load).

## Docs

`doc/h2_mux_internals.md` (new "ordered output queue" section, control preamble, `flush_output_to_socket`), `lib/src/protocol/mux/LIFECYCLE.md` (new invariant 28, invariant 24 and §5 amended), `CHANGELOG.md`; module docs of `h2_drain`, `h2_header_reassembly`, `h2_control_tx`, `h2_close`. Line citations re-anchored on the same text and function.

## Not touched

Rebased on `0155d40b` (#1626, which fixed #1622, on top of #1620 (the in-tree HPACK module), #1617, #1618 and #1621). The only conflict was a line citation in `doc/testing.md`; every addition #1626 made to the shared docs is kept, and `converter.rs`, `hpack_state.rs` and `hpack/` are untouched by this PR. `pkawa.rs`, `converter.rs`, `hpack_state.rs` and the HPACK codec branch in `h2.rs` are untouched.

**Related, tracked separately: #1627** (HPACK table desync when an encoded HEADERS block is dropped unsent, see above). #1622 (smallest table size before the last one) was fixed separately by #1626, which this branch is rebased on.

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.

test: udp early-wheel-fire eviction test depends on wall-clock timing and fails under load

1 participant