Skip to content

perf(runtime): shared transcript, raw tool JSON, and a precompiled prompt prefix (H18) - #38

Merged
lg2m merged 8 commits into
mainfrom
perf/h18-shared-transcript-prompt-prefix
Sep 14, 2026
Merged

lg2m merged 8 commits into
mainfrom
perf/h18-shared-transcript-prompt-prefix

Conversation

@lg2m

@lg2m lg2m commented Sep 14, 2026

Copy link
Copy Markdown
Collaborator

H18: shared transcript, raw tool JSON, and a precompiled prompt prefix (D5)

Spec: docs/plans/speed-first-extensible-agent-harness.md § D5 · ADR: docs/adr/0024-shared-transcript-raw-json-prompt-prefix.md

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

What changed

  • provider_encode bench (new, first commit). One MiB transcript + 32 schemas encoded for each HTTP protocol under a counting global allocator; reports encode time, body size, and the request's peak heap above the transcript along the adapter path (build → per-attempt clone → body), both from an owned Vec and from a shared Arc. test_support::encode_body exposes the wire structs without a transport. Baseline at 43caaea: 4.4–4.7x payload heap (D5 estimated ~3x — the tool-call Value trees and Responses/Chat to_string() per request were uncounted), 340–560 µs.
  • Shared transcript. ModelRequest.messages: Arc<Vec<Message>>. The run loop holds the same Arc, gives each turn's request a handle, drops the provider stream before appending, and appends via Arc::make_mut — a test pins that turn two's request carries the same allocation turn one saw. Every adapter's per-attempt request.clone() inside with_restart is now a refcount bump.
  • Raw tool JSON. ToolSpec.input_schema and ContentBlock::ToolCall.arguments are Box<RawValue> (workspace serde_json/raw_value). Codecs embed the text verbatim (or as the JSON string Responses/Chat want). The run already had the canonical argument string when it validated the call; the duplicate parsed Value on PendingToolCall is gone, measure_message stops re-serializing, and the catalog measures/digests schemas from the same text without a parallel Arc<str> list. Bedrock alone parses (SDK wants Document). PersistedContentBlock.arguments stays Value (internally tagged enums buffer; parse once at load).
  • Prompt prefix. CompiledAgentPlan holds a PromptPrefix per capability set (StaticFilter × guidance; ≤32 keys) — header/tool names, tool index, skill index, workspace instructions, persona — with its SHA-256 state. The common set is built at compile (counted in estimated_bytes); others on first use. A run appends only its suffix (selected guidance, context blocks, output contract) and finalizes a cloned hasher, so system_prompt_hash equals a whole-prompt digest. A test pins digest and byte-for-byte text across four capability sets against the single-pass builder.
  • Word-parallel string escaping. Finding: with RawValue fields in the wire structs, serde_json's per-byte string escape lost 30–60% on the transcript, and the loss appeared/vanished with unrelated codegen (identical instruction counts, different loop alignment — verified with perf stat/annotate). providers::support::Text wraps every bulk string: a SWAR scan finds the next byte needing escape 8 at a time, the clean run is copied once, and the literal reaches serde_json through its raw-value hook. Byte-identical output; exhaustive test of every byte value at every lane.

How verified

  • cargo test --workspace — 1,381 passed / 4 ignored (after rebase onto T3–T5, 95fef1b)
  • cargo fmt --all -- --check; cargo clippy --workspace --all-targets --all-features -- -D warnings clean; cargo build --workspace
  • cargo test -p qq-provider --no-default-features --features test-support — 165 passed; minimal-profile clippy clean
  • New tests: model::tests ×2 (request shares/releases the transcript; raw text preserved, from_raw == new); support::tests ×1 (escape parity incl. 8 lanes × 256 bytes, UTF-8, embedded in structs); qq_core::tests ×2 (the_transcript_is_shared_with_each_request_and_grown_in_place, prefix_plus_suffix_digest_equals_the_full_prompt_digest)

Measurements

provider_encode, release profile, separate target dirs, interleaved A/B vs 43caaea (evidence: target/qq-perf/h18-2026-09-13/ in the main checkout, untracked):

Protocol Heap: owned Vec Heap: shared Arc (run loop) Encode med (µs)
openai_responses 4.49x → 2.70x 1.57x 429 → 191
openai_chat 4.73x → 2.93x 1.80x 466 → 212
anthropic_messages 4.37x → 2.68x 1.55x 339 → 194
google_generate_content 4.40x → 2.70x 1.57x 559 → 406

Two candidate builds (default, debuginfo) agree within 6%. D5 gates: heap ≤2x met on the run-loop path; encode ≤10 ms met by ~25x.

Named gate A B Δ
provider_recipe_compile 488 ns 496 ns +1.5%
google_recipe_compile 362 372 +2.9%
mantle_recipe_compile 264 284 +7.8% (20 ns; host noise band — see ledger)
mantle_warm_dispatch 114 114 +0.4%
plan_compile 22.09 µs 22.47 µs +1.7% (builds the common prefix once)
plan_descriptor_digest 2289 ns 2310 ns +0.9%
plan_estimated_bytes 16,406 20,740 prefix counted

