# HTTP/2 protocol foundations (`http/parser`)

`http/parser` provides Vex-native HTTP/2 protocol ownership: frame ingress,
SETTINGS/GOAWAY, HPACK, flow control, extensible priority, stream state and a
typed application boundary. Fiber uses this owner for cleartext prior-knowledge
HTTP/2 synchronous buffered routes, async buffered routes and bounded response
streams. There is no HTTP/2 client facade, TLS ALPN activation or gRPC facade
in this interface.

Application serving coordinates flow control, HPACK table lifetime,
header-list limits, backpressure, cancellation, deadlines and GOAWAY draining
through one bounded connection/stream state machine. Exact fragmented-preface
promotion installs the connection-local transport; frame helpers cannot bypass
the worker queue. Standalone frame parsing remains useful for protocol tools
and deterministic tests without constructing an application server.

## Present use

The module remains useful for parser tests and protocol tooling. The following
is an illustrative fragment inside a unit-returning function, not a complete
standalone program. Its public
frame-level API is not a substitute for Fiber's application transport:

```vex
import {
    DynamicTable, H2EndpointRole, H2EncodeResult, H2FlowResult,
    H2FieldSectionKind, H2FieldSectionResult, H2InboundFrameResult,
    H2IngressResult,
    H2ReceivePriorityResult, HpackDecodeLimits,
    H2ProtocolConfig, H2ProtocolState, H2ScheduleResult,
    H2ParseResult, H2ProtocolFrameResult, H2SendHeaderResult, HpackBlockResult,
    H2StreamAdmissionResult,
    decodeHeaderBlockLimited, encodePing, parseH2FrameLimited,
    validateH2FieldSection,
} from "http/parser";

// Role and all bounded capacities belong to one owner.
let config = H2ProtocolConfig {
    maxConcurrentStreams: 128,
    maximumChunkBytes: 16384,
    starvationTurns: 64,
    maxHeaderBlockBytes: 65536,
    hpackLimits: HpackDecodeLimits.defaults(),
    maxOutstandingSettings: 16,
    maxOutstandingPings: 16,
};
let! h2 = match H2ProtocolState.new(H2EndpointRole.Client, config) {
    Some(state) => state,
    None => { return; }, // exit the enclosing function on invalid configuration
};
match h2.openLocalStream() {
    H2StreamAdmissionResult.Opened(streamId, index) => { /* odd client ID */ }
    H2StreamAdmissionResult.Blocked(reason) => { /* capacity, drain or exhaustion */ }
    _ => { /* internal/protocol error */ }
}

// Validate metadata against the negotiated peer frame limit without guessing
// error scope from a diagnostic string.
match parseH2FrameLimited(bytes, peerSettings.maxFrameSize) {
    H2ParseResult.Ok(frame) => {
        // `exactPayload` is the complete frame payload retained by transport.
        let result = h2.recvFrame(&frame, exactPayload);
    }
    H2ParseResult.NeedMore(bytesNeeded) => { /* retain partial header */ }
    H2ParseResult.StreamError(rejectedFrame, code, message) => {
        // Retain/discard rejectedFrame.length payload bytes, then RST_STREAM.
    }
    H2ParseResult.ConnectionError(code, message) => { /* GOAWAY + close */ }
    H2ParseResult.Invalid(message) => { /* invalid local configuration */ }
}

// Recommended incremental boundary. The caller retains unconsumed bytes.
match h2.recvBytes(bufferedInput) {
    H2IngressResult.Dispatched(consumed, result) => {
        // Handle borrowed result views before dropping `consumed` bytes.
    }
    H2IngressResult.NeedMore(consumed, additional) => {
        // Drop only `consumed`; retain the rest and read `additional` bytes.
    }
    H2IngressResult.Invalid(reason) => { /* local configuration/contract bug */ }
}

// A complete HPACK block is either wholly decoded or a terminal error.
let! table = DynamicTable.new(peerSettings.headerTableSize as usize);
let limits = HpackDecodeLimits.defaults();
match decodeHeaderBlockLimited(block, &table, &limits) {
    HpackBlockResult.Ok(headers) => {
        // Low-level users must apply the message-context gate themselves.
        let semantic = validateH2FieldSection(&headers, H2FieldSectionKind.Request);
    }
    HpackBlockResult.Error(message) => { /* COMPRESSION_ERROR */ }
}

// Control encoders are capacity-aware and atomic on failure.
match encodePing(&output, "12345678", false) {
    H2EncodeResult.Ok(bytesWritten) => { /* exactly 17 */ }
    H2EncodeResult.Error(message) => { /* output is unchanged */ }
}

// PRIORITY_UPDATE parsing, connection sequencing and scheduler mutation share
// one owner. `priorityFrame` is the already validated frame header.
match h2.recvPriorityUpdateFrame(&priorityFrame, priorityPayload) {
    H2ReceivePriorityResult.Applied(streamId, priority) => { /* committed */ }
    H2ReceivePriorityResult.ConnectionError(code, message) => { /* fail closed */ }
    H2ReceivePriorityResult.Invalid(message) => { /* wrong local API route */ }
}
```

## Typed application boundary

After `H2ProtocolState` has decoded and validated an initial request field
section, `h2ApplicationRequest` moves the existing HPACK-owned strings into the
shared Fiber `Ctx`. It does not synthesize or reparse an HTTP/1 request. Method,
scheme, authority, path, query and ordinary header views remain backed by one
stable owner in the context.

