Skip to content

refactor(mux-h2): mint the request ULID from an injected clock and RNG - #1497

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-seeded-determinism
Sep 24, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-seeded-determinism

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Refs #1338. Delivers Q8 only; Q9 is handed back deliberately, with the reason and the next slice named.

Q8 — the request ULID

ConnectionH2::create_stream was the mux's single production Ulid::generate() site. It now calls Context::next_request_id, composing the same ULID from Context::now_wall_ms and Context::request_id_rng.

The seam is published API, no fork: rusty_ulid 2.0.1 defines Ulid::generate() as exactly Ulid::from_timestamp_with_rng(unix_epoch_ms(), &mut rand::rng()), and it resolves the same rand 0.10.2 sozu-lib uses, so our RNG satisfies the bound.

A snapshot, not a provider closure — for the same reason Context::now is one. The mux's discipline is one clock sample per pass read from a field; a boxed provider would let the core reach the host at arbitrary depth into a pass. That is stated in the field doc so it does not read as a silent deviation from the recorded "provider" wording.

StdRng::from_rng(&mut rand::rng()) is not a weakening: it is byte-for-byte the same OS-backed reseeding CSPRNG Ulid::generate() already drew from, so request-id unpredictability is unchanged. (StdRng::from_os_rng does not exist in rand 0.10.2.)

Production dependencies unchanged. sozu-sim gains rand + rusty_ulid in its cfg-gated dev-dependencies, both already in the lock via sozu-lib at the same pin; the lockfile diff is two lines.

The leak table re-derived: 15, not 11 — and leak twelve decides where traffic goes

The issue claimed 2, a September sweep found 7, a reconciliation found 11. Re-derived against current main with a stated criterion (functional = a peer, backend or embedder observes different bytes, routing, or per-tick service order; diagnostic = log order only): 15.

router.rs — Router::connect, least-loaded H2 backend reuse:

for (token, backend) in &self.backends {        // HashMap
    ...
    if stream_count < best_h2_stream_count {    // strict <
        best_h2_stream_count = stream_count;
        reuse_token = Some(*token);
    }

Strict < means the first backend at the minimum wins, so on a stream-count tie hash order decides which backend serves the request. The connecting-backend fallback behaves differently and this description originally had it backwards: reuse_token = Some(*token) carries no break and no already-chosen guard, so every match overwrites and the last one seen wins. Under a total order that is the highest token, not the lowest. Corrected here after it was measured on the follow-up slice. This appears in none of the three prior enumerations, and it is the one with the most user-visible consequence.

The progression 2 → 7 → 11 → 15, with the newest find the most consequential, is the strongest evidence yet for the recorded decision: a seeded source cannot be forgotten, and site sixteen will be.

Functional (8): the above, plus Mux::ready's backends.iter_mut() with a break on CloseSession (hot path), Mux::ready's try_resume_reading order (present in the 7-count, silently dropped from the 11), Mux::close's deregister_socket + shutdown(Write) order — each backend peer sees FIN in a different order, reclassified from the issue's "diagnostic" — Mux::reschedule's wheel-insertion order, handle_goaway_frame's pending_links.push_back order, update_initial_window_size's early return leaving a hash-ordered prefix updated, and ConnectionH2::close's end_stream order.

Two are already fixed on main — and they were the issue's only wire-observable sites: pending_window_updates and the three stream_* maps are now BTreeMap. Both modules carry a doc section arguing BTreeMap over a seeded hasher for a u32-keyed map.

Refuted by reading, not grepping: cancel_timeouts (independent per element), .values().any() (pure probe), H2Scheduler::begin_pass (total-sorts by (urgency, id)), commutative sums, an injective find_map, a pure retain predicate. rst_sent and H2Scheduler::priorities are never iterated — re-verified after #1492 rewrote h2_scheduler.rs.

Why Q9 is not in this changeset

Not the dependency gate — that does not block it. A seeded BuildHasher over DefaultHasher is exactly UdpManager::affinity_hash's existing shape, zero crates.

What blocks it is coverage: all 8 functional leaks sit behind router.backends, StreamState::Linked, client-side GOAWAY, or a 2³¹ window overflow — none reachable from a server-side, no-backend simulator. I could not show one moving, so nothing is claimed fixed.

Next slice, concretely: router.backends → BTreeMap<Token, _> fixes 8 of the 15 at once (Token is Ord over a usize), provable by a Router::connect tie-break unit test with no simulator needed. That leaves H2StreamTable::streams as the only container the seeded-hasher-vs-BTreeMap decision still governs — and h2_flow_control.rs's own module doc on main already argues the BTreeMap side at this scale. Worth a maintainer decision before building the hasher.

Determinism evidence

Today's simulator passes deterministically despite every leak, and the reason is in its own contract: h2_simulation_is_deterministic's trace excludes Ulid-shaped values by design, and the harness attaches no backend and never reaches Linked. A trace that omits a value cannot testify about it.

So a separate test was constructed. With the production line reverted to Ulid::generate(), same seed, two runs:

assertion `left == right` failed: same seed must mint the same request ids in the same order
  left: (13578128866779824828, 4, 4)
 right:  (5463454199563118762, 4, 4)

Same four ids observed, different digests. After: 11 passed. In that same reverted state the pre-existing guard stays green — which is exactly why this is a second test rather than a widening of the old one.

It carries three separable claims so it cannot pass vacuously: same seed → same ids in order; four seeds → ≥2 distinct sequences; every stream-slot occupancy mints its own id, deduped on (slot, id) so a stuck RNG shows as many occupancies collapsing onto few ids. An RNG seeded once and never stepped satisfies the first two.

Test-shaping check: the production diff adds zero numeric or string literals, and the test's two constants appear nowhere in lib/.

Verification, on the rebased tree

cargo +nightly fmt --all -- --check                     exit 0
cargo build  --locked --no-default-features --features crypto-ring,…   exit 0
cargo clippy --all-targets --locked … -- -D warnings    exit 0, 0 diagnostics
cargo test -p sozu-lib --locked …    ok. 1107 passed; 0 failed      (baseline measured at ea228bc1: 1107, unchanged)
cargo test -p sozu     --locked …    ok. 113 passed; 0 failed
cargo test -p sozu-e2e --locked … -- --skip tests::fuzz_tests::   ok. 447 passed; 0 failed
RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked   h2_simulation 11 passed (baseline 10)
RUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets -- -D warnings   exit 0
check_doc_citations.py --root . / --base ea228bc1        exit 0
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked   exit 0

#1492 landed mid-run; rebased onto ea228bc1 and the entire battery, both baselines, the red proof and the citation audit were re-run against the new base.

The citation gate, and the #1447 false positive in the wild

--base was exit 1 with 63 drifted citations on first run — inserting into mod.rs and h2.rs moved 47 cited lines. A clean origin/main passes, so all of it was self-inflicted; renumbered through an exact difflib base→HEAD map.

One survivor was the documented reused-line-number false positive (#1447): a renumber of mod.rs:1357 → 1422 is correct — both hold if self.frontend.readiness().event.is_hup() — but base line 1422 held different code. Applied the gate's own prescribed remedy and converted that citation to a symbol.

70 exempt spans, audited rather than accepted: 70/70 point at a HEAD line byte-identical to the base line it cited, 0 at newly-added code, 0 mismatched. Re-audited from scratch after the rebase — same result.

Docs

LIFECYCLE.md §9 invariant 20 amended: its Instant::now|SystemTime::now|.elapsed() grep structurally cannot see a clock reached through a dependency, and reported the module clean the whole time the reach was live. now and now_wall_ms are now documented as siblings a future sampling point must set together.

doc/testing.md goes four → five named properties, with why the request-id guard is a second test rather than a widening: a digest's exclusions are part of its contract.

No test deleted or newly ignored, no assertion loosened, no #[allow], no -A, no async fn in lib/.

`ConnectionH2::create_stream` was the mux's single production
`Ulid::generate()` site, and `rusty_ulid` 2.0.1 defines that call as
`Ulid::from_timestamp_with_rng(unix_epoch_ms(), &mut rand::rng())` — the
host wall clock and a thread-local OS-seeded RNG, both reached from inside
the dependency. It now calls `Context::next_request_id`, which composes the
same ULID from two sources the embedder owns: `Context::now_wall_ms`, the
wall-clock sibling of `Context::now` refreshed by `Mux` at the same three
sampling points, and `Context::request_id_rng`, seeded once per session in
`Context::new` from `rand::rng()` — the same OS-backed reseeding CSPRNG
`Ulid::generate()` drew from. No production behaviour changes: same ULID
layout, same 48-bit millisecond prefix, same 80-bit random suffix, same
unpredictability.

This is the reach a reference sweep structurally cannot find. `Instant::now`,
`SystemTime::now` and `rand` all return zero hits for that call site because
the read happens one crate away, and LIFECYCLE.md's §9 invariant 20 grep is
written over exactly those three spellings — it reported the module clean
throughout. Invariant 20 now records that a sweep for an ambient reach must
enumerate what each external call does, not only match the spellings a local
reach would use.

`now_wall_ms` is a per-pass snapshot rather than a provider closure for the
same reason `now` is: the mux's discipline is one clock sample per pass read
from a field, and a boxed provider would let the core reach the host at an
arbitrary depth into a pass. The two fields are siblings — a future sampling
point that sets one and not the other lets a request id carry the timestamp
of an older pass.

Guarded by `h2_request_ids_are_a_pure_function_of_the_seed`, which asserts
three separable claims: one seed replayed twice mints the same ids in the
same order, four seeds mint more than one sequence, and every stream slot
occupancy gets its own id (an RNG seeded once and never stepped satisfies
the first two). Seen red — restoring `Ulid::generate()` at the one call site
yields two different digests over the same 4 ids at the same seed, a fresh
pair on every run (13223333605012924217 and 1129667692384430182 on one run).
The pre-existing `h2_simulation_is_deterministic`
stays green across that revert, deliberately: its trace excludes
`Ulid`-shaped values by contract, which is why the leak survived it and why
this is a separate test rather than a widening of the old one.

`sozu-sim` gains `rand` and `rusty_ulid` in its cfg-gated dev-dependencies so
the harness can supply both sources. Neither is a new package in the graph —
`sozu-lib` already depends on both at the same workspace pin and `sozu-sim`
is `publish = false` — so the lockfile change is two lines under `sozu-sim`'s
own dependency list and no production dependency grows.

The bulk of the LIFECYCLE.md and doc/ diff is mechanical: inserting into
`mod.rs` and `h2.rs` moved 47 cited lines, every one renumbered to the line
holding byte-identical text. One became a symbol citation instead, because
this changeset reused its old number for different code and a number cannot
express that.

Refs #1338

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the refactor/h2-seeded-determinism branch from 1cf7c2f to c75aa7a Compare September 24, 2026 12:57
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 342397d into main Sep 24, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the refactor/h2-seeded-determinism branch September 24, 2026 13:56
FlorentinDUBOIS added a commit that referenced this pull request Sep 24, 2026
…e code

lib/src/protocol/mux/LIFECYCLE.md carried three `path:NNN` citations that
resolved to real, non-blank, unrelated lines, which is all any rule in
check_doc_citations.py asks of them:

- §4.2 put the `Context.streams` push at `mod.rs:713-714`. Those are
  `listener.get_sticky_name().to_string()` and
  `listener.get_sozu_id_header().to_string()`, arguments of the
  `HttpContext::new(...)` call that opens `Context::create_stream`. The push is
  `self.streams.push(stream)` at `mod.rs:773`.
- §3.1's `Unlinked` bullet read `h1.rs:995-1052`. `995` is a format string in
  `ConnectionH1::end_stream`'s wrong-stream `error!` guard and `1052` is a
  `debug_assert!` argument; the four `StreamState::Unlinked` assignments the
  range is meant to bracket are `h1.rs:1042-1099`. It was exact at fbc83ed
  (`h1.rs:737-772` against assignments at 737, 745, 767 and 772) and successive
  renumberings walked it off them.
- §7.5's arm-site list read `h2.rs:5387`, which is `log_context!(self)` inside
  an `error!` for an out-of-bounds header block fragment. The HEADERS liveness
  refresh is `self.stream_table.touch_activity(stream_id, self.now)` at
  `h2.rs:5421`. The two commits directly below this one each renumbered that
  citation and neither noticed: #1501 moved it from `h2.rs:5376` to
  `h2.rs:5384`, and #1497 from `h2.rs:5384` to `h2.rs:5387`. Both moves were
  faithful and both landed on `log_context!(self)`: a re-anchor preserves the
  pointer, not the claim.

§7.2 described all three per-stream reap caches as `ConnectionH2` fields
holding a `HashMap`. Both halves are wrong and have been since #1415's
stream-slot-bookkeeping extraction: `stream_last_activity_at`,
`stream_fc_stalled_since` and `stream_fc_stalled_progress` are private
`BTreeMap` fields of `H2StreamTable`, built by `BTreeMap::new()` in
`H2StreamTable::new`, and `ConnectionH2` declares no field of any of those
names. #1415 converted them for the determinism reason its own CHANGELOG entry
records and updated §4.1's wire-map bullet, but left §7.2 on the pre-extraction
shape, so the section now inverts the ordering guarantee the code provides.
Cited by symbol rather than line: that module is being edited under #1338.

CHANGELOG.md's #1484 entry said `shared::drain_tls_close_notify`'s two
uncovered lines were uncovered "because nothing calls that function at all". It
has two production callers, the `Position::Server` arms of `ConnectionH1::close`
and `ConnectionH2::close`. What #1484 measured is that its own six-test fixture
never reaches them. Only that causal clause changed; every count and probe tally
in that historical entry was true as measured and is left as written.

The three citations sat in the drift rule's exemption: it keys on the citation
tuple as it stood in the base revision of the citing document, so a renumbered
span is counted exempt and never compared. Measured at 42ed6ba over the window
they were renumbered in, --base f2082b6 --show reported 133 exempt cited ends
across 91 doc sites; 11 are fenced blocks the pinned-quote rule already compares
verbatim, and reading the remaining 80 against the code they name found 77
correct and these three wrong. --base 42ed6ba --show on this tree exempts 109
more, the spans #1501's and #1497's renumberings re-anchored: 15 pinned fences,
the 4 repaired here, and 90 that anchor on byte-identical text before and after
them. --audit
reports 7 findings on this tree, all 7 the heuristic pairing a prose symbol with
a line eight or more away from it. The three §7.2 declarations were in no rule's
surface at all: every rule resolves a `path:NNN` or a fenced quote, and a
sentence naming a type and a container carries neither. Sweeping LIFECYCLE.md
for the same shape leaves only the three `ConnectionH2.streams` references that

Documentation only: no production code, no test, no dependency and no
Cargo.lock entry changes.

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 24, 2026
Checklist invariant 8 pinned the drain short-circuits of
ConnectionH2::create_stream and ConnectionH2::start_stream to
h2.rs:4882-4889 and h2.rs:6710-6717. Both ranges were correct at 342397d,
and both were still the wrong form: doc/README.md's first citation form
covers prose that names an item, this prose names two methods, and
invariant 7 immediately above already declares itself symbol-cited on
purpose. Invariant 8 contradicted its own neighbour.

Measured rather than argued. A 21-line insertion into
ConnectionH2::initiate_close_notify, the shape #1498's
H1-mirroring debug_assert!s take, moves both ranges onto
self.flush_tls_records() and a bare context argument, and both still
resolve: check_doc_citations.py --root . flags neither. What does catch them
is the drifted-citation rule, which ci.yml supplies a --base for on every
pull request, and what it asks for is a re-anchor: the cost, not the cure.
Re-anchoring this file's HEADERS citation is what #1501 and #1497 each did
faithfully and each landed on the wrong statement. After the conversion the
same insertion leaves LIFECYCLE.md with zero resolver failures instead of
one, and its drifted-citation entries fall 42 to 32.

Ten further anchors convert on the same test, each one where the prose
already names the item and the item resolves to a single site: the six
remove_dead_stream call sites in section 5.4 whose method holds exactly one
such call, H2ConnectionConfig::stream_shrink_ratio, ConnectionH2.now, and
invariant 20's #[cfg(test)] mod tests boundary. Four anchors deliberately
keep a line, because there the prose means one branch inside a method that
calls remove_dead_stream more than once, or one block inside close, which
does several unrelated things: poll_write_target's H2WritePhase::Resume and
H2WritePhase::End arms, handle_window_update_frame's zero-increment path,
and close's backend-stream teardown. Converting those would trade a rotting
pointer for a vague one.

The invariant-8 site and the section 5.4 list now carry a "do not convert it
back" note in invariant 7's style. Document only: no behaviour, no public
API, no test expectation, h2.rs is byte-identical to 342397d, and
doc/h2_mux_internals.md's pinned code blocks are untouched, being fenced
verbatim quotes compared by content.

Verified: python3 .github/scripts/check_doc_citations.py --root . -> exit 0
Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 24, 2026
…e code (#1504)

lib/src/protocol/mux/LIFECYCLE.md carried three `path:NNN` citations that
resolved to real, non-blank, unrelated lines, which is all any rule in
check_doc_citations.py asks of them:

- §4.2 put the `Context.streams` push at `mod.rs:713-714`. Those are
  `listener.get_sticky_name().to_string()` and
  `listener.get_sozu_id_header().to_string()`, arguments of the
  `HttpContext::new(...)` call that opens `Context::create_stream`. The push is
  `self.streams.push(stream)` at `mod.rs:773`.
- §3.1's `Unlinked` bullet read `h1.rs:995-1052`. `995` is a format string in
  `ConnectionH1::end_stream`'s wrong-stream `error!` guard and `1052` is a
  `debug_assert!` argument; the four `StreamState::Unlinked` assignments the
  range is meant to bracket are `h1.rs:1042-1099`. It was exact at fbc83ed
  (`h1.rs:737-772` against assignments at 737, 745, 767 and 772) and successive
  renumberings walked it off them.
- §7.5's arm-site list read `h2.rs:5387`, which is `log_context!(self)` inside
  an `error!` for an out-of-bounds header block fragment. The HEADERS liveness
  refresh is `self.stream_table.touch_activity(stream_id, self.now)` at
  `h2.rs:5421`. The two commits directly below this one each renumbered that
  citation and neither noticed: #1501 moved it from `h2.rs:5376` to
  `h2.rs:5384`, and #1497 from `h2.rs:5384` to `h2.rs:5387`. Both moves were
  faithful and both landed on `log_context!(self)`: a re-anchor preserves the
  pointer, not the claim.

§7.2 described all three per-stream reap caches as `ConnectionH2` fields
holding a `HashMap`. Both halves are wrong and have been since #1415's
stream-slot-bookkeeping extraction: `stream_last_activity_at`,
`stream_fc_stalled_since` and `stream_fc_stalled_progress` are private
`BTreeMap` fields of `H2StreamTable`, built by `BTreeMap::new()` in
`H2StreamTable::new`, and `ConnectionH2` declares no field of any of those
names. #1415 converted them for the determinism reason its own CHANGELOG entry
records and updated §4.1's wire-map bullet, but left §7.2 on the pre-extraction
shape, so the section now inverts the ordering guarantee the code provides.
Cited by symbol rather than line: that module is being edited under #1338.

CHANGELOG.md's #1484 entry said `shared::drain_tls_close_notify`'s two
uncovered lines were uncovered "because nothing calls that function at all". It
has two production callers, the `Position::Server` arms of `ConnectionH1::close`
and `ConnectionH2::close`. What #1484 measured is that its own six-test fixture
never reaches them. Only that causal clause changed; every count and probe tally
in that historical entry was true as measured and is left as written.

The three citations sat in the drift rule's exemption: it keys on the citation
tuple as it stood in the base revision of the citing document, so a renumbered
span is counted exempt and never compared. Measured at 42ed6ba over the window
they were renumbered in, --base f2082b6 --show reported 133 exempt cited ends
across 91 doc sites; 11 are fenced blocks the pinned-quote rule already compares
verbatim, and reading the remaining 80 against the code they name found 77
correct and these three wrong. --base 42ed6ba --show on this tree exempts 109
more, the spans #1501's and #1497's renumberings re-anchored: 15 pinned fences,
the 4 repaired here, and 90 that anchor on byte-identical text before and after
them. --audit
reports 7 findings on this tree, all 7 the heuristic pairing a prose symbol with
a line eight or more away from it. The three §7.2 declarations were in no rule's
surface at all: every rule resolves a `path:NNN` or a fenced quote, and a
sentence naming a type and a container carries neither. Sweeping LIFECYCLE.md
for the same shape leaves only the three `ConnectionH2.streams` references that

Documentation only: no production code, no test, no dependency and no
Cargo.lock entry changes.

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 24, 2026
#1509)

Checklist invariant 8 pinned the drain short-circuits of
ConnectionH2::create_stream and ConnectionH2::start_stream to
h2.rs:4882-4889 and h2.rs:6710-6717. Both ranges were correct at 342397d,
and both were still the wrong form: doc/README.md's first citation form
covers prose that names an item, this prose names two methods, and
invariant 7 immediately above already declares itself symbol-cited on
purpose. Invariant 8 contradicted its own neighbour.

Measured rather than argued. A 21-line insertion into
ConnectionH2::initiate_close_notify, the shape #1498's
H1-mirroring debug_assert!s take, moves both ranges onto
self.flush_tls_records() and a bare context argument, and both still
resolve: check_doc_citations.py --root . flags neither. What does catch them
is the drifted-citation rule, which ci.yml supplies a --base for on every
pull request, and what it asks for is a re-anchor: the cost, not the cure.
Re-anchoring this file's HEADERS citation is what #1501 and #1497 each did
faithfully and each landed on the wrong statement. After the conversion the
same insertion leaves LIFECYCLE.md with zero resolver failures instead of
one, and its drifted-citation entries fall 42 to 32.

Ten further anchors convert on the same test, each one where the prose
already names the item and the item resolves to a single site: the six
remove_dead_stream call sites in section 5.4 whose method holds exactly one
such call, H2ConnectionConfig::stream_shrink_ratio, ConnectionH2.now, and
invariant 20's #[cfg(test)] mod tests boundary. Four anchors deliberately
keep a line, because there the prose means one branch inside a method that
calls remove_dead_stream more than once, or one block inside close, which
does several unrelated things: poll_write_target's H2WritePhase::Resume and
H2WritePhase::End arms, handle_window_update_frame's zero-increment path,
and close's backend-stream teardown. Converting those would trade a rotting
pointer for a vague one.

The invariant-8 site and the section 5.4 list now carry a "do not convert it
back" note in invariant 7's style. Document only: no behaviour, no public
API, no test expectation, h2.rs is byte-identical to 342397d, and
doc/h2_mux_internals.md's pinned code blocks are untouched, being fenced
verbatim quotes compared by content.

Verified: python3 .github/scripts/check_doc_citations.py --root . -> exit 0

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.

1 participant