Skip to content

h2 sans-io: the clock, the timers and the flood-detector window (Q2, Q3, Q13) #1337

Closed

Description

@FlorentinDUBOIS

Part of the H2 sans-io extraction decision set. lib/src/protocol/mux/ holds 95 I/O and
ambient-state touchpoints: 26 mechanical, 55 structural, 14 requiring a maintainer decision

(h2.rs 53 / mod.rs 24 / connection.rs 9 / stream.rs 6 / router.rs 3). ConnectionH2<Front: SocketHandler>
carries 54 production socket references in h2.rs alone, and Context<L> holds
pub pool: Weak<RefCell<Pool>>. The structural majority is the signal: this is not a mechanical
extraction.

No design is proposed here and no work is budgeted until the question below is answered. The goal of
the extraction is a deterministic simulator for H2 in the FoundationDB style described in
doc/testing.md; every question below is a place where the current code reaches for I/O, the clock,
the allocator or a random source from inside what would become the pure core.

Question 2 — how the core learns the time

h2.rs:2403 readable / writable / close / graceful_goaway. Does every public entry point take
now: Instant explicitly (extending what collect_timed_out_streams at h2.rs:766 already does), or
does the core hold an injected clock supplied once at construction (extending ConnectionH2::new at
h2.rs:1883)?

Question 3 — who owns timers

h2.rs:1704 pub timeout_container: TimeoutContainer. Does the core keep TimeoutContainer handles
and go on mutating the thread-local TIMER wheel, or stop owning timers entirely and return a
next-deadline Option<Instant> that the embedder arms, with Mux's SessionState impl becoming the
adapter?

Question 13 — the flood detector's clock

h2.rs:957 H2FloodDetector.window_start: Instant. Does the flood detector read the same injected
core clock — so a simulator can advance virtual time, and must then preserve the documented
burst-then-wait half-decay at h2.rs:1136-1182 — or keep an independent real Instant, so that CVE
thresholds can never be time-travelled by a harness?

13 is the sharpest of the three: it is a deliberate tension between testability and a security
control. A simulator that can fast-forward the flood window can also fast-forward it in a way that
hides a regression.

Why these are one decision

2, 3 and 13 are one clock model seen three times. A core that takes now per call but keeps a
thread-local timer wheel is not sans-io; a core with an injected clock whose flood detector reads
the real one is not deterministic. The answer to 2 constrains 3, and 13 is the exception case that
the chosen model must explicitly accept or refuse.

Activity

  1. FlorentinDUBOIS commented on Sep 19, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Q2 and Q13 are answered and implemented; Q3 is not, and this records why

    Landed as #1358, merge 8be51676.

    Q2 — how the core learns the time: cached loop snapshot

    Mux samples Instant::now() once per outer ready() pass and at the top of timeout and shutting_down, stores it on Context.now, and ConnectionH2 mirrors it into its own now field at each public entry. graceful_goaway takes now as a parameter. Twenty-one production real-clock reads in h2.rs became snapshot reads.

    Instant stays the type — no Clock trait, no newtype, no new dependency. The mirror is a field rather than a threaded parameter because handle_ping_frame has no context in scope and the ten flood sites sit across six handlers; a field let check_flood_or_return! gain one $self.now argument with its ten call sites untouched.

    SessionMetrics and TimeoutContainer/TIMER deliberately stay on the real clock: metrics want true elapsed time, and the container is the embedder's timer that the core never reads.

    Behaviour: every deadline armed or evaluated inside a pass is accurate to within that pass, in either direction. An earlier draft of the changeset claimed "bounded lateness, never earliness"; that was wrong. Arm sites run at arbitrary depth into a pass while evaluation sites run at its top — cancel_timed_out_streams is the first thing readable does — so a stamp can be older than the event it records and a deadline can fire up to one pass early as well as late. Before the change both ends read the real clock and the comparison was exact.

    The flood and back-pressure windows are fail-closed within a pass, because now is constant across it and the window therefore decays at most once per pass instead of repeatedly under a burst. Their boundary still carries the same one-pass error as everything else.

    External precedent, checked rather than assumed

    This shape is what nginx does. ngx_current_msec is a volatile ngx_msec_t global assigned in ngx_time_update() from a single ngx_gettimeofday() reading, and ngx_time_update() is called from ngx_epoll_process_events() immediately after epoll_wait(), gated on NGX_UPDATE_TIME || ngx_event_timer_alarm. One cached clock tick per event-loop iteration, no syscall per stream. (Verified directly against nginx master.)

    Worth noting for Q13 specifically: neither nginx nor Pingora runs a time-windowed H2 abuse detector at all. nginx's limits are per-event-loop-iteration and per-connection counters — new_streams reset at the top of the read handler, refused_streams a lifetime budget. Pingora delegates H2 entirely to the h2 crate (pub use h2::server::Builder as H2Options) and adds only a counter, MAX_MALFORMED_STREAMS_PER_CONN = 32, with no rate and no decay. The only duration in that path is h2's reset_stream_duration, measured with std::time::Instant and swept opportunistically from the poll loop. So Sōzu's decaying window is the more elaborate control of the three, which is an argument for testing its decay rather than only its threshold.

    Q13 — the flood detector's clock: inject now

    check_flood(now), new(config, now), saturating_duration_since instead of .elapsed(), and window_start is now private. The documented burst-then-wait half-decay is unchanged, and the proposed progress gate was dropped as vacuous.

    Q3 — timer ownership: still open, and the ordering matters

    The return-deadline shape (a poll_timeout() returning the next deadline, the embedder arming it, as lib/src/protocol/udp/manager.rs already does) is the right end state, but it is gated on an actual commitment to build the simulator — which must also scope the socket split. ConnectionH2 touches its socket at 34 sites, 15 of them socket_wants_write(), so a clock-and-timer refactor without the socket split yields no simulator. The socket half is the larger half.

    The recorded internal ordering is C1 → C2 → C3 → C4: C1 stored deadlines plus re-validation in Mux::timeout; C2 poll_timeout() plus adapter-owned container plus consume-then-reschedule; C3 delete the six h2.rs container sites; C4 the simulator. C2 must not land without C1, and here is the reason, which is worth stating precisely because it is counter-intuitive:

    "Re-validate at the firing site" is necessary but not sufficient. Under a memoized reschedule() plus a wheel that can fire early, re-validation alone converts a spurious fire into a lost wakeup. That exact bug was found and fixed in the UDP shell (#1354): UdpManager::reschedule only emits ArmTimer when next != self.armed_deadline, and the fix was clearing armed_deadline on entry to handle_timeout.

    Today's H2 path cannot have that bug, because TimeoutContainer is duration-based with no memoization — TimeoutContainer::set (lib/src/timer.rs:120-129) unconditionally cancels and re-arms, and every StateResult::Continue exit from Mux::timeout re-arms. So the hazard is a property of the proposed design, not a live defect. That is precisely why the ordering is not negotiable: C2 introduces the memoization that makes C1's re-validation load-bearing.

    This also means there is no standalone bug fix hiding in Q3 — that was the most plausible "actionable now" candidate in the whole decision set, and it does not pan out.

    Keeping this issue open for Q3.

  2. FlorentinDUBOIS commented on Sep 19, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Closing: all three questions are now dispositioned.

    The correction in the comment above stands and is worth repeating, since it is the one thing here that was wrong rather than merely undecided: the changeset initially claimed the new clock model gave "bounded lateness, never earliness". That is false. Arm sites run at arbitrary depth into a pass while evaluation sites run at its top, so a deadline can fire up to one pass early as well as late. Before this change both ends read the real clock and the comparison was exact.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions