Skip to content

perf(ai): reuse frozen Anthropic HTTP request bytes - #186872

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-anthropic-body-fragments-20261028
Oct 28, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-anthropic-body-fragments-20261028

Conversation

@steipete

@steipete steipete commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Managed Anthropic HTTP requests repeatedly convert and serialize unchanged frozen conversation history, producing a large temporary JSON string on every tool turn.

User Impact

Lower main-thread CPU and allocation during repeated requests with frozen history. Request bytes, prompt-cache checkpoints, editable payload hooks, redirects/retries, SSE handling, and debug capture remain unchanged. A fragment cache retains one encoded copy of reusable live history; weak identities release it with that history. No configuration or schema changes.

Why This Change Was Made

The converter owns immutable message projections and route/group variants. Cache checkpoints copy only the marked containers. The request owner retains immutable Blob fragments by converted-message identity and encodes the envelope and mutable tail on each request. The existing guard still materializes contiguous bytes, so this does not eliminate the full byte copy or introduce streaming.

Hooks receive editable containers. An unchanged-graph proof permits fragment reuse; any edit or replacement uses full native JSON serialization. Opaque values retain native getter/toJSON behavior. Enabled debug capture snapshots the guard's bytes before dispatch. The SDK route retains SDK-owned body transformations and encoding.

Follow-up: share fragments with Responses after adapting its prompt-state worker's exact-byte hashing and diagnostic ownership. That is separate from this managed Anthropic HTTP change.

Evidence

Measured against source base 3eb6e8df529b; the relevant Anthropic owners were unchanged by the clean rebases onto current main (d7349d9395e2). Reviewed/pushed head: 1f94b15e2ee0762d0f1b2d86b313b961b3a1b3c4.

Acceptance: identical wire hashes, lower paired CPU/allocation per request, and no controlled material GC regression. Five alternating base/candidate pairs, separate untraced CPU and sampled JS-allocation passes, 2,000 warmups and 2,000 measured operations per arm. The 40/150-message fixtures include tools, system blocks, cache_control, an always-present payload hook, a changing mutable tail and changing max_tokens. Measurement includes real conversion/preparation, hook copies/comparison, encoding, and contiguous Blob.arrayBuffer consumption.

History Main-thread CPU/request Sampled JS allocation/request
40 messages 781.43 → 283.70 µs (-63.7%) 494,493 → 463,838 B (-6.2%)
150 messages 2868.34 → 918.08 µs (-68.0%) 1,788,345 → 1,483,550 B (-17.0%)

Five release controls per size retained exactly 192,751 / 750,911 fragment bytes for 40 / 150 messages, plus approximately 33 / 45 KB of additional JS heap over the baseline control. Every source/projection WeakRef was collected and all fragment backing bytes reclaimed. Native output remains 200,833 / 758,994 bytes per measured request (not included in sampled JS allocation).

GC and host-load context

Untraced total GC/request rose from 0.00405 to 0.00703 ms at 40 messages (+0.00298 ms, +73.4%) and 0.01935 to 0.02681 ms at 150 (+0.00745 ms, +38.5%). These absolute increases are far below the specified +1 ms/op materiality threshold while CPU improves over 60%; they are context, not an adverse gate. No A/A adverse claim. Major-GC counts are below 50 per arm and context-only.

  • 40 messages: max GC pause per pair (ms, base→candidate): 0.504→1.335, 0.441→0.749, 0.425→0.621, 0.513→0.628, 0.516→0.672. Host load (1m) per arm: base: 17.4, 16.2, 15.7, 17.9, 26.1; candidate: 17.3, 16.2, 15.7, 17.9, 28.0.
  • 150 messages: max GC pause per pair (ms, base→candidate): 1.194→1.425, 1.513→12.109, 5.245→1.720, 3.180→7.353, 23.858→1.518. Host load (1m) per arm: base: 16.6, 17.8, 16.4, 19.6, 24.9; candidate: 17.4, 16.9, 15.6, 19.9, 26.7.
  • Across 10,000 untraced measured requests/arm, 40-message scavenges: 105/40.55 ms → 135/70.30 ms. At 150: scavenges 415/186.74 ms → 443/228.57 ms; incremental marking 5/0.85 ms → 22/3.68 ms; major GC 5/5.94 ms → 22/35.83 ms.

