Skip to content

h2 sans-io: determinism — seeded sources or pinned observable order (Q8, Q9) #1338

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 8 — request identifiers

h2.rs:4835 Ulid::generate(). Is the request Ulid

  • (a) generated by the embedder and passed in, extending Context::create_stream(request_id: Ulid, ..)
    at mod.rs:519 up one level, or
  • (b) produced by an injected seeded id-source alongside the clock?

Note a Ulid embeds a timestamp, so (b) couples this to the clock decision.

Question 9 — hashing and iteration order

h2.rs:766 uses the default RandomState. Does the core

  • (a) take a hasher seed at construction and use a deterministic S, or
  • (b) keep RandomState and impose a total sort at the two confirmed order-leak sites
    (h2.rs:777-786, h2.rs:5898) so that only observable order is pinned?

(b) is cheaper and narrower but relies on the claim that those two sites are the only leaks, which
must be re-derived rather than trusted — an unenumerated third site is exactly the failure mode.

Why these are one decision

Both ask the same thing: does determinism come from seeding the sources, or from pinning what is
observable and letting the interior stay nondeterministic? A mixed answer gives a simulator that
replays identically except when it does not.

Activity

  1. FlorentinDUBOIS commented on Sep 19, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Q9's premise is falsified: there are at least seven order leaks in mux/, not two

    Option (b) is explicitly conditioned on "the claim that those two sites are the only leaks, which must be re-derived rather than trusted". Re-derived against main at 5cb5395e, by enumerating every for loop over a hash-ordered container in lib/src/protocol/mux/ production code. The claim does not hold.

    The two already listed

    1. h2.rs:777 and h2.rs:782 — for (&sid, &t) in last_activity / fc_stalled in collect_timed_out_streams, consumed at h2.rs:4250, where each entry emits an info!, a count! and a queued RST_STREAM(CANCEL). Order of RSTs on the wire.
    2. h2.rs:5933 — for (&stream_id, &global_stream_id) in &self.streams collecting the GOAWAY retry set, consumed at h2.rs:5938. Order of forcefully_terminate_answer and of context.pending_links.push_back — which stream reconnects first.

    Four that were not listed, two of them wire-observable inside ConnectionH2

    1. h2.rs:3654 — for (&stream_id, &increment) in &self.flow_control.pending_window_updates, a HashMap<u32, u32> (h2.rs:1653). Frames are serialized into self.zero in hash order and flushed at h2.rs:3677-3680. Additionally the Err(_) => break at h2.rs:3663-3666 means that when the buffer fills, which WINDOW_UPDATEs are emitted this pass is itself hash-order-dependent. Truncation is unlikely in practice (13 bytes per frame against a pool buffer), but the byte order is unconditional.
    2. h2.rs:6372 — for global_stream_id in self.streams.values() in close(), calling endpoint.end_stream(token, gid, context) for each Linked stream. Backend teardown order.
    3. mod.rs:828 — for (token, client) in self.router.backends.iter_mut() in the ready loop (backends is HashMap<Token, Connection<SessionTcpStream>>, router.rs:111). Which backend is serviced first.
    4. mod.rs:1150 — self.router.backends.values_mut() → try_resume_reading order.
    5. mod.rs:1780 — for (token, client) in &mut self.router.backends → deregister_socket order at close.

    Log-order only, listed for completeness: h2.rs:6279 (trace! per stream in close()), mod.rs:1676 (print_state).

    Checked and confirmed not leaks

    So this is an enumeration rather than a scare. h2.rs:2914-2922 is deliberately pinned — priorities_buf is filled from self.streams.keys() and then sort_by_cached_key(|id| (urgency, *id)), a total order because stream ids are unique. h2.rs:3248 and h2.rs:4039 are sums; h2.rs:6173 is commutative (open_window |=); h2.rs:3290, 3275, 3715 and 4250 iterate Vecs (pending_rst_streams is Vec<(StreamId, H2Error)>, h2.rs:1742); h2.rs:6477 is a find_map with a unique answer; h2.rs:3487 mutates each entry independently, so the outcome set is order-independent.

    What this does to the decision

    Option (b) was attractive as the cheaper, narrower choice: pin two observable sites. It is seven sites, four of which nobody had counted, two of them on the wire — and the enumeration then has to be maintained by hand, forever, against an 8937-line file where a new for … in &some_map is an ordinary thing to write. That is precisely the failure mode this issue names when it says "an unenumerated third site is exactly the failure mode".

    Option (a), a seeded deterministic hasher as a type parameter, is a change that cannot be forgotten by a later contributor. The cost comparison that made (b) look cheaper does not survive the corrected site count.

    Q8, for the record

    Ulid::generate() appears in mux/ production code exactly once, at h2.rs:4870 inside create_stream. Every other occurrence is under #[cfg(test)]. There is no rand/thread_rng/rng anywhere in lib/src/protocol/mux/. So Q8 is cheap either way, and the coupling the issue notes is real: a ULID embeds a 48-bit millisecond timestamp, so option (b) makes the id source a clock source too.

    Still not actionable now

    Sorting these sites changes the emitted byte order from arbitrary-but-current to sorted, and adds a collect-and-sort on the WINDOW_UPDATE drain path. RFC 9113 imposes no ordering on independent WINDOW_UPDATEs or on RSTs for distinct streams, so it is legal — but it buys nothing until there is a simulator to replay against. This comment is to make the decision better-posed, not to reopen it.

  2. FlorentinDUBOIS commented on Sep 21, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Answered by the maintainer on 2026-09-21. Q8 is decided. Q9's direction is decided but its premise is being re-derived first — see below.

    The framing both questions inherit

    The maintainer's direction is to follow the sans-io primitives FoundationDB, and Clever Cloud's own magnetar, already use — on moonpool. That is not a new dependency here: moonpool-sim ^0.8.0 is already a workspace dependency, sim/ already exists, and UDP simulation (moonpool) is already a required CI job. The relevant precedents are magnetar ADR-0004 (pure state machine, zero I/O deps, enforced by an xtask gate) and ADR-0011 (clock injected at every entry).

    So the answer to "seed the sources or pin the observable" is seed the sources. Bit-for-bit reproduction under a seed is the whole point of the moonpool harness, and pinning only what is observable leaves the interior free to diverge.

    Q8 — request identifiers: inject a wall-clock provider and an RNG

    Ulid::generate() at h2.rs:4835 is replaced by construction from two injected providers.

    A correction that shaped this answer. The obvious move was to build the ULID from the now: Instant that #1337 already injects, and it does not work: a ULID's first 48 bits are Unix milliseconds, while Instant is an opaque monotonic point with no epoch and no defined conversion. #1337's decision supplies nothing usable for the timestamp half.

    magnetar hit exactly this and its answer is the shape adopted here. ADR-0011 carries a separate wall_clock: Arc<dyn Fn() -> SystemTime + Send + Sync> provider alongside the now: Instant parameter, precisely for the sites that stamp a wall-clock value. It is worth being clear that this does not reintroduce a host call into the core: the core calls an injected provider, never SystemTime::now() itself, and under simulation the provider is virtualised, so determinism holds.

    The entropy half needs an RNG provider. ADR-0011 lists uuid::Uuid::new_v4() as a known, documented, still-open non-determinism leak — one it says would require a Random provider to close. sozu is in a position to close it rather than inherit it: sim/ already drives the seeded RNG (SimContext::random), so the provider has a real implementation on both sides from day one.

    The alternative considered and rejected was extending Context::create_stream(request_id: Ulid, ..) at mod.rs:519 so the embedder generates the id and passes it in. Cheaper, and it leaves the core with no clock and no RNG at all — but it pushes id generation into every embedder and makes the request id something the core observes rather than owns.

    Q9 — hashing and iteration order: direction decided, premise under re-derivation

    The direction follows Q8: seed the sources, per the framing above. The in-repo precedent is again udp/, and it is more precise than "use a deterministic hasher everywhere":

    udp/manager.rs:104 takes hash_seed: u64 at construction, stores it (:74, "Per-worker hash seed, injected once at construction"), and uses it for the affinity hash at :691-695 — the hash whose value reaches an observer, because it selects a backend. The flow table itself stays a plain HashMap with default RandomState, because it is only ever looked up by key and its order never escapes. Seed what is observable; do not pay for what is not.

    The premise is not yet safe to build on. This issue says the two confirmed order-leak sites are h2.rs:777-786 and h2.rs:5898, and adds that the claim "must be re-derived rather than trusted — an unenumerated third site is exactly the failure mode".

    A first pass says the claim is wrong. h2.rs alone has at least five iterations over self.streams — :744, :2914, :4039, :6173, :6372 — and :2914 is self.priorities_buf.extend(self.streams.keys().copied()), a hash-ordered fill of a buffer that is subsequently consumed in order. Some of the five are genuinely order-insensitive; that has to be judged per site rather than asserted.

    A full enumeration is in progress across lib/src/protocol/mux/, covering every HashMap/HashSet traversal including the ones a grep for .iter() misses — .any(), .find(), .retain(), .fold(), and max_by_key/min_by_key/sort_by_key, which leak on ties whenever the key is not unique. Its result will be posted here, and the concrete Q9 fix list will be built on that rather than on the two-site figure.

    Line numbers in the original text are from 2026-09-18 and have since drifted; the enumeration works against current main.

  3. FlorentinDUBOIS commented on Sep 21, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Q9 re-derivation, as promised in my previous comment. Done against origin/main at f798fdf5, 2026-09-21.

    The "exactly two" claim is wrong: there are seven

    Both originally-claimed sites are real and still present. The line numbers drifted — the issue's h2.rs:5898 maps onto handle_goaway_frame, cross-checked against a16c4813 (2026-09-18) where the identical loop sat at 5933 in a function starting at 5887. But five more genuine leaks were never counted.

    site at f798fdf5 what leaks severity
    mod.rs:1422 Mux::ready router.backends.iter_mut() with break at :1534/:1563 on CloseSession — which backends get their readable()/writable() run this tick before the break highest — hot path, every ready() call
    h2.rs:777-786 collect_timed_out_streams fills out: Vec from two HashMaps in hash order; consumed at h2.rs:4557 to emit RST_STREAM confirmed original
    h2.rs:6267 handle_goaway_frame order streams are queued onto context.pending_links for retry confirmed original
    h2.rs:3959 writable WINDOW_UPDATE wire order, and Err(_) => break on a full buffer makes which updates flush this pass hash-dependent unenumerated, wire-observable
    h2.rs:6489 update_initial_window_size early return true leaves a hash-ordered prefix of streams updated and the rest stale unenumerated, bounded by the immediate GOAWAY
    h2.rs:6613 close diagnostic log-line order only unenumerated, minor
    h2.rs:6704 close trace order certainly; whether backend RST_STREAM wire order also leaks was not traced to a conclusion unenumerated, flagged not asserted

    I verified the three that matter most by reading them directly rather than taking the enumeration's word:

    // mod.rs:1422
    for (token, client) in self.router.backends.iter_mut() {
    // mod.rs:1534 / :1563
        MuxResult::CloseSession => { backend_close = Some(("backend writable", *token)); break; }
    
    // h2.rs:3959
    for (&stream_id, &increment) in &self.flow_control.pending_window_updates {
        ...
        Err(_) => { /* Buffer full — stop here, remaining entries stay in the map */ break; }

    Worth recording why h2.rs:3959 was missed twice: it iterates with for … in &map, not a method call, so a grep for \.(iter|keys|values|drain)\(\) does not see it. My own first pass missed it for exactly that reason.

    What is already defended, and genuinely holds

    h2.rs:3185 fills priorities_buf from streams.keys() in hash order and then sorts at :3190 by (urgency, *id). The stream id is unique, so that is a total order and hash order cannot survive it. Prioriser::apply_incremental_rotation then re-sorts the bucket by a bool key using sort_by_key, which is stable in Rust, over a bucket that already arrives in ascending-id order — so ties keep that order. Both hold. Sums over ready_incremental_by_urgency and streams are commutative and were excluded, as were Vec iterations and the #[cfg(debug_assertions)] invariant checks.

    What this does to the decision

    The issue framed (b) — pin the observable — as "cheaper and narrower". At seven hand-maintained sites, with two found only on the third attempt and one still unresolved, that advantage is gone. A seeded hasher cannot be forgotten; a sort at site number eight can.

    So Q9 follows Q8: seed the sources, per the udp/ precedent of a hash_seed: u64 injected at construction (udp/manager.rs:104).

    With one addition the enumeration makes unavoidable. A seeded hasher buys determinism, not sensible order — same seed, same arbitrary sequence. For the two wire-observable sites that is not sufficient on its own:

    • h2.rs:3959 should emit WINDOW_UPDATE in ascending stream id, and its buffer-full break should defer a deterministic remainder;
    • h2.rs:777-786 / :4557 should reap and emit RST_STREAM in ascending stream id.

    Both want a total sort on the stream id regardless of the hasher decision, because an arbitrary-but-reproducible wire order is still an arbitrary wire order. The seeded hasher is the blanket guarantee; the sorts are correctness at the two places the ordering is visible to a peer.

    mod.rs:1422 is the one I would treat separately and first. Switching router.backends to a BTreeMap<Token, _> fixes every current and future whole-map iteration of it at once — Token is Ord over a usize, and this is not a per-frame hot path relative to the streams map.

    Two things left open, stated rather than papered over

    • h2.rs:6489: whether a write_streams pass can read a stale window before the GOAWAY completes teardown. Needs a targeted test, not an assertion.
    • h2.rs:6704: whether two streams sharing one backend H2 connection can both emit from the same close() pass, which would make that wire order observable too.

    Neither blocks the decision; both should be settled before the corresponding fix is written.

  4. FlorentinDUBOIS commented on Sep 21, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Correcting my previous comment: the count is eleven, not seven. A reconciliation pass against the 2026-09-19 enumeration found four more and refuted one. All at f798fdf5.

    The progression is the point: the issue said 2, a September sweep said 7, this one says 11, and two of the eleven were found only on the third attempt. That is the strongest possible argument for the decision taken — a seeded hasher cannot be forgotten, and site number twelve will be.

    Functionally observable — wire bytes, retry order, or per-tick service order

    site what leaks
    mod.rs:1422, breaks at :1533 / :1562 which backends get readable()/writable() serviced this tick before a CloseSession truncates the pass. Hot path, every Mux::ready. Missed by both the issue and the September sweep
    h2.rs:777-786 → consumed h2.rs:4557 RST_STREAM emission order from the idle/stall reaper — the issue's site 1, unchanged
    h2.rs:3959-3976 WINDOW_UPDATE wire order, plus Err(_) => break making which entries flush this pass hash-dependent
    h2.rs:6267-6301 order streams are queued onto context.pending_links for retry — the issue's site 2 (was 5898), unchanged
    h2.rs:6489-6520 early return true on overflow leaves a hash-ordered prefix updated, rest stale
    h2.rs:6704-6709 close()'s end_stream loop — log order certain, cross-connection wire order not determined

    Diagnostic / log-order only

    h2.rs:6613-6627, mod.rs:1124 (print_state), mod.rs:1141 and mod.rs:1694 (two BACKENDS: {:#?} trace dumps — {:#?} on a HashMap traverses it), mod.rs:1234 (close() teardown, log interleaving only; the gauge_add! calls are commutative so final state is order-independent).

    Refuted

    cancel_timeouts (mod.rs:1096, the September sweep's "mod.rs:828") is not a leak — independent per-element mutation, no accumulator, no early exit, no log. I verified it directly.

    Still defended, re-confirmed

    h2.rs:3185/:3190 sorts by (urgency, *id) with a unique id — total order. Prioriser::apply_incremental_rotation at h2.rs:1625 then uses a stable sort_by_key on a bool over a slice already in ascending-id order, so ties keep that order, exactly as its doc comment claims. Both hold.

    One methodological note worth keeping

    h2.rs:3959 was missed by two separate sweeps because it iterates for (&k, &v) in &map — the bare IntoIterator for &HashMap form, with no method call for a \.(iter|keys|values|drain|retain)\(\) pattern to match. My own first pass missed it for that reason too. Any future sweep of this class must match the borrow form.

    Unchanged

    The decision stands: seed the sources, plus a total sort at the wire-observable sites, and router.backends as a BTreeMap<Token, _> — which alone fixes mod.rs:1422, :1141, :1234 and :1694 at once, since Token is Ord over a usize.

    Three items remain undetermined rather than guessed: the cross-connection RST order at h2.rs:6704, whether a stale window is readable at h2.rs:6489 before teardown, and which of mod.rs:1694 / :1748 the September sweep's "mod.rs:1780" referred to.

  5. FlorentinDUBOIS commented on Sep 21, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Q8: the injection seam already exists in rusty_ulid, no fork needed

    Measured against origin/main at 7be659544163f0d780f8eb0666a25d992f5f8e23.

    The decision recorded here is to inject a wall_clock provider and an RNG, with the core building
    the request ULID from both. The implementation question left open was how, given that Ulid::generate()
    hides both reaches inside a third-party crate.

    It is already published API. rusty_ulid 2.0.1:

    // what we call today
    pub fn generate() -> Self {
        Self::from_timestamp_with_rng(unix_epoch_ms(), &mut rand::rng())
    }
    
    // the seam
    pub fn from_timestamp_with_rng<R>(timestamp: u64, rng: &mut R) -> Self

    So generate() is exactly the composition of the two ambient reaches we are removing, and the
    decomposed form is public. One call site changes — ConnectionH2::create_stream, the only production
    ULID site in all of mux/ — to Ulid::from_timestamp_with_rng(wall_clock.now_millis(), &mut rng).
    No wrapper, no fork, no new dependency.

    Worth restating why this site mattered enough to find: it is invisible to any grep over mux/ for a
    clock reach. Instant::now() and SystemTime::now() both return zero hits for it, because the read
    happens inside the crate. This is the leak shape that a reference sweep structurally cannot find — you
    can only find it by enumerating what each external call does, not by searching for what it looks
    like.

    For the record on the remaining live clock reads: nine survive in mux/, all at construction or in
    diagnostics. The per-pass snapshot discipline holds for everything that drives protocol timeouts and
    flood windows.

    Q9 — the eleven order leaks, and a note on re-deriving the count

    No change to the decision (seed the hasher and total-sort the wire-observable sites). One process
    note, since this issue has now carried three different counts — 2, then 7, then 11.

    The site that was missed twice uses for (&k, &v) in &map. There is no method call, so a grep for
    \.(iter|keys|values|drain)\(\) cannot see it. The general rule that follows: a countable claim about
    leak sites must be re-derived from scratch by whoever restates it, never incremented from a prior
    enumeration, and the pattern used has to cover the bare-reference forms as well as the method-call
    ones.

  6. 1 remaining item

  7. FlorentinDUBOIS commented on Sep 24, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Both questions are answered and the implementations are on `main`.

    Q8 — request identifiers. Resolved as option (b), an injected seeded id-source alongside the clock, in #1497 (`342397dd`). `Context` now carries `now_wall_ms: u64` and `request_id_rng: StdRng` (`lib/src/protocol/mux/mod.rs:569` and `:586`), and the core calls `context.next_request_id()` instead of `Ulid::generate()`. The only `Ulid::generate()` remaining above `mod tests` in `h2.rs` is the comment that records why it is gone; every other occurrence is inside the test module.

    Q9 — pinned observable order. Resolved on measurement in #1506 (`0dddedf2`). `H2StreamTable.streams` is a `BTreeMap<StreamId, GlobalStreamId>` (`lib/src/protocol/mux/h2_stream_table.rs:125`), as are `stream_last_activity_at`, `stream_fc_stalled_since` and `stream_fc_stalled_progress`, so `collect_timed_out` walks each guard in a fixed, reproducible order.

    The measurement inverted this issue's own premise that `O(1)` lookup should win on the hot path: at the stream counts H2 connections actually carry, `BTreeMap` is 1.7-2.3x faster than `HashMap` at n=8 and equal-or-faster at n=100, with the crossover between 100 and 1000. A seeded hasher was below noise in all 20 cells. The module doc in `h2_stream_table.rs` records the corrected justification.

    Closing as resolved.

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