Skip to content

perf(ai): reduce allocation when validating long continuations - #182365

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-fork-capture-transport-encoding-20261024
Oct 24, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-fork-capture-transport-encoding-20261024

Conversation

@steipete

@steipete steipete commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Related: #145679

What Problem This Solves

Long Responses continuations encode and parse both normalized histories just to compare them, before encoding the fork snapshot and accounting for the completed continuation state.

User Impact

Continuation decisions, provider wire bytes, and independent-fork prefixes remain unchanged. Large matched histories allocate less temporary memory and use less CPU.

Why This Change Was Made

Remove validation's two full-history JSON round trips. The existing continuation owner compares transient JSON-value projections that keep text by reference. Native JSON still handles hook-provided custom serializers, proxies, built-in objects, and invalid/cyclic values with their property keys. This preserves omission/null/number semantics without a cache, additional retained prepared graph, or another wire/capture representation.

An audit of provider-built content found plain text/image/tool-result records and JSON-projected tool schemas, with no non-idempotent production toJSON on that path. Arbitrary payload hooks remain supported by native subtree serialization; dispatch and fork serialization are untouched. Normalized call-ID, assistant-metadata, reasoning-control, and envelope-change rules are unchanged.

Production code grows by 51 lines: the JSON projection is needed to preserve those semantics while deleting full-history encoding/parsing. It is private to its only consumer; no new exported API, config, dependency, or cache.

Evidence

The real Responses transport work-count test fails on base with 4 full-history serializations and requires 2 after the change: validation 2→0, fork capture 1→1, completed-state accounting 1→1. The wire still encodes one suffix. The same test checks exact wire and replay-prefix bytes. Existing continuation/reasoning tests cover accepted and rejected histories, changed envelopes/tools, call-ID collisions, unsafe arguments, and recovery.

Owner benchmark on Node 26.12.1, 4,096-character fields, six counterbalanced samples per side per size; 120 unprofiled CPU calls and 60 separately sampled allocation calls per side. Sampling includes collected objects at a 32 KiB interval. These are local owner measurements, not Gateway latency or GC/promotion claims.

History items Allocated bytes/call before → after Absolute / relative delta CPU ms/call before → after Absolute / relative delta Allocation samples before / after
200 3,673,728 → 1,709,244 -1,964,483 / -53.47% 1.567742 → 1.088133 -0.479608 / -30.59% 2,234 / 1,657
1,000 18,068,587 → 7,760,823 -10,307,765 / -57.05% 7.435200 → 4.179175 -3.256025 / -43.79% 9,889 / 6,594

The benchmark includes actual validation, body encoding, and fork capture owners with explicit external-service adapters; it excludes response-commit accounting and provider/Gateway execution. In that scope, full-history serialization drops 3→1, and serialized full-history bytes drop 2,501,981→835,519 at 200 items and 12,509,781→4,176,719 at 1,000. Wire and snapshot bytes match exactly. All three tracked prepared-payload references collect on both sides at both sizes; this is a bounded retention check, not a whole-process retained-heap claim.

Reproduce with node --expose-gc scripts/perf/responses-continuation-measure.mjs <baseline-root> <candidate-root>; the script lists its seven required source files and emits source hashes and all raw samples. No queued remote compute or production profiling is required.

Independent subagent review (autoreview route unavailable): clean, no actionable P0–P2 findings. The autoreview helper refused the selected provider route because it does not match the operator configuration; no configuration was changed. Scoped type-aware lint and the core typecheck passed. All 117 focused tests passed across the continuation, reasoning-update, continuation-retention, real-client continuation integration, session-fork, and agent-tools prefix-stability files. The work-count regression fails on base (4 encodings instead of 2). After deployment, look for lower allocation and CPU per matched continuation/history size; fork-capture allocation itself remains, so its stack disappearing is not the success criterion.

Focused validation

node scripts/run-vitest.mjs <files below> --maxWorkers=1: 117 passed.

  • packages/ai/src/transports/openai-responses-continuation.test.ts
  • packages/ai/src/transports/openai-responses-reasoning-update.test.ts
  • packages/ai/src/transports/openai-responses-continuation.retention.test.ts
  • packages/ai/src/transports/openai-responses-client.continuation.integration.test.ts
  • src/agents/embedded-agent-runner/session-fork.test.ts
  • src/agents/agent-tools.prefix-stability.test.ts

pnpm tsgo:core, changed-file oxfmt, scoped type-aware lint, benchmark syntax, and git diff --check: passed. Tests and measurements used baseline 5e0b786b18d1cc8af25e3eac7ca987085d6f1de0; the latest pre-push rebase onto 068022e6e8df leaves the affected transport/capture sources and this patch unchanged. PR CI supplies broad proof on the pushed head.

The first CI run found an obsolete assertion-safety allowance for the two deleted casts. The native prune command removed exactly that entry (2→0), and the targeted assertion-safety check passed; this is a shrink-only metadata correction, with no runtime change. All transport test shards, prompt snapshots, production types, lint, and architecture checks passed on that run.

CI is green on 4fd80f2cb7e432e32ffc7f4a487c24c69c4c44a9, including the corrected assertion-safety ratchet. The current-head automated code review reports no findings. ClawSweeper’s earlier-head finding was the same allowance correction; the fix evidence and one re-review request are posted.

Leave this PR open for the lead to merge.

@clawsweeper

clawsweeper Bot commented Oct 24, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 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-24T07:43:33.247342Z 4fd80f2 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.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts agents Agent runtime and tooling size: L labels Oct 24, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 24, 2026
@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: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 24, 2026
@clawsweeper

clawsweeper Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR compares transient JSON-value projections instead of encoding and parsing entire histories when validating Responses continuations.

Example: Continue a conversation containing 1,000 history items with 4,096-character fields.

  • Before: The supplied owner benchmark reports 18,068,587 allocated bytes and 7.435200 CPU milliseconds per call.
  • After: It reports 7,760,823 allocated bytes and 4.179175 CPU milliseconds per call, with identical wire and snapshot bytes.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is focused and supported by measured production-owner behavior and green current-head gates, with confidence bounded by harness-level proof.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; supplied Node owner measurements exercise continuation validation, body encoding and fork capture with explicit service adapters, while excluding Gateway/provider execution.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Long matching Responses histories consume avoidable CPU and temporary memory before the next request can proceed.
Reason: The maintainer-directed optimization has measured owner-level gains and preserves the existing user-facing contract.

Merge readiness

✅ Ready for maintainer review

This PR provides a focused, measured optimization that current main still lacks; the prior assertion-baseline finding is fixed, and no actionable introduced defect was found.

Priority: P2
Reviewed head: 4fd80f2cb7e432e32ffc7f4a487c24c69c4c44a9

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied owner benchmark and transport tests do not demonstrate this change through a shipped Gateway/provider entry point.
Agent review details

How this fits together

The shared Responses continuation resolver receives prepared requests and previous response state, validates their compatibility, and returns either a suffix referencing the previous response or the full request for HTTP and WebSocket callers.

flowchart LR
  A[Prepared request] --> B[Continuation resolver]
  C[Previous response state] --> B
  B --> D[JSON value comparison]
  D --> E[Suffix or full request]
  E --> F[HTTP or WebSocket transport]
Loading

Technical review

Best possible solution:

Retain the optimization in the existing continuation owner while preserving native JSON semantics, continuation decisions, and exact request and fork-prefix bytes.

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

Current main visibly serializes both comparison operands, and the supplied benchmark and reported base-failing work-count regression identify that repeated work; this review executed no target code.

Is this the best way to solve the issue?

The smallest complete change belongs in the existing comparator: the projection removes the redundant text copies without adding a cache, retained representation, or parallel continuation policy.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Responses JSON comparison keeps the original intent (b6aa285: Avoid duplicate normalization while preserving JSON-wire semantics, serialization failures, and left-before-right hook ordering.)
  • Parsed-JSON deep equality keeps the original intent (1663ea8: Reduce request-preparation allocation while comparing already-normalized continuation values directly.)
  • Session-fork continuation regression keeps the original intent (85e7a9b: Consolidate low-value tests while retaining the full-prefix continuation contract.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 76c9dc1 adds packages/ai/src/transports/openai-responses-continuation.ts:343 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 76c9dc1605bc; files: packages/ai/src/transports/openai-responses-continuation.ts)
  • Markus Hartung: Raw commit 45f155d adds packages/ai/src/transports/openai-responses-continuation.ts:38 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 45f155d88a9b; files: packages/ai/src/transports/openai-responses-continuation.ts)

PR surface

Source +51, Tests +96, Other +450. Total +597 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 56 5 +51
Tests 2 99 3 +96
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 451 1 +450
Total 5 606 9 +597

Labels

Label changes:

  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: The supplied measurements establish useful CPU and allocation savings for long continuations without evidence of an 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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-24T07:38:56.145Z sha b8e046cca2b9a84e3d6918201646b9b875cc940f :: needs changes before merge. :: [P2] [P2] Remove the obsolete assertion-safety baseline entry

Reviewed October 24, 2026, 3:56 AM ET / 07:56 UTC (Revision 2).

@steipete
steipete force-pushed the steipete/perf-fork-capture-transport-encoding-20261024 branch from b8e046c to 4fd80f2 Compare October 24, 2026 07:40
@steipete

Copy link
Copy Markdown
Contributor Author

Fixed the obsolete assertion-safety allowance in 4fd80f2cb7e432e32ffc7f4a487c24c69c4c44a9: the native prune tool removed exactly the continuation file's 2-count entry. The targeted local ratchet passed, and the corrected-head baseline-ratchet CI job is green.

Production code and measured owner inputs are unchanged. The PR body records the correction and the owner-only proof boundary; it makes no live-provider, whole-Gateway, or GC claim.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 24, 2026
@steipete
steipete merged commit d181181 into main Oct 24, 2026
151 of 152 checks passed
@steipete
steipete deleted the steipete/perf-fork-capture-transport-encoding-20261024 branch October 24, 2026 08:00
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 25, 2026
…law#182365)

* perf(ai): avoid full-history JSON copies in continuation checks

* chore(ai): prune removed continuation assertion allowance
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: L 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