Skip to content

perf(provider): frame SSE bodies per chunk with one allocation per event (H19) - #39

Merged
lg2m merged 6 commits into
mainfrom
perf/h19-sse-framing
Sep 14, 2026
Merged

lg2m merged 6 commits into
mainfrom
perf/h19-sse-framing

Conversation

@lg2m

@lg2m lg2m commented Sep 14, 2026

Copy link
Copy Markdown
Collaborator

H19: SSE bodies framed per chunk, one allocation per event; Anthropic parses once (D10)

Spec: docs/plans/speed-first-extensible-agent-harness.md § D10 (conditional) · ADR: docs/adr/0025-sse-chunk-framing.md

Phase 6 slice. No PROTOCOL_VERSION or store-schema bump; no wire bytes change.

The conditional

D10 said: measure the decoder first; implement only if framing is a material share of the decode path; a documented no-change decision is acceptable. The sse_decode bench (first commit, a2c6824) measured realistic text-delta streams at 64 KiB / 512 KiB / 1 MiB delivered in 16 KiB chunks, under a counting allocator, split into framing alone vs framing + adapter parse:

  • Framing was 55–72 % of the decode path, ~11 allocations per event (a Vec per line, plus name/data strings), ~5.4 allocated bytes per body byte, 2.9–3.7 ms per MiB.

That's on the time-to-first-token / streaming path for every concurrent agent, so the conditional resolved to implement.

What changed

  • qq-provider::sse::SseDecoder — push_into(&[u8], &mut Vec<SseEvent>) scans a chunk for line ends once and parses each complete line in place from the chunk. Only a line a chunk boundary splits is buffered (and that buffer is reused). An event's data: lines accumulate in one buffer that is moved into the dispatched event, so an event costs one allocation. Size bounds are counted on bytes as they arrive (oversized events still refused before their terminator). BOM (including a BOM split across chunks), CR/LF/CRLF, comments, id:, unknown fields: unchanged behavior.
  • SseExchangeStream lets the framer append straight into its pending buffer (no intermediate Vec per chunk, no VecDeque shifting).
  • Anthropic adapter parses once. StreamingEvent::wire_type() returns the type the single parse selected; the SSE event name is checked against it. The EventEnvelope pre-parse is gone.
  • qq-client /events decoder — same shape, duplicated (the client must not depend on qq-provider). Its extra behaviors are kept: id: field, line bound, final event without a blank line, MalformedSse on a non-UTF-8 line.
  • Tool-call ids stay String (D10 proposed Arc<str>). The ledger clone is one small allocation per delta against the delta's own JSON parse, and the change would widen a public ProviderEvent type into core's PendingToolCall/RuntimeToolCall. Not worth it on this evidence; recorded in ADR-0025 as a follow-up if a profile isolates it.

Behavioral note (one relaxation)

Previously the Anthropic adapter refused any SSE name that didn't match the payload type, including for payload types it doesn't model (which it then ignored). Now, since the type of an unmodelled payload is never read, such a payload is ignored under any name. Known types with a mismatched name are still refused. A test (the_event_name_is_checked_against_the_payload_in_one_parse) names this.

How verified

  • cargo test --workspace — 1,386 passed / 4 ignored; fmt; clippy --workspace --all-targets --all-features -D warnings clean; cargo build --workspace
  • cargo test -p qq-provider --no-default-features --features test-support — 169 passed
  • Property tests in both crates: a body containing a BOM, all three line endings, a comment, multi-line data:, id:, and an unknown field is framed at every split point and every chunk size and must produce the same events as one push. Plus: split-BOM and non-BOM-prefix handling; invalid data UTF-8; size bound spanning lines and resetting per event; unterminated oversized line (client).

Measurements

sse_decode, 5 interleaved pairs vs a2c6824, release, separate target dirs (evidence: target/qq-perf/h19-2026-09-14/):

Case Frame µs Frame allocs Frame+parse µs Total allocs
openai_responses 64 KiB 184 → 41 (0.22x) 4,734 → 864 259 → 103 (0.40x) 5,785 → 1,915
openai_responses 1 MiB 2,867 → 620 (0.22x) 75,384 → 13,576 3,963 → 1,644 (0.41x) 92,137 → 30,329
anthropic_messages 64 KiB 220 → 50 (0.23x) 5,758 → 1,576 400 → 168 (0.42x) 8,595 → 3,891
anthropic_messages 1 MiB 3,790 → 793 (0.21x) 91,560 → 24,862 6,397 → 2,636 (0.41x) 136,861 → 61,879

Framing is now 30–40 % of decode; the remainder is serde_json on each payload, which is the adapter's real work.

Docs

  • docs/adr/0025-sse-chunk-framing.md (Accepted); docs/adr/README.md; docs/plans/progress/root.md (0024 → merged, 0025 added)
  • docs/design/architecture.md § Provider Compilation (streaming rule)
  • Plan status block (Now → H19 in review; Next → H21.2), task index (H18 Done, H19 In review), D10 as-built note, Phase 6 order/acceptance, bench inventory; ledger receipt in docs/plans/progress/speed-first.md (also closes H18 as Shipped (a13fbfd, #38))

Compatibility

  • qq-provider: SseDecoder is crate-private; SseDecoder::push (Vec-returning) is now #[cfg(test)], the hot path uses push_into. openai::decode_event/anthropic::decode_event/sse_decoder and DecodedEvent became pub(crate) for the bench. test_support::decode_sse_body added (test-support feature only).
  • qq-client: SseDecoder::feed_byte → feed(&[u8], &mut Vec); private type.
  • No public API change.

Follow-ups

  • Next slice per plan: H21.2 (mechanical sessions.rs split), which also absorbs the persist_model_turn re-measure noted under H18.

Realistic text-delta streams at 64 KiB / 512 KiB / 1 MiB for the OpenAI
Responses and Anthropic decoders, delivered in 16 KiB chunks; reports
framing alone and framing plus the adapter's parse, with allocation counts.
Baseline at a13fbfd: framing is 55-72% of the decode path at ~11
allocations per event (a fresh Vec per line plus name/data strings) and
~5.4 bytes allocated per body byte; 1 MiB frames in 2.9-3.7 ms.
test_support::decode_sse_body drives the decoders without a transport.

Slice: H19
…events once (H19)

SseDecoder::push_into scans a chunk for line ends once and parses each
line in place from the chunk; only a line a chunk boundary splits is
buffered, and the event's data accumulates in one reusable buffer that is
moved into the event, so an event costs one allocation instead of ~11.
SseExchangeStream lets the framer append straight into its pending buffer.
The Anthropic adapter reads the payload type from the single parse and
checks the SSE name against it, dropping the envelope pre-parse.

Property test: every split point and every chunk size of a body with BOM,
CRLF/CR/LF, comments, multi-line data, and unknown fields frames identically
to one push. sse_decode vs a2c6824: 1 MiB framing 2853 -> 640 us (OpenAI),
3731 -> 805 us (Anthropic); allocations 75k -> 13.6k and 92k -> 24.9k;
frame+parse 4003 -> 1650 us and 6425 -> 2670 us.

Slice: H19
The client SseDecoder mirrors the provider framer: one scan per chunk,
lines parsed in place, only a boundary-split line buffered, the data buffer
reused across events. Behavior is unchanged (id field, BOM, CR/LF/CRLF, a
final event without a blank line, line and event bounds enforced as bytes
arrive); a property test frames a body at every split point and every
chunk size identically to one feed. Duplicated rather than shared so the
client keeps no dependency on qq-provider.

Slice: H19
@lg2m
lg2m merged commit 53bca7d into main Sep 14, 2026
4 checks passed
@lg2m
lg2m deleted the perf/h19-sse-framing branch September 14, 2026 21:50
lg2m added a commit that referenced this pull request Sep 15, 2026
* refactor(runtime): split sessions.rs by concern (H21.2)

Mechanical move of the 34.6k-line sessions.rs into ten concern modules
(claim, codec, commands, compaction, events, settlement, snapshots,
streaming, tool_calls, transcript) and a tests tree (shared harness in
tests.rs; 292 tests in thirteen theme modules). Every moved item became
pub(super) with its fields and inherent methods; nothing else in the
moved text changed, and rustfmt reflowed only what the visibility prefix
and the dedent required. sessions.rs keeps the constants, the module
declarations, the public re-exports, and a glob of every concern module
so the halves import each other as before.

Slice: H21.2

* docs(h21.2): record the sessions split; close H19 (#39)

Slice: H21.2

* docs(ledger): link H21.2 PR #44
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