Docs

  • docs/adr/0024-shared-transcript-raw-json-prompt-prefix.md (Accepted); docs/adr/README.md; docs/plans/progress/root.md
  • docs/design/architecture.md § Compiled Agent Plans (prefix, shared transcript, raw JSON, Text)
  • Plan status block (Now → H18 in review, Phase 5b closed; Next → H19), task index, D5 as-built note, Phase 6 order and acceptance; ledger receipt in docs/plans/progress/speed-first.md (also closes HC4 as Shipped (43caaea, #34))

Compatibility

  • qq-provider public API: ModelRequest::new takes impl Into<Arc<Vec<Message>>> (a Vec still works); ModelRequest::shared_messages() added; ToolSpec::input_schema() returns &RawValue (was &Value); ToolSpec::from_raw and ContentBlock::tool_call(id, name, &Value) added; ContentBlock::ToolCall.arguments is Box<RawValue>. ContentBlock/ToolSpec PartialEq compare JSON text (exact for canonical output).
  • Text depends on serde_json's private raw-value token ("$serde_json::private::RawValue") — the same hook RawValue itself serializes through; the unit test fails immediately if it is ever renamed.

Follow-ups / decisions needed

  • persist_model_turn (sessions.rs) re-measures the assistant message the runtime already measured — fold into H21.2.
  • The 1 MiB / 512 KiB H0 ratio (Phase 6 acceptance) is a quiet-host fixture recording, not made here.
  • Next slice: H19 after its sse_decode baseline.

Review note: touches ModelRequest/ContentBlock (shared types) and the run loop in lib.rs; the prompt-hash equality test is the guard for persisted RunPromptIdentity and occupancy reuse.

One MiB transcript plus 32 schemas encoded for each HTTP protocol; reports
encode time, body size, and the request's peak heap above the transcript
along the adapter path (build, per-attempt clone, body). Baseline at
43caaea: 4.4-4.7x payload, 335-555 us. test_support::encode_body exposes
the wire structs without a transport.

Slice: H18
…H18)

ModelRequest.messages is Arc<Vec<Message>>: the per-attempt clone every
adapter performs inside with_restart is a refcount bump. ToolSpec.input_schema
and ContentBlock::ToolCall.arguments are Box<RawValue>: every codec embeds
the compact text verbatim (or sends it as the string Responses and Chat
want) instead of walking a Value tree or re-stringifying per request.
Bedrock alone parses, because the Converse SDK wants a Document tree.

provider_encode, 6 interleaved A/B pairs, release profile, separate target
dirs: request heap 4.4-4.7x -> 2.7-2.9x payload; encode openai_responses
430 -> 305 us, openai_chat 479 -> 326, anthropic 342 -> 333, google 570 -> 504.

Slice: H18
…tay text (H18)

The run holds Arc<Vec<Message>>, hands it to each turn's request by
reference count, drops the provider stream before appending, and appends
through Arc::make_mut, which copies nothing once the stream is gone (a test
pins the same allocation across turns). Tool-call arguments keep the
canonical string the run already produced; PendingToolCall loses its
duplicate parsed Value and measure_message stops re-serializing. The
catalog reads schema text straight from each spec instead of serializing
on compile and carrying a parallel Arc<str> list.

Slice: H18
…e its digest (H18)

CompiledAgentPlan holds a PromptPrefix per capability set (header, tool
index, skill index, workspace instructions, persona) with its SHA-256 state;
the common set is built at compile, others on first use. A run appends only
its suffix (selected guidance, context blocks, output contract) to a copy
and finalizes the cloned hasher over the suffix, so system_prompt_hash is
unchanged from a whole-prompt digest; a test pins that across four
capability sets and against the single-pass builder.

Slice: H18
…r (H18)

With RawValue fields in the request structs serde_json's per-byte escape
loop lost 30-60% on a one MiB body, and the loss flipped with unrelated
build changes (same instruction count, different loop alignment). Text<'a>
and OwnedOrBorrowedText<'a> wrap every bulk string (message text, tool
results, system prompt): a SWAR scan finds the next byte needing escape
eight at a time, the clean run is copied once, and the literal reaches
serde_json through its raw-value hook. Byte-identical output, pinned by an
exhaustive per-lane test. The bench now also reports request heap from a
shared Arc, the run loop's case.

provider_encode vs 43caaea, 5 interleaved triples (base, cand, cand with
debuginfo): openai_responses 429 -> 191 us, openai_chat 466 -> 212,
anthropic 339 -> 194, google 559 -> 406; both candidate builds agree.

Slice: H18
@lg2m
lg2m merged commit a13fbfd into main Sep 14, 2026
4 checks passed
@lg2m
lg2m deleted the perf/h18-shared-transcript-prompt-prefix branch September 14, 2026 20:21
@lg2m lg2m mentioned this pull request Sep 14, 2026
lg2m added a commit that referenced this pull request Sep 14, 2026
…ent (H19) (#39)

* docs(ledger): start H19, close H18 (#38)

Slice: H19

* perf(provider): sse_decode bench with a counting allocator (H19)

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

* perf(provider): frame SSE per chunk with one buffer, parse Anthropic 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

* perf(client): frame the /events stream per chunk (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

* docs(h19): ADR-0025 SSE chunk framing; architecture, plan, and ledger

Slice: H19

* docs(ledger): link H19 PR #39
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