Repository navigation
Description
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
BufferSourcetrait 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
FlorentinDUBOIS commentedon Sep 21, 2026
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_tickrounding and #1341's livegetpeername(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 fromrefuse_stream_and_discard, reached on a graceful drain, overMAX_CONCURRENT_STREAMS, on bufferpool 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:
Pad Lengthbyte andan 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 alegitimate peer into a spurious
COMPRESSION_ERRORGOAWAY.handle_header_statealready treats thefollowing standalone CONTINUATION as
PROTOCOL_ERROR, so a refused multi-frame block tears theconnection down regardless.
zero.storage.enqueue_rstarmsWRITABLE, and the inner event loop dispatches
readable()thenwritable()in the same sweep(
mod.rs:1387vs:1714), soflush_pending_control_frames— which reuses that buffer asRST_STREAM scratch — is guaranteed to clobber it first.
That last point generalises beyond the fix and was deliberately left alone:
zero.storageis writescratch 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.
FlorentinDUBOIS commentedon Sep 21, 2026
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 contractQ1 takes option (c): the core keeps a caller-implemented
BufferSourcetrait it may call mid-request and that may fail. Q14 answers yes — the HPACK encoder/decoder and the four scratchVecs built inConnectionH2::newcome 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.storageis not a per-call buffer.header_block_fragmentis a(start, len)window into it that has to stay valid across however manyreadable()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 needzeroexempted, 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_hpackexposes no capacity-supplied construction. Checked at the version actually locked,loona-hpack 0.4.3:new()and nothing else — nowith_capacityon 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
BufferSourceis fallible by construction, so every core entry point that can need a buffer mid-request has to have a failure path that producesREFUSED_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.
FlorentinDUBOIS commentedon Sep 21, 2026
Implementation shape for Q1/Q14, and a correction to my own earlier comment
Measured against
origin/mainat7be659544163f0d780f8eb0666a25d992f5f8e23.Correction first:
BufferSourcedoes not exist inlib/.grep -rn BufferSource lib/returnszero 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 itelsewhere in a way that implied otherwise.
The output contract splits by kind, and that is what retires the
zero.storagebug classQ10 (#1339) settled that the core goes byte-in / byte-out with caller-supplied buffers. Applying that
uniformly would regress the write path:
write_streamscurrently gathersIoSlices pointing directlyinto
kawa.storage.buffer()and hands them tosocket_write_vectored— zero staging copies, with adeliberate
unsafelifetime extension and aSAFETYnote explaining thatkawa.consume()mayrelocate the buffer. A
poll_transmit(&mut self, buf: &mut [u8])on that path would add a copy thatdoes not exist today.
So:
kawa::StoresThe caller-supplied half is not a new convention.
serializer.rsalready has exactly that signature —pub fn gen_settings<'a>(buf: &'a mut [u8], settings: &H2Settings) -> Result<(&'a mut [u8], usize), GenError>— and
h2.rsalready calls it askawa.storage.clear(); let buf = kawa.storage.space(); gen_*(buf, …); kawa.storage.fill(size);at three sites. Also verified:.shift()is never called onzero.storagein the H2 path, so the contract needs no shift-awareness.
The consequence that matters for this issue.
ConnectionH2::zeroserves two roles today — theHEADERS+CONTINUATION accumulator, whose
header_block_fragmentis a(start, len)window that mustsurvive several
readable()passes, and control-frame write scratch. Three bugs came from thatcollision 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 thanload-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 noclock — 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 theDecoder<'static>/Encoder<'static>values on a dedicated sub-machine is a value move.One constraint discovered while sequencing this, which bears on Q14:
H2BlockConverterholds&mut self.encoderfor the whole per-stream loop inwrite_streams, so no&mut selfmethod can runinside that loop. The existing free function
distribute_overheadexists precisely to route aroundit. 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.rschanged at the struct fields, the construction siteand 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 bereviewed as a pure move with zero behaviour change.
FlorentinDUBOIS commentedon Sep 23, 2026
Status:
BufferSourceis unimplemented, and the decision on it is deferred until after thewrite_streamsinversionMeasured at
f2082b6e:BufferSourcehas zero occurrences inlib/. The decision recorded on2026-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) movesout,lowercase_bufandcookie_bufout ofHpackStatefor the duration of a pass and returnsthem afterwards — a lease, without a trait.
drain_window_updates_into(buf: &mut [u8]) -> (usize, usize)(
lib/src/protocol/mux/h2_flow_control.rs:351) andh2_control_tx.rs:264take a caller-suppliedbuffer.
So the open question is not how to design
BufferSourcebut whether the decision still namesanything 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
Vecatlib/src/protocol/mux/h2_header_reassembly.rs:165that nothing bounds. Whatever happens toBufferSource, that allocation still needs an owner and a bound.refactor(mux-h2): take core buffers from a caller-implemented BufferS…
refactor(mux-h2): take core buffers from a caller-implemented BufferS…
refactor(mux-h2): take core buffers from a caller-implemented BufferS…
refactor(mux-h2): take core buffers from a caller-implemented BufferS…
FlorentinDUBOIS commentedon Sep 24, 2026
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.rsdefines the contract:The core no longer names
Pool;PoolBufferSourceis the implementation the proxy itself runs on, and theWeak<RefCell<Pool>>upgrade-then-checkout thatStream::newandConnectionH2::neweach 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 exposesDecoder::new/Encoder::newand 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.scratchhands over an emptyVecthe 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()returnspool::Checkout, so an io_uring registered-buffer backend would need either to produce aCheckoutor an associated buffer type added to the trait. That is a separate, smaller decision and is not blocked by anything here.Closing as resolved.