Skip to content

perf(ai): reuse encoded bodies and prepared system blocks - #189476

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-anthropic-request-body-double-copy-20260919
Oct 31, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-anthropic-request-body-double-copy-20260919

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Repeated large model requests allocate redundant body copies and normalize the same Anthropic system prompt again on every call.

User Impact

Lower request-preparation CPU and allocation, with unchanged request bytes, prompt-cache boundaries, diagnostics, and retry behavior. No configuration or migration is needed.

Why This Change Was Made

The shared OpenAI request owner now passes its already-encoded Uint8Array directly to Fetch. This removes the intermediate Blob and the fetch guard's materialization of that Blob; native Fetch still takes its required dispatch snapshot. The unused encoded-body observer is removed. Generic Blob replay handling remains intact.

Anthropic system normalization now follows the existing immutable prepared-prompt revision, with separate cache-policy variants. Payload hooks receive editable copies, OAuth identity headers remain current, and obsolete revisions are weakly owned. This uses the session's existing revision lifetime rather than adding a string pool or eviction policy.

Anthropic's frozen-message Blob fragments from #186872 remain: an exploratory cached-string/byte composition comparison increased CPU and JS allocation. Codex inference already retains one upload buffer and has no matching Blob conversion.

Evidence

Five serial A/A/B pairs per mode; timing and allocation sampling ran separately. Synthetic 600 KiB UTF-8 request bodies, roughly a 150k-token byte budget; no tokenizer or real user data. Shared handoff exercised the real fetch guard and native Request body consumption. Encoding and network/model latency are excluded.

Shared body handoff, per request Before A/A control After
Main-thread CPU, median 345.37 µs 359.83 µs 206.60 µs
CPU range across five batch means 325.07–379.98 µs 351.55–384.73 µs 186.42–239.58 µs
Wall time, median 351.71 µs 376.89 µs 212.17 µs
Sampled JS allocation, median 56,735 B 53,653 B 48,474 B
GC per 500 requests, median 29.92 ms 34.96 ms 16.12 ms

Two additional native 614,400-byte copies per request are eliminated; they are excluded from sampled JS allocation. Every arm produced the same wire SHA-256.

Prepared 64 KiB Anthropic system owner, per request Before A/A control After
CPU, median 6.326 µs 6.325 µs 0.131 µs
CPU range across five batch means 6.292–6.433 µs 6.288–6.456 µs 0.129–0.132 µs
Sampled JS allocation, median 909 B 921 B 461 B

Wire hashes match across tool turns, moved cache boundaries, payload edits/replacements, and both revisions. The new regressions fail on the original owner: encoded-buffer identity differs, and repeated system normalization occurs 12 times instead of 6. Native Request replay preserves bytes after mutation of the first consumed snapshot. The system regression covers interleaved revisions/policies, editable blocks, stale revisions, and changing OAuth versions.

Reproduce shared handoff with node --expose-gc --import ./scripts/tsx.mjs scripts/perf/model-request-body-measure.ts --base ed51affd7873d3e3125d9e3b72d65535e874fbf4 --iterations 500 --pairs 5, then repeat with --allocation. System owner uses scripts/perf/anthropic-request-construction.ts --messages 150 --mode system --prepared-system --iterations 20000, with the two prior Anthropic owner modules supplied through its existing --baseline-dir overlay option. The acceptance rule is identical bytes, lower owner CPU/allocation, and no material GC regression.

Focused validation: 34 policy/transport tests, 114 body/diagnostic/fetch tests, 14 prompt-prefix tests, and the immutable Blob redirect/retry regression passed. Actual regression test time is milliseconds; first-run compiled prefix proof took 79 seconds including compilation. Package artifact E2E is left to PR CI. No whole-Gateway, live-provider cache-token, or production-runtime improvement is claimed.

Production delta: +26 lines. Shared body handling shrinks by 2; revision-owned system reuse adds 28 to preserve policy separation and editable hooks. The +103 test-line allocation is scoped to the two regression contracts. Open #170438 touches the same Anthropic modules but changes message checkpoint placement, not the system helper.

Independent Codex review is clean through P2. pnpm check:changed passed every gate except three new non-null assertions in the system regression; those were replaced by an explicit fixture check, and targeted lint plus the 10-test policy suite passed afterward. The test-line ratchet also passed. No inherited failure is being excused.

Avoid redundant Blob copies for shared model requests and normalize Anthropic system blocks once per prepared prompt revision. Preserve exact request bytes, editable hooks, stream metadata, and native Fetch replay. Keep Anthropic frozen-message Blob composition because the string alternative regresses CPU and allocation.
@clawsweeper

