Repository navigation
fix(mux): re-validate an early timer firing, and give the H2 core poll_timeout() - #1369
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 20, 2026 11:43
FlorentinDUBOIS
force-pushed
the
refactor/h2-timer-ownership
branch
3 times, most recently
from
September 20, 2026 12:50
695274e to
f68aea8
Compare
…d with
`crate::timer`'s wheel is duration-based and rounds a requested delay to the
NEAREST tick (`duration_to_tick`: `(elapsed_ms + tick_ms / 2) / tick_ms`), then
`Timer::poll` recomputes `current_tick` from the real clock and fires everything
whose tick has come. An entry armed for deadline `D` is therefore delivered from
`tick * round(D / tick) - tick/2` onwards, and the delivery consumes the slab
entry either way.
The earliness is `(D_ms + 50) mod 100` at the worker's default 100 ms tick, so
it spans [0, 99] ms — a full tick minus a millisecond, not half a tick. The
first 50 ms are unconditional, because `next_poll_date` returns the tick grid
point `start + tick_ms * tick`. The further 49 ms need the loop to poll inside
`[100T - 50, 100T)`, which it reaches through another session's earlier wheel
entry plus loop latency, or through the `Token(1)` arm — both ordinary.
`Mux::timeout` took every delivery at face value: it called
`TimeoutContainer::triggered()` and ran the timeout body, so a 60 s
`front_timeout` could write a 408 and close a live session at 59.901 s, and a
`backend_timeout` could 504 a backend that still had time left. The same bound
applies identically on the backend branch; it does not apply to
`Mux::shutting_down`, which `shut_down_sessions()` drives directly and which
compares `context.now` against `drain.started_at` rather than consuming a wheel
delivery.
`TimeoutContainer` now records the absolute instant each armed entry is meant to
fire at — the mirror of the wheel entry the wheel itself does not keep, stamped
at exactly the sites that touch the wheel — and exposes it as `deadline()`.
`Mux::timeout` re-validates every delivery against it through the new
`consume_timer_entry` helper, on both the frontend and the backend branch.
An early delivery is put back at the SAME absolute deadline (`set_at`), never
re-armed for a fresh full duration. Those three steps — consume, re-validate,
put back — are one operation:
- re-arming with `set` would push a 60 s timeout out to ~120 s on every early
delivery;
- not re-arming at all is strictly worse. The wheel entry is already gone, so
rejecting the firing without putting it back leaves the session with no timer
and nothing to arm one: a LOST WAKEUP. That is exactly the bug fixed for the
UDP shell in `UdpManager::handle_timeout`, where `reschedule` emitted
`ArmTimer` only when the minimum deadline had MOVED.
Today's mux path cannot have the UDP bug on its own, because `TimeoutContainer`
has no memoization: `set`/`reset` unconditionally cancel and re-arm, and every
`StateResult::Continue` exit from `Mux::timeout` re-arms. The hazard belongs to
any design that ADDS memoization on top — a `poll_timeout()` core plus an
adapter that re-arms only when the deadline changed. Such an adapter must land
after this re-validation, never before it.
A container with no recorded deadline fails OPEN and is reported due: that is
the behaviour of every earlier release, and an immortal session would be worse
than the early close fixed here.
Also settles the unverified backend re-arm question on the same path. The
backend branch consumes the backend container unconditionally but re-arms only
when `!should_close`, while the shared tail can still return `Continue` with
only the frontend re-armed. That is safe, and the chain is one link longer than
it looks. The branch calls `Connection::end_stream` for every id in
`context.backend_streams[&token]`, unconditionally at the bottom of the loop.
`ConnectionH2::end_stream` then begins with `Context::unlink_stream` — but
`ConnectionH1::end_stream` does NOT: it guards `self.stream != Some(stream)` and
returns early first, skipping the unlink. That guard cannot reject a stream this
loop passes it, because an H1 connection carries at most one linked stream and
it equals `self.stream`: `self.stream = Some(..)` occurs only in `start_stream`,
paired with `link_stream`, and `self.stream = None` only inside `end_stream`,
after the unlink has run.
`Context::unlink_stream` is the eviction point this path relies on, not the only
one in the module: `remove_backend_stream` also has direct callers in `h1.rs`
and `h2.rs`. Extra eviction only strengthens the conclusion, but the premise is
"this loop evicts", not "nothing else can".
Work attached to the backend afterwards re-arms the container itself, because
`triggered` keeps its token and `ConnectionH1::{readable,writable}` /
`ConnectionH2::{write_streams,handle_headers_frame}` call `reset()` — which
matters because the pool-reuse branch of `Router::connect`, unlike the
fresh-dial branch, never arms it. The reasoning is recorded at the site, guarded
by a `debug_assert!`, and pinned by two tests that set `h1.stream = Some(0)` by
hand and therefore exercise the matched path only. The mismatch arm is guarded
by `debug_assert_h1_owns_stream`, which runs immediately before every
`end_stream` call in `Mux::timeout` and fires if the backend index and
`ConnectionH1::stream` ever drift, turning a prose invariant into a tripwire in
every debug / test / e2e build. It sits at the call site rather than inside
`ConnectionH1::end_stream` on purpose: that function's mismatch arm is an
`error!`, not an `unreachable!`, and is reachable from `EndpointServer` /
`EndpointClient` paths this proof never traced, so asserting there would assert
something broader than what was traced: `ConnectionH2::{close, end_stream}`
iterate their own wire map and hand each linked gid to the peer, which on an
H2-frontend / H1-backend session is a `ConnectionH1`. Running the full e2e suite
with a `debug_assert_eq!` in that mismatch arm passes with zero hits, which
shows absence of coverage, not absence of the path, and so is not a reason
either way.
The same earliness correction is applied to every unreleased note and doc
comment that carried the grid figure as a delivery bound: `CHANGELOG.md`'s
`fix(udp)` entry, `lib/src/udp.rs`, `lib/src/protocol/udp/manager.rs` (two doc
comments and one test comment) and `lib/src/protocol/udp/LIFECYCLE.md`, which
that `fix(udp)` entry points the reader at and which was the last uncorrected
copy. The `[0, 99]` ms bound is the one a consumer must tolerate, 50 ms is the
on-grid half. That paragraph's stale `timer.rs:496` citation — `:496` is a
commented-out `info!`, `duration_to_tick` is at `:616` — becomes a symbol
anchor; it was the last `timer.rs:NNN` citation in the tree.
`ConnectionH1::end_stream`'s post-condition comment also claimed
`unlink_stream` was the module's single eviction point. It is not —
`remove_backend_stream` has direct callers in `h1.rs` and `h2.rs` — and that
was the same claim the four other sites retracted. It survived four sweeps
because the phrase is line-wrapped, so a line-scoped grep for it returns a
confident zero. `test_timeout_fires_up_to_half_a_tick_early` and
`test_maximum_earliness_is_a_full_half_tick` keep their names and assertions —
they measure the grid mapping correctly — and gained the qualifier plus a
pointer to the consumer bound.
Operator-visible: nothing changes on a healthy session; a timing out session now
reaches its configured timeout exactly rather than up to one timer tick early.
Documented in `lib/src/protocol/mux/LIFECYCLE.md` §7.6 and invariants 21 and 22.
Signed-off-by: Florentin Dubois <[email protected]>
…e timer
No behaviour change beyond one deliberate clock-source shift, noted below. The
H1 and H2 cores stop owning a `TimeoutContainer` and instead publish the next
instant they want `timeout()` called at; the `Mux` `SessionState` impl becomes
the adapter that owns every wheel handle. This is the shape
`UdpManager::{poll_timeout, reschedule}` already uses, and it is what the timer
half of a deterministic H2 simulator needs: `lib/src/protocol/mux/h1.rs` and
`h2.rs` no longer reference `crate::timer` at all, so the cores can be driven
with no timer wheel in the process.
Each core now carries `timeout_duration` plus `timeout_deadline:
Option<Instant>` and exposes `poll_timeout()`. `Connection::{arm_timeout,
clear_timeout, set_timeout_duration}` replace `timeout_container().{reset,
cancel, set, set_duration}` one for one.
The six `TimeoutContainer` sites in `h2.rs` — field, constructor parameter,
constructor init, three `reset()` calls — go with it, and cannot be a separate
commit: `Connection` dispatches through a `forward!` enum, so
`timeout_container()` cannot be removed for the H2 variant alone. Leaving the
H2 field behind while the adapter owned a second handle would arm the wheel
twice or not at all, so neither half would build and test green on its own.
`Mux` gained `timeouts: HashMap<Token, TimeoutContainer>`: one handle for the
frontend token plus one per backend. `Mux::reschedule` walks the cores and
arms, re-arms or cancels only when what a handle holds differs from what its
core wants, then drops handles whose token has left `router.backends` —
`TimeoutContainer::drop` cancels, so no removal site has to remember to.
Three things make that memoization safe. Two have a test that fails when they
are dropped; the third has none and rests on the wrappers having no other exit:
- The reschedule is structural. `ready`, `timeout` and `shutting_down` are thin
wrappers around `*_inner` bodies whose only job is to run it on the way out,
so none of the early returns inside them can skip it.
- Consume before you reschedule. `Mux::consume_timer_entry` calls
`TimeoutContainer::triggered` on entry to a firing, which clears the handle's
deadline, so an early delivery is re-armed instead of memoized away. Without
it the memo reads "nothing changed" while the wheel entry is already gone and
the session is left with no timer: the lost wakeup this series is ordered
around, and the reason the stored deadline had to land first.
- A real expiry clears the core's elapsed deadline. Leaving it in place has
`reschedule` re-arm an instant in the past, which the wheel re-delivers on the
next tick and the session spins. Every branch that keeps the session alive
re-arms explicitly.
Two `debug_assert`s come across from the UDP manager: the strict-advance guard
from `handle_timeout`, and `Mux::debug_assert_timer_coherence`, the analogue of
`check_invariants` (6), which verifies after every reschedule that each handle
is armed iff its core wants a timer, holds exactly the core's instant, and that
no handle outlived its connection.
The clock-source shift: the old `TimeoutContainer::reset()` computed its
deadline from a fresh `Instant::now()` at the call site, whereas
`arm_timeout(now)` computes it from the pass snapshot. A deadline therefore
lands earlier by however long the pass had been running when the re-arm ran —
bounded by one pass, in the same direction as every other snapshot-governed
deadline, required by invariant 20, and dominated by the wheel's own
up-to-99 ms rounding.
One knock-on: the WebSocket upgrade used to destructure the handles out of
`ConnectionH1`; it now takes them out of `Mux.timeouts`, and `sync_timeout`
keeps each handle's `duration()` current through the new
`TimeoutContainer::retune`, because `Pipe` re-arms from it.
Diff accounting, since the shape is misleading. Raw, and reproducible with
`git diff --numstat 0cb1e2a..HEAD -- lib/src/protocol/mux/mod.rs`: +1224/-336,
the file going 2281 -> 3169 lines. Some of that is relocation:
`cancel_timeouts`, `print_state`, `close` and `shutting_down` move above the
`*_inner` bodies, while the `*_inner` bodies themselves keep file order and are
charged nothing. Comparing the two revisions as line multisets rather than as a
diff puts that relocation at 316 lines on each side (908 lines unique to head,
20 unique to base), so ~908 lines are genuinely new: +479 inside `mod tests`
(2 `#[test]` -> 10) and ~429 outside it. Most of this commit is new code, not a
move.
Earlier revisions of this message published a breakdown three times and got it
wrong three times; the multiset method above is stated so the next reader can
re-derive it in one command instead of trusting the prose.
Verified end to end by `test_issue_810_timeout`,
`test_h2_backend_silent_triggers_504_within_back_timeout`,
`test_idle_timeout_no_underflow`, `test_h2_basic_request_response`,
`test_keep_alive`, `test_websocket_upgrade` and
`test_proxy_protocol_websocket_upgrade`.
Documented in `lib/src/protocol/mux/LIFECYCLE.md` §7.7 and invariant 23.
Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
refactor/h2-timer-ownership
branch
from
September 20, 2026 15:33
f68aea8 to
22601f7
Compare
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 20, 2026
517 `file.rs:NNN` anchors across `bin/src/command/LIFECYCLE.md`, `lib/src/protocol/kawa_h1/LIFECYCLE.md`, `lib/src/protocol/mux/LIFECYCLE.md`, `lib/src/protocol/proxy_protocol/LIFECYCLE.md` and `lib/src/protocol/udp/LIFECYCLE.md` were read against the code they point at. 310 did not need a line number and are now symbol anchors; of the 207 that name a specific statement or branch, 171 had to be renumbered and 36 were already right. A line number has no anchor, so it rots the moment anyone edits above it, and nothing resolves it: a mechanical scan for a missing target, a line past EOF or a blank line flagged only 27 of the 517. The two drift patterns measured in issue #1335 account for nearly all of the rest — single-line anchors off by +1 from the `//!` module-doc line added at the top of each source file after the documents were written, and ranges off by tens to thousands of lines from the TigerStyle `debug_assert!` campaign and the growth of `lib/src/protocol/mux/h2.rs`, where the drift reaches +2165. The convention now matches `lib/src/protocol/tcp_preread/LIFECYCLE.md`, which was already written this way and is why it needed no repair. Where the prose names an item the anchor is that item plus its file, with a method qualified `Type::method` so it is greppable; a line or range survives only where the claim is about a statement or a branch inside an item. Bare basenames that were ambiguous repo-wide (`server.rs`, `backends.rs`, `upgrade.rs`) are now repo-root-relative. Each of the five preambles states the convention and the date the surviving numbers were refreshed. No prose claim was rewritten to match code. Four stale claims surfaced on the way — `Server::run`, `upgrade_main`'s file, `ListenerAnswers` / `ClusterAnswers` and the mux "inline removal" list — and are anchored correctly but left for a separate pass. `doc/` is untouched. Rebased onto 95c5f37 (#1369), whose H2 timer-ownership move drifted five more citations in these same documents. Four were caught by the guard landing in #1371 -- `editor.rs:561-621`, `h2.rs:6045-6047` and `manager.rs:555-567` twice, each now resolving to a blank line -- and are re-anchored on `HttpContext::on_request_headers`, the three `ConnectionH2` frame handlers that decrement `active_requests`, and `UdpManager::handle_timeout`. The fifth the guard cannot see, and it is the more instructive one: `shrink_trailing_recycle`'s "single call site at `mod.rs:616`" now lands on `HttpContext::new`, 58 lines short of the real call at `mod.rs:674`. A citation that drifts onto a different non-blank line passes the check -- the checker says so in its own output -- which is why the anchor is now `Mux::create_stream`. The rebase also took the `mux/LIFECYCLE.md` backend-timeout tracker from 95c5f37, whose description is current, but symbolised its two citations rather than keeping either side's numbers: `mod.rs:773` had come to land on unrelated doc prose and `mod.rs:1279` on a `gauge_add!` call. Refs #1335 Signed-off-by: Florentin Dubois <[email protected]>
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.
Refs #1359. C1 is a bug fix, not a refactor — and it falsifies a claim in the issue itself.
Two commits.
c1125650(C1) is standalone and can land alone.29a28bf2(C2+C3) is the ownership move.C1 — the issue says there is no bug here; there is
#1359 states: "there is no standalone bug fix hiding in Q3. That was the most plausible 'actionable
now' candidate across the whole fourteen-question decision set, and it does not pan out."
crate::timer'sduration_to_tickiselapsed_ms.saturating_add(tick_ms / 2) / tick_ms— it roundsto the nearest tick, so an entry armed for
Dis delivered fromD - tick/2onwards.Mux::timeouttook every delivery at face value.
Observable consequence: the wheel's
tick_msis 100 (Builder::default), and the earliness is(D + 50) mod 100— i.e. [0, 99] ms, one full tick minus 1 ms. A 60 sfront_timeoutcould write a408 and close a live session at 59.901 s. After this change it fires at 60 s or just after.
The ≤50 ms half is unconditional rounding; the extra ≤49 ms requires the loop to poll inside
[100t−50, 100t), reachable via another session's earlier entry plus loop latency, or theToken(1)arm. Reachable identically on the backend branch. Not reachable on
shutting_down, which is drivenby
shut_down_sessions()and comparescontext.nowagainstdrain.started_at, never a wheel delivery.TimeoutContainergains a recordeddeadline,set_at()anddeadline();Mux::timeoutre-validatesboth branches through
consume_timer_entry. An early delivery is put back at the same absoluteinstant —
setwould have doubled the configured timeout, and not re-arming at all would be the lostwakeup.
C2+C3 — the ownership move
ConnectionH1/ConnectionH2carrytimeout_duration+timeout_deadlineand exposepoll_timeout();neither file references
crate::timerany more.Muxgainstimeouts: HashMap<Token, TimeoutContainer>plus
reschedule()/sync_timeout(), memoized on handle-vs-core, withretaindropping departed tokens.ready/timeout/shutting_downbecame thin wrappers around*_innerso the reschedule cannot beskipped on an early return.
Observable consequence: none. So the internal invariant is proved instead, by
Mux::debug_assert_timer_coherence— carried fromUdpManager::check_invariants— running after everyreschedule in debug/test/e2e builds, plus the strict-advance guard from
UdpManager::handle_timeout.C3's six
h2.rssites are deleted inside C2 rather than in a third commit: an intermediate tree wherethe adapter owns a container and the core still owns one either arms the wheel twice or not at all,
so neither half would build-and-test green alone. The ordering that matters — C1 standalone — is kept.
The ordering constraint, proved rather than asserted
#1359 argues C2 must not land without C1, because under a memoized
reschedule()plus a wheel that canfire early, re-validation alone converts a spurious fire into a lost wakeup. That argument is now a
test. Mutating the tree to the C2-without-C1 shape — delete
self.deadline = None;fromTimeoutContainer::triggered, and delete the&& container.is_armed() == next.is_some()half of thememo — reddens:
armed=falsewith the core still wanting a timer is the lost wakeup: the wheel entry was consumed,the memo said "nothing changed", nothing re-armed.
The loose end #1359 flagged as unverified: it cannot happen
The issue asks whether a backend can still be in
router.backendswith live work when the shared tailreturns
Continuewith only the frontend container re-armed. Chain:Mux::timeout's backend branch callsbackend.end_stream(stream_id, &mut self.context)unconditionally at the bottom of every iteration, outside the if/else chain.
ConnectionH2::end_streambegins withcontext.unlink_stream(...).ConnectionH1::end_streamdoesnot — it opens with a guarded early return,
if self.stream != Some(stream) { error!(..); return; }.It reaches the unlink only on the matched-stream path.
self.stream = Noneoccurs onlyinside
end_streamafter the unlink, andself.stream = Some(..)only instart_stream, pairedwith
link_stream. So a linked H1 stream always equalsself.streamand always reaches the unlink.Context::unlink_streamis not the only eviction point of that index —remove_backend_streamhas four other direct callers. That is not load-bearing here, since extra eviction only helps.
protect, and a
debug_assert!tripwire catches a violation in every debug/test/e2e build.The issue named only the
delay_close_for_frontend_flushexit; theshould_writeexit has the sameshape and is covered by the same proof. Delivered as the chain in a comment at the re-arm site, a
debug_assert!that fires if the impossible becomes possible, invariant 22 inLIFECYCLE.md, and tworegression tests.
Nine tests, each seen red under a named mutation
Including
a_real_expiry_clears_the_elapsed_deadline_instead_of_re_arming_it, whose failure is abusy-loop guard (
Mux::timeout must strictly advance past a firing on Token(1)), anda_departed_backend_releases_its_wheel_handle(timer handle for Token(1) outlived its connection).The fix is not test-shaped: the production diff shares no literal with any fixture, and the tests observe
public API state.
Found while tracing, unchanged, worth knowing
Router::connect's pool-reuse branch arms no timeout, unlike the fresh-dial branch. Pre-existing andharmless only because the cores re-arm on their first I/O pass — but it is load-bearing for invariant 22.
Out of scope
C4 (the deterministic simulator) is not started and not stubbed; no
sim/target added. It cannot bescoped without the socket split (Q10, #1339), which remains an open architecture decision.
Validation
BUILD=0 CLIPPY=0 TEST=0 FMT=0,test result: ok. 872 passed; 0 failed. Seven e2e tests by exact name,all green, including
test_issue_810_timeoutandtest_h2_backend_silent_triggers_504_within_back_timeout.mod.rs's line count is dominated by theready_inner/timeout_inner/shutting_down_innersplit; themoved bodies are verbatim apart from their signatures and the documented timer hunks, with zero
unexplained hunks. Genuine delta is +851/−63: tests +464, non-test +387.
This branch adds zero new
file.rs:NNNcitations — new references are by symbol — so it does notreintroduce the rot PR #1366 repairs in the same file.