Allocation figures are sampled JavaScript heap allocation, excluding native byte buffers. Full contiguous output bytes still allocate on every request. Owner-level synthetic proof follows the requested fast path; no whole-Gateway latency or production-load claim.

Reproduce with node --expose-gc --import ./scripts/tsx.mjs scripts/perf/anthropic-request-construction.ts --messages 40 --iterations 2000 (repeat with 150 and --allocation; --retained exercises actual projection/fragment lifetime; header documents source-overlay baseline use).

All six base/candidate scenario hashes match: initial request, tool call, tool result, moving cache boundary, hook edit, and hook replacement. The transport work-count regression fails on base (one full-body serialization) and passes on the change (zero), with identical wire SHA-256. Additional regressions cover frozen projection identity, grouped result changes, OAuth/thinking/suffix variants, mutable tails, hook-edited tool inputs, opaque JSON behavior, and capture redaction after fetch mutates its byte buffer.

Focused local validation: 176 tests passed across Anthropic conversion/cache/provider/HTTP transport, prompt-prefix stability, model request bodies, guarded retries and real-loopback debug capture. The two required module-closure files passed all 33 tests; export-name collision guard, changed-file lint/format and diff checks passed. The capture regression fails on base with a missing request body and passes with the original redacted bytes despite a mutating fetch. Focused cache/request files ran in 1–3 seconds; the capture/prefix/body batch took 62 seconds including worker artifact preparation. Broad validation is delegated to PR CI.

Independent subagent review (autoreview route unavailable): the configured autoreview helper refused its provider/config mismatch. The independent review found SDK header-field extraction and caller-controlled array methods; both were fixed and the final scope was reviewed clean.

The non-test diff is +469 lines, including +177 lines in the existing benchmark; runtime code is +292. Growth is required by the editable-hook contract, immutable projection/fragment lifecycle, and capture preservation. The repeated full-history managed-body serialization is removed; native serialization remains for edited/opaque payloads and embedding hosts without plain-data admission. No shared perf README, baseline, ceiling, or budget file changed.

CI repair on the final head: replaced the unavailable DOM-only BlobPart type with the actual string/Blob union, awaited the test helper’s stream factory, and updated two fetch fixtures to decode valid Blob bodies through Request.text(). The production runtime and measured path are unchanged. The failing tsgo:core lane and all three affected integration files pass locally (27 credential/transport, 19 cache-stability, and 2 runtime-context tests), as do the 36 cache parity tests and repaired-file lint.

A later CI run hit a 30-second fork-request timeout in src/gateway/server-plugin-subagent-runtime.fork-transport.test.ts on its OpenAI Completions path. Five single-file Bun replays passed on both the PR head and unchanged base; that did not establish inherited-failure attribution, so no exception was used. The authorization/HTTP fixture now loads the lazy agent module inside its hermetic setup before starting either timed fork. The real fork path, request deadline and every assertion remain unchanged. This scopes the test to an initialized module; the original timeout remains unreproduced and unattributed. The two-line adjustment passed independent review and its focused Bun test.

@clawsweeper

clawsweeper Bot commented Oct 28, 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 size: L labels Oct 28, 2026
@steipete
steipete marked this pull request as ready for review October 28, 2026 15:54
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 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-28T16:49:16.688446Z 1f94b15 New commits
ℹ️ 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 the clawsweeper:intake:feature Preliminary submission classification; full source review pending. label Oct 28, 2026
@steipete
steipete force-pushed the steipete/perf-anthropic-body-fragments-20261028 branch from be2eb47 to 05c9220 Compare October 28, 2026 16:13
@steipete
steipete force-pushed the steipete/perf-anthropic-body-fragments-20261028 branch from 05c9220 to 1f94b15 Compare October 28, 2026 16:46
@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Oct 28, 2026
@steipete
steipete merged commit f20d1f4 into main Oct 28, 2026
135 of 137 checks passed
@steipete
steipete deleted the steipete/perf-anthropic-body-fragments-20261028 branch October 28, 2026 17:11
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 29, 2026
* perf(ai): reuse frozen Anthropic HTTP request bytes

* fix(ai): align request body types and capture fixtures

* test(gateway): prepare fork module before timed transport proof
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawsweeper:intake:feature Preliminary submission classification; full source review pending. gateway Gateway runtime scripts Repository scripts size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant