Repository navigation
perf(ai): reduce allocation when validating long continuations - #182365
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex review: needs maintainer review before merge. What this changesThis 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.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherThe 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]
Technical reviewBest 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
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +51, Tests +96, Other +450. Total +597 across 5 files. Added test files: 0. View PR surface stats
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed October 24, 2026, 3:56 AM ET / 07:56 UTC (Revision 2). |
b8e046c to
4fd80f2
Compare
|
Fixed the obsolete assertion-safety allowance in 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 |
|
🦞👀 Re-review progress:
|
…law#182365) * perf(ai): avoid full-history JSON copies in continuation checks * chore(ai): prune removed continuation assertion allowance
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
toJSONon 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.
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.tspackages/ai/src/transports/openai-responses-reasoning-update.test.tspackages/ai/src/transports/openai-responses-continuation.retention.test.tspackages/ai/src/transports/openai-responses-client.continuation.integration.test.tssrc/agents/embedded-agent-runner/session-fork.test.tssrc/agents/agent-tools.prefix-stability.test.tspnpm tsgo:core, changed-file oxfmt, scoped type-aware lint, benchmark syntax, andgit diff --check: passed. Tests and measurements used baseline5e0b786b18d1cc8af25e3eac7ca987085d6f1de0; the latest pre-push rebase onto068022e6e8dfleaves 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.