Skip to content

h2 sans-io: who owns the buffers and the HPACK state (Q1, Q14) #1336

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 1 — buffer ownership

mod.rs:369 pub pool: Weak<RefCell<Pool>>. Does the sans-io core

  • (a) own buffers allocated at construction from a caller-supplied capacity,
  • (b) borrow caller-provided buffer slices on every entry-point call, or
  • (c) keep a caller-implemented BufferSource trait it may call mid-request and that may fail?

(c) is the only option that preserves today's observable behaviour, where buffer-pool exhaustion
mid-request produces REFUSED_STREAM rather than a connection error. (a) and (b) both require
deciding what replaces that.

Question 14 — HPACK coders and scratch buffers

h2.rs:1691 ConnectionH2::new builds the HPACK encoder/decoder plus four scratch Vecs. Do they
keep allocating from the global allocator independently of the buffer-pool decision, or come under
the same ownership contract?

Bringing them under it requires a capacity-supplied construction that loona_hpack does not
currently expose, so answering "yes" implies either an upstream change, a vendored fork, or a
wrapper that pre-sizes and never grows.

Why these are one decision

14 is a sub-case of 1: "who owns the memory the core uses" has one answer, and HPACK state is memory
the core uses. Answering them separately invites a core that borrows its stream buffers but
allocates its header state, which is the worst of both for a simulator trying to bound allocation.

Activity

  1. FlorentinDUBOIS commented on Sep 21, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    2026-09-21: instructing this issue surfaced a standalone defect, fixed in #1396 — the design question itself is untouched

    Q1/Q14 have not been answered here. What instructing them found is a shippable bug that needed no
    sans-io decision at all, in the same shape as #1359's duration_to_tick rounding and #1341's live
    getpeername(2).

    A refused stream desynchronised the connection's HPACK decoder. Field-compression state is
    scoped to the connection, not the stream (RFC 9113 §4.3). H2State::Discard — entered only from
    refuse_stream_and_discard, reached on a graceful drain, over MAX_CONCURRENT_STREAMS, on buffer
    pool exhaustion, and on a CONTINUATION refusal after flood detection — threw the buffered payload
    away undecoded. Those bytes are a field block the peer's encoder has already applied to its own
    dynamic table, so our decoder fell permanently behind and every later header block on the
    surviving connection resolved the wrong dynamic entry or failed outright. Every one of those
    refusal paths deliberately keeps the connection alive, so the desync persisted. Any peer able to
    trigger a refusal could trigger it.

    Three things that were not obvious and are worth recording here, because they constrain anything
    else that touches this area:

    • A HEADERS payload is not a field block. RFC 9113 §6.2 puts an optional Pad Length byte and
      an optional 5-byte PRIORITY prefix in front of it, and the three new-stream call sites pass the
      whole payload_len. Decoding that raw turns every refused PADDED or PRIORITY HEADERS from a
      legitimate peer into a spurious COMPRESSION_ERROR GOAWAY.
    • Without END_HEADERS there is nothing to keep in sync. handle_header_state already treats the
      following standalone CONTINUATION as PROTOCOL_ERROR, so a refused multi-frame block tears the
      connection down regardless.
    • The CONTINUATION refusal site cannot hold a byte offset into zero.storage. enqueue_rst arms
      WRITABLE, and the inner event loop dispatches readable() then writable() in the same sweep
      (mod.rs:1387 vs :1714), so flush_pending_control_frames — which reuses that buffer as
      RST_STREAM scratch — is guaranteed to clobber it first.

    That last point generalises beyond the fix and was deliberately left alone: zero.storage is write
    scratch for any queued RST_STREAM or WINDOW_UPDATE, so a legitimate multi-frame
    HEADERS+CONTINUATION reassembly could in principle be corrupted by an unrelated stream's pending
    control frame. Pre-existing, independent of Discard, and now being investigated under #1339.

    Q1 and Q14 remain open and uninstructed. The buffer- and HPACK-ownership question this issue
    actually asks still wants its own measured pass — none of the counts in the issue body have been
    re-derived.

  2. FlorentinDUBOIS commented on Sep 21, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Answered by the maintainer on 2026-09-21.

    Decision — Q1 and Q14 together: (c), a caller-implemented BufferSource, with the HPACK state under the same contract

    Q1 takes option (c): the core keeps a caller-implemented BufferSource trait it may call mid-request and that may fail. Q14 answers yes — the HPACK encoder/decoder and the four scratch Vecs built in ConnectionH2::new come under that same ownership contract rather than continuing to allocate independently.

    This is the pairing the issue argued for. Answering them apart would give a core that borrows its stream buffers while allocating its header state, which bounds nothing for a simulator.

    Why (c) rather than (a) or (b)

    (c) is the only option that preserves the observable behaviour we have today: buffer-pool exhaustion mid-request produces REFUSED_STREAM, not a connection error. (a) and (b) both require replacing that with something, and no one has proposed what.

    (b) has a second problem that was not in the issue text and is worth recording, because three bugs this week came out of it. zero.storage is not a per-call buffer. header_block_fragment is a (start, len) window into it that has to stay valid across however many readable() passes a HEADERS+CONTINUATION block takes to arrive. Borrowing caller slices per entry-point call is directly hostile to that lifetime — the buffer has to outlive the call. Any design along those lines would need zero exempted, at which point it is not really (b). The three bugs: #1396, #1397, #1398.

    What Q14 costs, verified rather than assumed

    The issue said loona_hpack exposes no capacity-supplied construction. Checked at the version actually locked, loona-hpack 0.4.3:

    loona-hpack-0.4.3/src/encoder.rs:186:    pub fn new() -> Encoder<'a> {
    loona-hpack-0.4.3/src/decoder.rs:300:    pub fn new() -> Decoder<'a> {
    

    new() and nothing else — no with_capacity on either. So the claim holds and the cost is real: an upstream change, a vendored fork, or a wrapper that pre-sizes and never grows. Of the three the wrapper is the only one that does not take on a dependency we do not control; it should be the default unless someone wants to carry the upstream patch.

    Consequence to carry into the design

    BufferSource is fallible by construction, so every core entry point that can need a buffer mid-request has to have a failure path that produces REFUSED_STREAM. That is what we already do — the requirement is that the trait makes it expressible, not that it introduces it.

    Unblocks the memory half of the extraction. The perimeter half is #1340, now also answered.

  3. FlorentinDUBOIS commented on Sep 21, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Implementation shape for Q1/Q14, and a correction to my own earlier comment

    Measured against origin/main at 7be659544163f0d780f8eb0666a25d992f5f8e23.

    Correction first: BufferSource does not exist in lib/. grep -rn BufferSource lib/ returns
    zero hits. The decision recorded on this issue is a decision, not shipped code — the HPACK coders and
    the four scratch buffers are still four plain fields on ConnectionH2. I have referred to it
    elsewhere in a way that implied otherwise.

    The output contract splits by kind, and that is what retires the zero.storage bug class

    Q10 (#1339) settled that the core goes byte-in / byte-out with caller-supplied buffers. Applying that
    uniformly would regress the write path: write_streams currently gathers IoSlices pointing directly
    into kawa.storage.buffer() and hands them to socket_write_vectored — zero staging copies, with a
    deliberate unsafe lifetime extension and a SAFETY note explaining that kawa.consume() may
    relocate the buffer. A poll_transmit(&mut self, buf: &mut [u8]) on that path would add a copy that
    does not exist today.

    So:

    output shape
    control frames — SETTINGS, PING, GOAWAY, WINDOW_UPDATE, RST_STREAM caller supplies the buffer
    DATA and response bodies already in kawa::Stores borrowed vectored descriptor

    The caller-supplied half is not a new convention. serializer.rs already has exactly that signature —
    pub fn gen_settings<'a>(buf: &'a mut [u8], settings: &H2Settings) -> Result<(&'a mut [u8], usize), GenError>
    — and h2.rs already calls it as kawa.storage.clear(); let buf = kawa.storage.space(); gen_*(buf, …); kawa.storage.fill(size); at three sites. Also verified: .shift() is never called on zero.storage
    in the H2 path, so the contract needs no shift-awareness.

    The consequence that matters for this issue. ConnectionH2::zero serves two roles today — the
    HEADERS+CONTINUATION accumulator, whose header_block_fragment is a (start, len) window that must
    survive several readable() passes, and control-frame write scratch. Three bugs came from that
    collision in one day (#1396, #1397, #1401). If the control scratch is supplied by the caller per
    call
    instead of being a field on the connection, the two roles cannot collide: the core owns only
    the accumulator, and there is nothing left to clear by mistake. The
    header_block_reassembly_in_progress() guard added three times becomes unnecessary rather than
    load-bearing.

    This is why the reassembly extraction and the buffer-role split should land together rather than the
    split being deferred behind it — every intervening changeset touching WINDOW_UPDATE, RST_STREAM or
    GOAWAY serialization is another chance to reintroduce the class through a forgotten guard.

    Related: none of LIFECYCLE.md's 23 invariants names the dual-role hazard. They cover wire-map
    validity, timer ownership and scheduler fairness. Three bugs came from the unnamed one. That invariant
    should be written now, as documentation debt independent of any code change, so reviewers have
    something citable before the reassembly work starts.

    On the HPACK half of Q14

    loona_hpack's dynamic table is opaque — no public accessor, pure in-memory state, no I/O and no
    clock — so it is already sans-io-compatible and wants wrapping rather than forking. The crate API
    already in use (decode_with_cb, set_max_table_size) is exactly what is needed. Owning the
    Decoder<'static>/Encoder<'static> values on a dedicated sub-machine is a value move.

    One constraint discovered while sequencing this, which bears on Q14: H2BlockConverter holds
    &mut self.encoder for the whole per-stream loop in write_streams, so no &mut self method can run
    inside that loop. The existing free function distribute_overhead exists precisely to route around
    it. Any design that wants an extracted sub-machine called from inside the write loop needs that borrow
    scope restructured first.

    First changeset

    Relocating the HPACK-owned state is the first extraction step: a new module owning the two coder
    values and the four scratch buffers, with h2.rs changed at the struct fields, the construction site
    and the two SETTINGS table-size sites. Roughly 400-500 lines across three files, no new test files —
    the existing HPACK unit tests migrate by field rename, and both fuzz targets are untouched because
    they target the crate and the parser directly rather than ConnectionH2's field layout. It should be
    reviewed as a pure move with zero behaviour change.

  4. FlorentinDUBOIS commented on Sep 23, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Status: BufferSource is unimplemented, and the decision on it is deferred until after the write_streams inversion

    Measured at f2082b6e: BufferSource has zero occurrences in lib/. The decision recorded on
    2026-09-21 has not been implemented.

    What has shipped, twice, is the mechanism under other names:

    • H2ConverterPass::new / into_buffers (lib/src/protocol/mux/converter.rs:196-218) moves
      out, lowercase_buf and cookie_buf out of HpackState for the duration of a pass and returns
      them afterwards — a lease, without a trait.
    • drain_window_updates_into(buf: &mut [u8]) -> (usize, usize)
      (lib/src/protocol/mux/h2_flow_control.rs:351) and h2_control_tx.rs:264 take a caller-supplied
      buffer.

    So the open question is not how to design BufferSource but whether the decision still names
    anything the tree does not already have. Deferred deliberately until the write-path inversion lands,
    with the cost of deferring stated plainly: retrofitting a trait over an already-inverted write loop
    is more expensive than adding it before. That is accepted.

    Not deferred, and worth tracking separately: the read side keeps a core-owned Vec at
    lib/src/protocol/mux/h2_header_reassembly.rs:165 that nothing bounds. Whatever happens to
    BufferSource, that allocation still needs an owner and a bound.

  5. FlorentinDUBOIS commented on Sep 24, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Both questions are answered, and the implementation is on main.

    Q1 — buffer ownership. Resolved as option (c), a caller-implemented source the core may call mid-request and that may refuse, in #1496 (58c20711). lib/src/protocol/mux/buffer_source.rs defines the contract:

    pub trait BufferSource {
        fn checkout(&mut self) -> Option<Checkout>;
        fn scratch(&mut self) -> Option<Vec<u8>>;
    }

    The core no longer names Pool; PoolBufferSource is the implementation the proxy itself runs on, and the Weak<RefCell<Pool>> upgrade-then-checkout that Stream::new and ConnectionH2::new each spelled out now lives there unchanged.

    This is what preserves the behaviour the question flagged: a refusal is a transient shortage, not an error, and the obligation is to degrade the smallest unit available — one stream refused with RST_STREAM(REFUSED_STREAM) while the connection carries on, because the streams already running will hand their buffers back. Escalating a shortage to a connection error would convert it into the loss of every in-flight request that would have survived it.

    Q14 — HPACK coders and scratch buffers. They come under the same contract, at acquisition: the codec pair and the three reusable scratch buffers beside them are built inside a fallible HpackState::new, so a shortage refuses the construction rather than allocating behind the core's back.

    Two things are deliberately outside it, which this issue anticipated:

    • loona_hpack's own allocations. The crate exposes Decoder::new / Encoder::new and no capacity-supplied constructor, so its dynamic tables cannot be routed through a source without forking it. They stay bounded where they already were, by the RFC 7541 §4.2 table-size settings; growth after acquisition still reaches the global allocator.
    • Growth of an already-acquired scratch buffer. scratch hands over an empty Vec the core grows and reclaims on its own schedule. Pre-sizing one and refusing to grow it is a behaviour change — it needs an answer for what a header block larger than the reservation does — and was not made there.

    One consequence worth recording for whoever picks up #690: the trait abstracts where buffers come from, not what a buffer is. checkout() returns pool::Checkout, so an io_uring registered-buffer backend would need either to produce a Checkout or an associated buffer type added to the trait. That is a separate, smaller decision and is not blocked by anything here.

    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