Skip to content

refactor(mux-h2): put the H2 core's buffers and HPACK state under a BufferSource - #1496

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-buffer-source
Sep 24, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-buffer-source

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Refs #1336. First slice of the decided answer to Q1 and Q14.

Q1 took option (c) — a caller-implemented BufferSource the core may call mid-request and that may fail — and Q14 answered yes, the HPACK state comes under the same contract. The pairing is the point: answering them apart gives a core that borrows its stream buffers while allocating its header state, which bounds nothing for a simulator.

BufferSource had zero occurrences repo-wide. The decision was recorded 2026-09-21 and never implemented; its own comment deferred it until after the write_streams inversion, which landed in #1479.

The shape

pub trait BufferSource {
    fn checkout(&mut self) -> Option<Checkout>;   // wire octets
    fn scratch(&mut self) -> Option<Vec<u8>>;     // reusable connection-lifetime buffer
}
pub struct PoolBufferSource { pool: Weak<RefCell<Pool>> }

PoolBufferSource::checkout is literally the expression that sat at both call sites; scratch is literally what HpackState::new did. Zero behaviour change by construction — what changes is who may be asked.

Two methods, not more. A ScratchRole/put_scratch pair was sketched and dropped: the scratch buffers are owned by HpackState for the connection's lifetime and leased internally by H2ConverterPass::new/into_buffers, so a return path to the source would be a concept nothing calls.

Context.pool becomes Context.buffers: Box<dyn BufferSource>. HpackState::new becomes fallible as a consequence, so a refused scratch refuses the connection on the path a refused stream-0 buffer already took. https.rs and router.rs both pass &mut *context.buffers, so a session's connection and its streams draw from one source — no two ownership models coexist.

The acceptance criterion had no test, which is the finding

(c) was chosen because it is the only option preserving today's observable behaviour: pool exhaustion mid-request produces REFUSED_STREAM, not a connection error.

Nothing in lib/, e2e/ or sim/ covered that. Every existing REFUSED_STREAM test covers MAX_CONCURRENT_STREAMS; connection.rs's FORCE_NEW_H2_CLIENT_FAILURE is the backend construction path. The behaviour the decision rests on was unverified.

So the test was added before ownership moved: h2_pool_exhaustion_mid_request_refuses_the_stream_not_the_connection, with pool max 3 and max_concurrent_streams 64 so the pool and not the ceiling refuses. It asserts exactly one RST_STREAM(REFUSED_STREAM) on stream 3, no GOAWAY, stream 1 still live and still drivable to completion. The oracle is decoded wire frames only — it never reads the "buffer pool exhausted" log.

That also answers the simulator question posed in the brief: forcing exhaustion deterministically is already cheap today via pool sizing, no allocator injection needed.

Two corrections to the issue

  • The "four scratch Vecs" are three. The HpackState extraction already landed, and priorities_buf left with the scheduler extraction — it is now H2Scheduler::order.
  • BufferSource genuinely did not exist; the mechanism had shipped twice under other names (H2ConverterPass::new/into_buffers, drain_window_updates_into).

Red-then-green, per test

test mutation measured
h2_pool_exhaustion_… refuse_stream_and_discard(RefusedStream) → goaway(InternalError) saw 0 RST_STREAM frames in total / left: 0 right: 1, with >>> GOAWAY: InternalError in the log
a_source_that_refuses_scratch_refuses_the_connection HpackState::new uses .unwrap_or_default() instead of ? fails on its own message
a_pool_source_refuses_once_its_pool_is_exhausted checkout unwraps the happy path panics at the pool expect
…_once_its_pool_is_gone same panics at the buffer expect

After each, h2.rs was restored and compared by md5 against git show origin/main:… — identical, and no git stash used. Shared-literal check between production and test sides: empty.

Boundary left, explicitly

This is the first piece, not half of everything. Named in the commit body, the CHANGELOG and the module doc:

  1. loona_hpack's own tables — no with_capacity exists, so they are under the contract at acquisition and bounded where they already were, by the RFC 7541 §4.2 table-size settings. Growth still reaches the global allocator.
  2. Growth of an already-granted scratch buffer — pre-sizing needs an answer for an over-sized header block, which is a behaviour change.
  3. H2Scheduler::order — holds StreamIds, not octets, so a Vec<u8> method cannot serve it, and it is already bounded by the admission gate. Routing it would add a second element type for no bound gained.
  4. h2_header_reassembly's accumulator — still unbounded, tracked separately.
  5. Context::new still takes Weak<RefCell<Pool>> and boxes it. That is the one place Pool enters; the core beneath never names it. A constructor taking a caller's own Box<dyn BufferSource> is the follow-on that lets the simulator inject a refusing source.

Verification

cargo +nightly fmt --all -- --check                     exit 0
cargo build  --locked --no-default-features --features crypto-ring,…   exit 0, 0 warnings
cargo clippy --all-targets --locked … -- -D warnings    exit 0, 0 warnings
cargo test -p sozu-lib --locked …    ok. 1109 passed; 0 failed     (main measured at 1106; +3 = the three new lib tests)
cargo test -p sozu     --locked …    ok. 113 passed; 0 failed
cargo test -p sozu-e2e --locked … -- --skip tests::fuzz_tests::    ok. 446 passed; 0 failed
RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked
    h2_simulation 11 passed (baseline 10); metrics 6, tcp 6, udp 6
RUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets -- -D warnings   exit 0
check_doc_citations.py --root .      208 citations, 535 test names, 16 pinned, 0 Rust-comment line citations
check_doc_citations.py --base 6172929e   269 compared, 0 drifted; 54 exempt, audited
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked   exit 0

The sozu-lib baseline was measured on a detached origin/main worktree (1106), not derived.

The 54 exempt spans were audited rather than accepted: for each, current content at the new line against base content at the old line — 54 spans point at byte-identical content; 0 mismatched; 0 point at lines with no base counterpart. Pure renumber from a difflib map built only from equal opcodes; 44 citations plus 2 pinned blocks were drifted by the line shifts and all were repaired.

Rustdoc initially failed with exit 101 on four errors — two private-item intra-doc links in the new module and two [Pool] links orphaned by removing the now-unused import. Fixed properly (plain code spans, crate::pool::Pool), not with an #[allow].

No check weakened, no test deleted or ignored, no lint escape, no production dependency added, no async fn in lib/.

@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the refactor/h2-buffer-source branch 2 times, most recently from cc92b86 to aa122ee Compare September 24, 2026 08:34
…ource

Q1 of #1336 takes option (c) and Q14 answers yes, together:
the core keeps a caller-implemented buffer source it may call mid-request
and that may fail, and the HPACK state comes under that same contract
rather than allocating on its own. Answering them apart would leave a core
that borrows its wire buffers while allocating its header state, which
bounds nothing.

`BufferSource` has two calls: `checkout` for wire octets, and `scratch` for
a reusable connection-lifetime buffer. `PoolBufferSource` is the one
implementation, and each of its bodies is the expression that used to sit
at the call site — an upgrade-then-checkout, and a plain `Vec::new()`.
`Context` holds a `Box<dyn BufferSource>` where it held `pool`; `Stream::new`,
`ConnectionH2::new`, `Connection::new_h2_server` / `new_h2_client` and
`HpackState::new` take `&mut dyn BufferSource`. `HpackState::new` is
fallible as a result: a refused scratch buffer refuses the connection on
the path a refused stream-0 buffer already took.

No behaviour changes. Every allocation happens where and when it did. What
changes is who may be asked.

The behaviour this had to preserve — exhaustion mid-request produces
RST_STREAM(REFUSED_STREAM), never a connection error — had no coverage.
It does now, added before the ownership moved: the simulator sizes its pool
to three buffers so the connection's own takes one, the first stream takes
the pair, and the second finds nothing, then requires exactly one refusal
on the stream that could not be served, no GOAWAY, and the admitted stream
still drivable to completion. Replacing the refusal with
goaway(InternalError) reddens it.

Left for its own changeset, deliberately: `loona_hpack` has no
capacity-supplied constructor, so its tables are under the contract at
acquisition and bounded by the RFC 7541 table-size settings, not routed
through the source; growth of an already-granted scratch buffer still
reaches the global allocator; `H2Scheduler`'s pass-order buffer holds
stream ids rather than octets and is already bounded by the
concurrent-stream admission gate; and `h2_header_reassembly`'s accumulator
still has no bound.

Refs #1336

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