The returned `H2ApplicationBody` connects DATA to the same
`RequestBodyConsumer` contract used by HTTP/1 streaming routes:

```vex
import {
    H2ApplicationBodyResult, H2ApplicationRequestResult,
    h2ApplicationRequest,
} from "http/fiber";

match h2ApplicationRequest(
    fd, streamId, endStream, kind, info, &fields!, config.bodyLimit,
) {
    H2ApplicationRequestResult.Ready(request) => {
        let! request = request;
        let! body = request.body;
        match body.begin(&consumer!) {
            H2ApplicationBodyResult.Complete(0) => { /* header-only request */ }
            H2ApplicationBodyResult.NeedMore(_) => { /* wait for DATA */ }
            H2ApplicationBodyResult.Error(reason) => { /* reset/fail closed */ }
        }

        // `payload` is the padding-free borrowed view returned by
        // H2ProtocolState.recvDataFrame / recvFrame.
        let result = body.feedData(streamId, payload, endStream, &consumer!);
    }
    H2ApplicationRequestResult.Invalid(reason) => { /* local bridge contract */ }
}
```

The shared `DecodedBodyLifecycle` owns admission, byte-limit enforcement,
declared content-length equality, synchronous borrowed-chunk delivery and the
exactly-once finish/cancel transition. HTTP/1 feeds it after transfer decoding;
HTTP/2 feeds it after padding and flow-control validation. A DATA stream-ID
mismatch, body-limit overflow, early END_STREAM or consumer rejection cancels
the lifecycle atomically.

Once a buffered request is complete, `app.dispatchBuffered(&request.ctx!)`
uses the exact frozen radix lookup, route parameters, global middleware and
route middleware used by HTTP/1. It performs no wire I/O. Ordinary buffered
routes complete synchronously. Dynamic lanes return
`ApplicationDispatchResult.TransportRequired` with one exact
`ApplicationTransportRequirement`: `AsyncRequest`, `StreamingRequestBody`,
`StreamingResponse` or `WebSocket`. Impossible combinations such as
`TransportRequired(Complete)` are not representable. Those lanes cannot
accidentally execute without a transport owner, and HTTP/2 does not maintain a
second router or middleware implementation.

The live H2 transport installs `AsyncRequest` as a scheduler task without
lending it the multiplexed descriptor. Each worker owns one bounded MPSC result
lane and non-blocking wake pipe; workers without async routes allocate neither.
Cancellation is registered before spawn. A token containing exact boxed
connection identity is authoritative, while its fd is only a lookup hint, so a
late completion cannot target a reused descriptor or stream. Peer reset,
deadline, connection abort and shutdown cancel the exact task owner; late
results are dropped, and invalid handler results commit a stream-scoped reset.

Streaming responses use a second bounded task-to-worker lane. One exact
connection-generation token, cooperative cancellation handle and one-slot
acknowledgement channel couple every producer chunk to actual HEADERS/DATA wire
progress. Peer reset, deadline and connection abort cancel the producer, close
backpressure and reject stale events. Request-body streaming and WebSocket
lanes remain refused without leaking capacity: the transport removes the
buffered application owner, returns accepted connection credit and commits one
RST_STREAM without entering user code. The full frozen match plus capability
classification measured 51.10 ns with zero allocations in the 2026-08-26 short
M2 Max O3 regression run.

This seam is the static `BufferedApplicationDispatcher` contract rather than a
dependency on Fiber's concrete `App` type. `App` implements it with no virtual
dispatch or allocation; HTTP/2 transport code therefore remains reusable by a
future HTTP/3 owner without creating an application/transport import cycle.

The live prior-knowledge integration uses a connection-local
`H2BufferedStreamSet` for ordinary synchronous routes. Its capacity mirrors the negotiated concurrent-stream
limit; duplicate/full admission changes no state, fragmented bodies remain
bounded by the shared lifecycle, completed responses release their slot, and
RST_STREAM/GOAWAY teardown cancels each remaining consumer once. Header-only
requests allocate no body buffer. Small declared bodies reserve exactly their
size, while large declarations start at 4 KiB and grow only after validated
DATA arrives, avoiding eager per-stream RSS.

`H2ApplicationSession` now connects typed protocol results to that registry.
It moves initial request HEADERS into the shared `App`, completes DATA or
terminal trailers through the same body lifecycle, and cancels the exact owner
on RST_STREAM or connection failure. Accepted DATA records both connection and
stream receive credit; neither ledger entry is cleared until
`flushConnectionCredit` / `flushStreamCredit` successfully encode a complete
WINDOW_UPDATE. Callers must flush stream credit before committing an
END_STREAM response which closes that stream.

Receive validation may correctly retire a malformed stream before transport
has written its required reset. `H2ProtocolState.sendStreamErrorFrame` owns
that separate obligation: failed output capacity leaves it pending and the
first successful 13-byte RST_STREAM commit makes later attempts inert. The
transport never selects reset scope by matching diagnostic strings.

Late DATA on a closed stream is reported as typed `DiscardedData` with the
exact flow-controlled payload size. It is not delivered to the application,
but `H2ApplicationSession` retains the connection-level credit for a later
atomic WINDOW_UPDATE. Stream credit is intentionally absent after retirement,
so one bad stream cannot leak or inflate another stream's window.

`H2ResponseEgress` is the bounded outbound counterpart. It serializes one HPACK
field block at a time, copies each complete HEADERS/CONTINUATION frame into a
caller-reserved queue region, and retains response bodies until scheduled DATA
has also been copied. DATA chunk size is the minimum of queue capacity, the
peer's max-frame-size, the RFC 9218 scheduler turn and connection/stream send
windows. HPACK reports an exact `OutputTooSmall(required)` result without
changing compression state, allowing the connection scratch to begin at 512
bytes and grow only when a real response needs more.

The 2026-08-25 M2 Max O3 gate measures one 64 KiB borrowed DATA admission,
accounting callback and END_STREAM transition at **1.86 ns / 536.8 M
transitions/s**. Its 32.0 TB/s logical byte rate is not a memory-bandwidth
claim: this boundary intentionally performs no payload copy.

Fiber's cleartext prior-knowledge server now drains these typed session,
task-completion, response-stream and egress actions through its existing socket event loop. Mandatory control bytes
are reserved ahead of DATA, buffered work is deferred fairly, accepted credit
returns before terminal responses, and connection deadlines retain GOAWAY until
write completion. Async/stream task cancellation and late-result rejection are
complete; TLS ALPN and two-stage active-stream shutdown remain open. Request ownership, flow-credit accounting,
receive-error reset mapping and bounded response scheduling are complete.

After dispatch, `h2ApplicationResponse(&ctx!)` moves the buffered response body
into one HTTP/2 egress owner. It emits `:status`, canonical content-length and
lowercase validated application fields, filters HTTP/1-only framing fields and
preserves HEAD representation length while suppressing payload DATA. The
returned fields are passed directly to `H2ProtocolState.sendHeaderBlock`; the
HTTP/1 response encoder is never involved.

The codec boundary is fail-closed:

- frame parsing enforces the negotiated frame size and type-specific
  stream/length rules before a caller accepts metadata. Peer failures carry
  typed `StreamError` or `ConnectionError` scope and HTTP/2 error codes; local
  negotiated-limit misuse is a separate `Invalid` result. The transport never
  has to inspect diagnostic text to choose RST_STREAM versus GOAWAY. Unknown
  extension frames are discarded without stream admission or mutation in every
  state, but still pass through connection sequencing and cannot interleave a
  fragmented field block;
- SETTINGS validation is transactional and rejects invalid push, window and
  frame-size values without partially mutating state. Omitted values retain
  their effective value, duplicate known fields apply in wire order, and
  unknown identifiers are ignored. Typed parse errors preserve RFC scope:
  an oversized initial window is `FLOW_CONTROL_ERROR`, while malformed frame
  size/push values retain their specified connection error;
- complete SETTINGS, SETTINGS ACK, PING, WINDOW_UPDATE, RST_STREAM and GOAWAY
  encoders validate buffer capacity and wire metadata before writing; failures
  leave the destination unchanged. GOAWAY encoding also preserves optional
  opaque debug bytes under the 24-bit payload bound;
- GOAWAY parsing is typed and rejects every payload shorter than eight bytes.
  `recvGoAwayFrame` / `sendGoAwayFrame` own exact payload/debug data,
  connection sequencing, the non-increasing boundary, retry-safe stream
  retirement and complete wire encoding. Generic connection/frame APIs cannot
  bypass the owner, and undersized output changes no drain state;
- PING uses exact eight-byte opaque payloads. `sendPingFrame` registers a token
  only after the complete 17-byte frame encodes; the preallocated
  `maxOutstandingPings` set rejects duplicates and overflow without mutation.
  `recvPingFrame` releases only an exact matching ACK, classifies unmatched
  acknowledgements without consuming another probe, and exposes non-ACK bytes
  as a borrowed `AckRequired` payload for `sendPingAckFrame`. Generic frame
  methods cannot bypass this correlation owner;
- HPACK integers distinguish truncation from overflow;
- Huffman literals use the complete RFC 7541 octet table, validate EOS/padding
  and never write beyond caller capacity;
- complete block decoding returns `HpackBlockResult`, never a silent partial
  header list, and applies explicit field-count, decoded-byte, per-string and
  dynamic-table limits;
- table-size updates are accepted only at the beginning of a block and cannot
  exceed the configured SETTINGS maximum. After an acknowledged reduction, the
  peer's next block must begin with a conforming size update; a rejected block
  cannot mutate shared table state;
- outbound `HpackEncoder` state is connection-owned and transactional. Fields
  select `Auto`, `Incremental`, `Without` or `Never` indexing; authorization and
  cookie fields default to never-indexed, and Huffman is emitted only when it
  is shorter. Preflight checks field count/list/string/block/output bounds
  before the first byte, so a rejected block changes neither output nor the
  dynamic table;
- stream windows reject zero/negative consumption and update increments,
  check overflow before arithmetic, represent the full 1–256 priority range,
  and enforce the map's concurrent-stream cap. DATA arriving after the
  peer-facing side closes is discarded with `STREAM_CLOSED` but remains charged
  to connection flow control; non-zero WINDOW_UPDATE racing a closed stream is
  accepted without reviving it;
- `H2ConnectionState` independently sequences received and emitted header
  blocks, rejects orphan/wrong-stream/interleaved CONTINUATION frames, accounts
  both local SETTINGS awaiting peer ACKs and peer SETTINGS awaiting local ACKs,
  and enforces non-increasing GOAWAY last-stream identifiers;
- the live prior-knowledge transport requires the first post-preface peer frame
  to be non-ACK SETTINGS. A request or other frame cannot reach user dispatch
  before this RFC 9113 connection gate succeeds;
- the same connection owner assigns local IDs and admits peer streams under an
  explicit client/server role. It enforces odd/even ownership, monotonic peer
  IDs, concurrent capacity and non-wrapping 31-bit exhaustion before
  materialization. PUSH_PROMISE reserves only its payload's promised ID, never
  its carrier, and peer HEADERS cannot open a locally owned idle stream. Valid
  refused/ignored peer IDs are consumed, while failed
  local admission leaves the next ID unchanged;
- graceful GOAWAY supports the initial maximum boundary followed by a lower
  final boundary. New local work stops after peer GOAWAY, streams above its
  boundary are classified retry-safe, and peer streams above the locally sent
  boundary are ignored without entering the stream map. A steady-state exact
  GOAWAY receive turn with three debug bytes measures **13.20 ns / 75.74 M/s**
  on the 2026-08-25 M2 Max O3 gate;
- `recvDataFrame` validates exact payload length and padding, returns only a
  borrowed application-byte slice, and commits connection/stream receive credit
  with END_STREAM state. `sendDataFrame` symmetrically commits the selected
  scheduler budget, both send windows, frame metadata and stream transition.
  Generic stream methods reject DATA, so flow accounting cannot be split from
  protocol state; local exhaustion reports `Blocked`, while peer violations
  distinguish connection and stream error scope;
- `recvWindowUpdateFrame` / `sendWindowUpdateFrame` own payload parsing or
  encoding, connection sequencing, zero/31-bit validation, scoped overflow,
  credit mutation and scheduler wakeup as one transaction. Generic stream and
  connection methods reject WINDOW_UPDATE. `StreamMap` applies peer and local
  SETTINGS_INITIAL_WINDOW_SIZE deltas to all existing streams transactionally,
  preserves legal negative windows, and gives future streams the correct
  direction-specific defaults;
- WINDOW_UPDATE payload parsing is typed, exact-width and rejects the reserved
  zero increment before arithmetic;
- RST_STREAM payload parsing preserves the complete open 32-bit error-code
  space. `recvRstStreamFrame` / `sendRstStreamFrame` own sequencing,
  idle-stream classification, stream/scheduler retirement and encoding as one
  transaction; generic frame methods reject resets, and a failed 13-byte
  encode changes no active state;
- RFC 9218 dictionaries accept `u=0..7` and boolean `i`, ignore valid unknown or
  unsupported members, and reject malformed RFC 8941 syntax or over-limit
  fields before registration;
- `recvPriorityUpdateFrame` and `sendPriorityUpdateFrame` own complete
  PRIORITY_UPDATE turns: exact bounded Structured Fields parsing or canonical
  encoding, client-only connection sequencing and scheduler mutation commit
  together. Generic connection/stream APIs reject the frame. Request priority
  may arrive before HEADERS, push targets must already be materialized, closed
  targets are discarded, and active plus idle priority state belongs to one
  bounded scheduler registry;
- `H2PriorityScheduler` pre-reserves its registry and performs selection and
  completion without allocation. Lower urgency numbers win, non-incremental
  peers run serially by stream ID, incremental peers rotate, byte chunks are
  capped, and a configurable turn bound prevents starvation. One outstanding
  lease makes structural mutation and completion ordering explicit;
- `H2ProtocolState` is the production-facing composition used by Fiber's live
  prior-knowledge transport. It uses one
  capacity for active streams and early idle priorities, pre-reserves and
  recycles stream slots, and retires stream plus scheduler state atomically on
  reset, natural close, GOAWAY or abort. Stream memory is therefore
  bounded by concurrency rather than total IDs observed over a long-lived
  connection;
- `H2ProtocolState.recvFrame` is the single transport-facing receive switch for
  a complete parsed frame. It routes DATA, headers, SETTINGS, WINDOW_UPDATE,
  reset, GOAWAY, PING and both priority formats to their dedicated owner and
  returns one `H2InboundFrameResult`. Unknown extensions are sequenced then
  ignored, so transport needs no competing frame-type switch;
- `recvBytes` connects fragmented caller-owned buffers to that switch through
  connection-owned discard state. Incomplete valid frames report zero consumed bytes and
  retain a zero-copy payload. Stream-invalid or oversized payloads are safely
  discarded across read boundaries before the next pipelined frame is parsed,
  avoiding attacker-selected frame-sized allocations;
- SETTINGS is not accepted through generic frame methods. Peer deltas become
  effective before `SettingsAckRequired` is returned. Locally sent deltas are
  merged onto the newest pending snapshot and commit from a pre-bounded FIFO
  only when the corresponding ACK arrives. This keeps ordered ACK semantics,
  concurrent-stream admission, directional frame/window limits, header-list
  policy and HPACK table lifetime under one owner;
- `recvHeaderFrame` owns the exact received payload path behind that dispatcher.
  HEADERS admits a new peer stream inside the same transaction; capacity-
  refused and post-GOAWAY ignored blocks are nevertheless decoded fully before
  the typed result is exposed, preserving the connection HPACK table. It validates frame
  length, strips HEADERS/PUSH_PROMISE padding and metadata, reassembles only
  compressed bytes under `maxHeaderBlockBytes`, and decodes at END_HEADERS
  using one connection-lifetime dynamic table. The generic stream-frame method
  rejects header-bearing frames, so HPACK lifetime cannot be bypassed;
- `sendHeaderBlock` owns the symmetric outbound path. Request/response/trailer
  semantics, per-stream message phase, stream transition, connection
  sequencing, peer limits, encoder table and caller bytes commit as one unit.
  `sendStreamFrame` rejects HEADERS, PUSH_PROMISE and CONTINUATION. The result
  carries an allocation-free cursor that maps the contiguous HPACK payload to
  one HEADERS and any required CONTINUATION frames under the effective peer
  frame size. `remainingWireBytes` supports exact all-or-nothing queue
  reservation before cursor drain, preventing frame interleaving;
- `sendPushPromise` owns outbound server push under the same transaction. It
  reserves an even local ID as `ReservedLocal`, scheduler capacity and the
  carrier transition together with HPACK/output commit. Failure restores the
  ID, slot, scheduler, compression table and caller bytes. The returned cursor
  counts the four-byte promised-ID prefix inside the first frame and uses
  CONTINUATION for the remainder without copying;
- a stream transition error is retained until the complete compressed block has
  advanced HPACK state. This keeps later streams synchronized. A malformed
  compressed block returns `COMPRESSION_ERROR` and makes the owner terminal;
- after successful HPACK decode, fields cross an RFC 9113 semantic gate before
  application delivery. It enforces lowercase token names, rejects CR/LF/NUL,
  invalid control bytes and edge whitespace, forbids connection-specific
  fields, limits `te` to request `trailers`, and validates pseudo-header
  context/order/uniqueness plus request, response, CONNECT and trailer shape;
- message-phase state distinguishes initial requests, informational responses,
  final responses and terminal trailers. Malformed messages retire their
  stream with `PROTOCOL_ERROR` after HPACK synchronization; they do not become
  connection-level compression failures;
- valid server PUSH_PROMISE received by a client atomically reserves the
  promised peer ID as `ReservedRemote` under the same parity, monotonicity and
  active-capacity checks. Its field section must be a complete GET/HEAD request;
  unsafe/non-cacheable methods retire the consumed promised stream. Forbidden
  client push and zero/reused IDs fail closed;
- writable selection is a byte lease capped by scheduler policy, connection
  credit and stream credit. Flow-blocked work stays pending; WINDOW_UPDATE
  makes it schedulable again without requiring the application to republish
  readiness. Connection-only entry points reject stream frames, preventing
  callers from bypassing the unified stream state machine;
- RFC 7540 dependency/weight fields are deprecated by RFC 9113 and retained as
  explicitly named `legacy*` metadata for old wire compatibility only.
  `recvLegacyPriorityFrame` owns the exact five-byte payload, accepts idle and
  closed IDs without materializing them, preserves stream-scoped size and
  self-dependency errors, and still enforces the connection CONTINUATION lock.
  `sendLegacyPriorityFrame` is the symmetric explicit compatibility encoder.
  Neither path affects the RFC 9218 scheduler. A legacy priority prefix inside
  HEADERS uses the same codec; self-dependency becomes a delayed stream error
  only after the HPACK block has advanced;

Example transport-owner scheduling (an integration fragment). Here `data` is
this selected stream's pending byte view, `bytesToWrite: u32` describes its
available prefix, and `peerMaxFrameSize` is the current negotiated frame limit.
The transport must reserve queue capacity before committing protocol state:

```vex
// Admission has already registered the stream in the bounded priority domain.
h2.markReady(streamId);
match h2.nextWritable(Math.min(maximumWriteBytes, peerMaxFrameSize)) {
    H2ScheduleResult.Selected(id, budget) => {
        let payloadBytes = Math.min(budget, bytesToWrite);
        let finalChunk = endStream && payloadBytes == bytesToWrite;
        // The transport reserves exactly 9 + payloadBytes writable queue bytes
        // here. If reservation fails, release the lease while keeping work ready.
        // This example sends unpadded DATA, so payloadBytes == flowBytes.
        let! stillReady = true;
        match h2.sendDataFrame(id, payloadBytes, 0 as u8, finalChunk) {
            H2SendDataResult.Ready(frame, dataBytes, trailingPadding) => {
                emitData(frame, data, dataBytes, trailingPadding);
                // Advance the application's pending prefix by dataBytes.
                stillReady = hasMoreData || dataBytes < bytesToWrite;
            }
            H2SendDataResult.Blocked => { /* retain all pending application data */ }
            _ => { /* handle the local/protocol error; do not emit a frame */ }
        }
        let _ = h2.completeWritable(id, stillReady);
    }
    H2ScheduleResult.FlowBlocked => { /* wait for connection/stream credit */ }
    _ => { /* empty, busy, or invalid budget */ }
}
```

`emitData` is transport pseudocode, not an exported helper. Select `data` and
its completion flags for the returned `id`, not for an unrelated ready stream.
When adding padding, the charged payload is `dataBytes + 1 + paddingBytes`
(the extra byte is absent when padding is zero). That whole amount must fit
both the selected remaining budget and the peer frame limit. Reserve
`9 + flowBytes` queue bytes before `sendDataFrame`; the returned `Ready` commits
windows, scheduler budget and stream state, so a subsequent queue-capacity
failure cannot be treated as a harmless retry.

Inbound DATA uses the symmetric exact-payload boundary:

```vex
match h2.recvDataFrame(&frame, exactPayload) {
    H2ReceiveDataResult.Data(id, applicationBytes, endStream, flowBytes) => {
        consumeBorrowed(id, applicationBytes, endStream);
        // Replenish credit only after the consumer releases flowBytes.
    }
    H2ReceiveDataResult.Discarded(id, code, reason, flowBytes) => {
        // Do not deliver these bytes to the application.
        // Retain flowBytes as CONNECTION-only pending receive credit;
        // replenish it through stream-0 WINDOW_UPDATE after discarding input.
        // Queue the stream-scoped error/reset; never replenish this stream.
    }
    H2ReceiveDataResult.StreamError(id, code, reason) => { /* scoped error/reset */ }
    H2ReceiveDataResult.ConnectionError(code, reason) => { /* GOAWAY */ }
    H2ReceiveDataResult.Invalid(reason) => { /* local API contract violation */ }
}
```

`Discarded` is distinct from an uncharged rejection: the connection receive
window has already consumed `flowBytes`, even though the stream is rejected.
Dropping that credit stalls unrelated streams; returning stream credit would
revive accounting for a retired stream. `H2ApplicationSession` retains the
connection-only obligation for its atomic credit flush.

Application cancellation uses the complete wire-owned reset API:

```vex
match h2.sendRstStreamFrame(streamId, ERR_CANCEL, &reservedOutput!) {
    H2SendResetResult.Encoded(id, code, 13) => {
        // Frame bytes, stream retirement and scheduler revocation committed.
    }
    H2SendResetResult.Closed(id) => {
        // Locally reserved idle stream: no wire stream, no reset frame.
    }
    H2SendResetResult.IdlePriorityRemoved(id) => {
        // Early priority state retired without inventing a stream.
    }
    H2SendResetResult.Invalid(reason) => {
        // State is unchanged; reserve output capacity and retry if appropriate.
    }
    _ => { /* already closed, not found, or sequencing error */ }
}
```

Inbound reset payloads cross the symmetric `recvRstStreamFrame` boundary. A
valid reset exposes its exact peer error code after retiring stream and
scheduler state; RST_STREAM on an idle stream is connection-terminal.

PING liveness uses the same transaction boundary:

```vex
match h2.sendPingFrame("12345678", &reservedOutput!) {
    H2SendPingResult.Encoded(17) => { /* one bounded token is outstanding */ }
    H2SendPingResult.Duplicate => { /* choose a distinct probe token */ }
    H2SendPingResult.Full => { /* wait for an ACK or timeout policy */ }
    _ => { /* no token was consumed */ }
}

match h2.recvPingFrame(&frame, exactPayload) {
    H2ReceivePingResult.AckRequired(payload) => {
        let _ = h2.sendPingAckFrame(payload, &reservedOutput!);
    }
    H2ReceivePingResult.Acknowledged(payload) => { /* liveness confirmed */ }
    H2ReceivePingResult.UnmatchedAcknowledgement(_) => { /* ignore/report */ }
    _ => { /* malformed or sequencing failure */ }
}
```

Received frames use the unified owner rather than transport-side routing or an
independent HPACK decoder:

```vex
match h2.recvFrame(&frame, exactPayload) {
    H2InboundFrameResult.HeaderBlockPending(streamId) => {
        // Only CONTINUATION for this stream may follow.
    }
    H2InboundFrameResult.Headers(streamId, promisedId, endStream, kind, info, headers) => {
        // promisedId is zero for HEADERS and non-zero for PUSH_PROMISE.
        // Admission, HPACK and HTTP/2 message semantics are validated here.
        // kind distinguishes request/response/trailers/push without a second
        // stream-state interpretation; info retains pseudo-header positions.
        // endStream tells the application whether a DATA body can follow.
        dispatch(headers);
    }
    H2InboundFrameResult.StreamError(id, code, reason) => {
        // Emit RST_STREAM; HPACK state is already synchronized.
    }
    H2InboundFrameResult.ConnectionError(code, reason) => {
        // Emit GOAWAY and close; the owner is terminal for compression errors.
    }
    H2InboundFrameResult.SettingsAckRequired => { /* emit SETTINGS ACK */ }
    H2InboundFrameResult.PingAckRequired(payload) => { /* echo ACK */ }
    H2InboundFrameResult.Ignored(_, _) => { /* compatible extension/ignored block */ }
    _ => { /* deliver other typed control/data results */ }
}
```

The validated `info` also carries the canonical `contentLength` (`-1` when
absent) and exact pseudo-header indexes. The connection owner compares that
declaration with application DATA bytes in both directions. Frame padding is
charged to flow-control windows but excluded from message content. Conflicting
or overflowing declarations, trailer redefinition, early END_STREAM and excess
DATA are stream-scoped protocol failures; a rejected local send changes no
window, scheduler lease, HPACK state or stream phase.

SETTINGS transport integration uses the dedicated owner methods:

```vex
match h2.recvSettingsFrame(&frame, exactPayload) {
    H2ProtocolFrameResult.SettingsAckRequired => {
        // Peer values are already effective; emit one SETTINGS ACK.
    }
    H2ProtocolFrameResult.ConnectionError(code, reason) => {
        // Emit GOAWAY and close.
    }
    _ => { /* ACK committed, or caller contract violation */ }
}

// Record a locally emitted SETTINGS frame before handing bytes to transport.
// Its snapshot becomes effective only after the matching peer ACK.
let result = h2.sendSettingsFrame(&outboundFrame, outboundPayload);
```

Outbound application fields must also enter through the owner:

```vex
let! output = VexStr.fromRaw(storage.asPtr() as Ptr<Opaque>, storage.len());
match h2.sendHeaderBlock(streamId, endStream, &headers, &output!) {
    H2SendHeaderResult.Encoded(id, payloadBytes, frames) => {
        let! cursor = frames;
        // Each fragment slices output without copying the HPACK block.
        while let Some(fragment) = cursor.next() {
            emitFrame(fragment.frame,
                output[fragment.payloadOffset ..
                       fragment.payloadOffset + fragment.payloadBytes]);
        }
    }
    H2SendHeaderResult.StreamError(id, code, reason) => { /* reset stream */ }
    H2SendHeaderResult.ConnectionError(code, reason) => { /* close */ }
    H2SendHeaderResult.Invalid(reason) => { /* caller/policy failure */ }
}

match h2.sendPushPromise(carrierStreamId, &promisedRequest, &output!) {
    H2SendPushResult.Promised(carrier, promised, payloadBytes, frames) => {
        let! cursor = frames;
        // Reserve cursor.remainingWireBytes() atomically before this loop.
        while let Some(fragment) = cursor.next() {
            if fragment.promisedStreamId != 0 {
                emitPushFrame(fragment.frame, fragment.promisedStreamId,
                    output[fragment.payloadOffset ..
                           fragment.payloadOffset + fragment.payloadBytes]);
            } else {
                emitFrame(fragment.frame,
                    output[fragment.payloadOffset ..
                           fragment.payloadOffset + fragment.payloadBytes]);
            }
        }
    }
    _ => { /* no promised ID, slot, HPACK, or bytes leaked on failure */ }
}
```

RFC 9113 defaults `MAX_CONCURRENT_STREAMS` and `MAX_HEADER_LIST_SIZE` to no
wire-level limit. That does not make the implementation unbounded:
`H2ProtocolConfig.maxConcurrentStreams`, `maxHeaderBlockBytes`, `hpackLimits`
and `maxOutstandingSettings` are independent local resource ceilings.
The connection configuration requires `hpackLimits.maxDynamicTableSize >= 4096`
so the decoder can safely honor the pre-ACK RFC default before any advertised
reduction becomes effective.

The following are historical component measurements reported for an M2 Max
with `-O3` in August 2026. They have not been revalidated for this page's
current checkout or compiler and do not establish live-server throughput or
production readiness. Reproduce them with recorded fixtures and a pinned build
before using them for comparison.

The 2026-08-24 M2 Max O3 component baseline measured priority-field parsing at
30.64 ns (32.6 M/s) and a select+complete turn across 32 ready streams at
72.77 ns (13.7 M/s). The unified owner performed the same turn, including
stream lookup and connection/stream flow checks, in 77.71 ns (12.87 M/s), only
about 4.94 ns above the raw policy primitive. These figures are not live HTTP
throughput measurements.
After the semantic gate, the 2026-08-24 M2 Max O3 baseline measures HPACK decode
plus validation of a canonical three-field request at 126.19 ns (7.92 M/s).
A complete connection-owner lifecycle turn—monotonic admission, request decode
and validation, response-side close, scheduler retirement and slot reuse—takes
171.54 ns (5.83 M streams/s). The earlier 51.64 ns single-field probe was
retired because it was not a complete valid HTTP/2 request and omitted stream
retirement.
Steady-state encoding of a canonical four-field request into four indexed bytes
measures 40.06 ns (24.97 M blocks/s). The common all-indexed path performs a
stack preflight and direct RFC static-table dispatch; literal and table-update
blocks keep the full virtual-table transaction.
A full reusable server-push ownership cycle—promise reservation and encoding,
terminal response, scheduler release and slot recycle—measures 172.94 ns
(5.78 M cycles/s).
The complete received-reset lifecycle—monotonic admission, HPACK/field
validation, exact RST_STREAM decode, stream/scheduler retirement and bounded
slot reuse—measures **175.27 ns / 5.71 M streams/s**.
A complete reusable PING send/ACK correlation turn measures **14.45 ns / 69.20
M round trips/s**; it includes frame encoding, bounded token registration,
exact ACK matching and token release.
The 2026-08-25 complete transport-facing PRIORITY_UPDATE receive turn—unified
dispatch, bounded Structured Fields parse, direction/connection sequencing,
registry lookup and in-place scheduler update—measures **29.43 ns / 33.97 M
updates/s**.
The corresponding production-shaped `recvBytes` turn—including the nine-byte
frame-header parse and exact payload slice—measures **42.55 ns / 23.50 M
frames/s**.
The 2026-08-25 exact DATA-owner baseline measures a complete scheduled outbound
turn—including two parsed WINDOW_UPDATE frames, flow/state commit, scheduler
rotation and wakeup—at 32.99 ns / 30.31 M turns/s. Inbound exact-payload
validation, state/flow commit and two atomically encoded credit updates measure
22.53 ns / 44.38 M turns/s. These use a
16-byte payload to emphasize control-plane cost, not bandwidth throughput.

## Remaining integration and qualification

The cleartext prior-knowledge path is present in the development event loop;
TLS ALPN integration remains open. Before relying on it, investigate the
failed local async loopback run and validate reset, cancellation and write
completion on the target. Cross-implementation interoperability, adversarial
conformance and sustained backpressure tests also remain qualification gates.

HTTP/3/QUIC follows only after these contracts exist; it will use the same
application/router/middleware interface rather than a parallel framework.

## Detailed implementation notes from the overview

The development implementation includes exact fragmented-preface selection,
non-blocking worker queues, negotiated and
type-specific frame checks with typed RFC stream/connection error scope,
separate local-configuration failures, and extension-safe unknown-frame
discard that still enforces field-block exclusivity. Transactional SETTINGS,
typed whole-block HPACK,
complete Huffman decoding, explicit header/table limits, checked stream
windows, atomic capacity-aware control encoders and connection-owned
CONTINUATION/SETTINGS-ACK/GOAWAY sequencing. DATA ownership is transactional
across exact payload shape, checked padding, borrowed application bytes,
scheduler budget, connection/stream windows and END_STREAM state. Late DATA
is discarded without losing connection credit, while closed-stream
WINDOW_UPDATE races are accepted without reviving state;
generic frame APIs cannot bypass it. WINDOW_UPDATE has the same exact-frame
ownership across parsing/encoding, sequencing, scoped overflow, credit and
scheduler wakeup. RST_STREAM likewise owns exact payload/error decoding,
idle-stream scope, sequencing, retirement and complete encoding; failed
output commits nothing. SETTINGS window deltas are overflow-safe and
directional. Explicit endpoint roles enforce
local/peer stream parity, monotonic peer IDs, capacity, non-wrapping ID
exhaustion and graceful GOAWAY drain/retry boundaries before materialization.
Dedicated GOAWAY receive/send methods bind exact payload/debug bytes,
sequencing, the non-increasing boundary, retry-safe retirement and complete
encoding; failed output cannot begin draining.
PING uses exact opaque payloads and a preallocated bounded correlation set;
duplicate/full/failed sends consume no token, matched ACKs release one, and
unmatched ACKs cannot corrupt another liveness probe.
RFC 9218 priority fields and PRIORITY_UPDATE are bounded and typed. Dedicated
receive/send methods atomically bind exact parsing or encoding, client-only
sequencing and scheduler mutation; generic frame APIs cannot bypass them.
A pre-reserved urgency/incremental
scheduler providing serial/round-robin service, bounded starvation and no
allocation during selection/completion. Deprecated RFC 7540 PRIORITY is
isolated behind compatibility-only exact-frame methods: it accepts any
stream state without materializing unknown IDs, preserves error scope and
never enters the RFC 9218 scheduler. `H2ProtocolState` is the recommended
integration boundary: it atomically owns admission, recyclable stream slots,
active plus idle priority capacity, flow-aware writable leases,
reset, GOAWAY retirement and abort. It also owns bounded fragmented
header reassembly and the connection-lifetime HPACK table; stream errors do
not desynchronize later streams, while compression errors fail the
connection closed. Successfully decompressed fields then cross a strict
request/response/CONNECT/push/trailer semantic gate; invalid names/values,
connection fields and pseudo-header/message-phase violations retire only the
malformed stream before application delivery. It also owns SETTINGS lifecycle: peer changes apply
immediately, local snapshots commit in FIFO ACK order, initial-window deltas
are transactional, and acknowledged HPACK table reductions are enforced at
the next field-block boundary. Wire-level unlimited defaults remain separate
from configured local memory/concurrency ceilings.
`H2ProtocolState.recvFrame` is the single complete-frame receive boundary:
known types reach their dedicated transaction, unknown extensions remain
connection-sequenced, and HEADERS performs peer admission internally.
Refused/GOAWAY-ignored field blocks still advance HPACK before their typed
result is returned, so transport cannot split admission from compression.
Completed field results retain validated message kind, pseudo-header
positions and END_STREAM. Content-Length lists and DATA content totals are
owned per stream in both directions; padding consumes flow credit but never
content length, while mismatches fail without contaminating the connection.
connection-owned `recvBytes` handles fragmented caller-owned input with
exact consumed-prefix reporting. Valid payloads remain zero-copy; rejected
stream payloads are discarded incrementally without frame-sized allocation
before parsing resumes at the next pipelined frame.
Outbound field sections use the same owner: semantic phase,
stream/connection transition, negotiated limits, HPACK table and output
commit atomically. Indexing policy is explicit, credentials/cookies default
to never-indexed, Huffman is used only when smaller, and generic frame APIs
reject header-bearing sends. Successful blocks return an allocation-free
cursor that maps the contiguous payload to negotiated-size HEADERS and
CONTINUATION frames without copying. Server `sendPushPromise` uses the same
transaction for the carrier, even promised ID, `ReservedLocal` slot,
scheduler capacity and HPACK bytes; its cursor includes the four-byte
promised-ID prefix in exact frame/queue accounting.
Fiber contains no dormant H2 side transport; prior knowledge installs the
same cancellable non-blocking owner used by the protocol/application tests.
Async request handlers publish through a bounded worker-local completion
lane while the event loop retains the socket. Exact connection-generation
identity rejects late results after reset, deadline, shutdown or fd reuse.