clawsweeper Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts agents Agent runtime and tooling size: M labels Oct 31, 2026
@steipete
steipete marked this pull request as ready for review October 31, 2026 14:56
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-31T14:58:03.903247Z 6971dd1 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 31, 2026
@clawsweeper

clawsweeper Bot commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR reuses encoded request buffers and normalizes Anthropic system blocks once per prepared prompt revision and cache policy.

Example: Prepare repeated requests with a 614,400-byte encoded body.

  • Before: The shared request owner creates a Blob that the fetch guard materializes into another byte buffer.
  • After: The owner passes its encoded buffer directly onward, preserving native Fetch's dispatch snapshot.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Focused, correct-looking owner changes with successful exact-head gates; performance confidence rests on bounded in-process measurements.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its synthetic workloads exercise shared encoding through the real fetch guard and native Request consumption, plus Anthropic system normalization, with reported matching bytes and lower preparation costs.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Repeated large model requests spend avoidable CPU and memory preparing unchanged request content.
Reason: The maintainer-authored direction removes measured duplicate work without changing provider bytes, runtime defaults, or stored state.

Merge readiness

✅ Ready for maintainer review

This PR provides a useful, focused performance improvement absent from current main; no actionable correctness or security findings were identified.

Priority: P2
Reviewed head: 6971dd1c77c8fe705cc715fe54717fcce473acf8

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied evidence exercises production owners and native Request consumption, without a shipped Gateway or live-provider run.
Agent review details

How this fits together

The AI package converts prepared agent context into provider requests; encoded bodies pass through SDK dispatch and guarded fetch, while Anthropic system blocks pass through cache policy and editable payload hooks.

flowchart TD
  A[Prepared agent context] --> B[Anthropic system policy]
  B --> C[Editable payload hooks]
  A --> D[Shared request encoder]
  C --> E[Provider request]
  D --> E
  E --> F[Guarded fetch]
  F --> G[Provider endpoint]
Loading

Technical review

Best possible solution:

Reuse the existing encoder buffer and revision-owned system projections while preserving exact bytes, editable hooks, and cache-policy separation.

Do we have a high-confidence way to reproduce the issue?

The base source visibly constructs the redundant Blob and repeats system normalization; the PR supplies paired measurements and reports discriminating base failures, but no target code was executed during this review.

Is this the best way to solve the issue?

The patch is a small complete optimization using existing owners, with benchmark-only flags and no runtime configuration or persisted-format changes.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 194b10349b12.

Provenance checked

  • Shared encoded-body handoff changes intended behavior with a stated reason (29ccb9b: The immutable Blob originally shared storage with fork replay and avoided Fetch retention costs; this PR explains its removal, and current source verifies the observer no longer has consumers.)
  • Anthropic system shaping keeps the original intent (5a4f24e: Independent tool/system checkpoints preserve tool caching when prompts change and conserve OAuth marker slots; the new reuse retains those rules and current identity text.)
  • Frozen Anthropic message fragments keeps the original intent (f20d1f4: Immutable message projections and Blob fragments avoid repeated full-history serialization while supporting editable hooks; this PR deliberately retains that owner.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 69809d7 adds packages/ai/src/transports/model-request-body.ts:46 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 69809d7a9427; files: packages/ai/src/transports/model-request-body.ts)

PR surface

Source +26, Tests +103, Other +159. Total +288 across 10 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 39 13 +26
Tests 4 106 3 +103
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 3 162 3 +159
Total 10 307 19 +288

Review metrics

Metric Value Why it matters
Production versus regression growth Production +39/-13, net +26; tests +106/-3, net +103. Production growth adds revision/policy isolation and editable copies; the two regression contracts cover buffer reuse and interleaved system revisions.

Labels

Label changes:

  • add P2: Measured request-preparation CPU and allocation improvements have clear value but no demonstrated urgent user-facing failure.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Measured request-preparation CPU and allocation improvements have clear value but no demonstrated urgent user-facing failure.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 31, 2026, 11:12 AM ET / 15:12 UTC.

@steipete
steipete merged commit f1c9357 into main Oct 31, 2026
207 of 210 checks passed
@steipete
steipete deleted the steipete/perf-micro-anthropic-request-body-double-copy-20260919 branch October 31, 2026 15:15
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 1, 2026
…89476)

Avoid redundant Blob copies for shared model requests and normalize Anthropic system blocks once per prepared prompt revision. Preserve exact request bytes, editable hooks, stream metadata, and native Fetch replay. Keep Anthropic frozen-message Blob composition because the string alternative regresses CPU and allocation.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant