Repository navigation
improve: reduce allocation when preparing long conversations - #200888
Conversation
Let the transcript copier certify its plain output before trusted freezing. Preserve inspected freezing for opaque and symbol-bearing SDK data, mutable detachment, and frozen payload sharing. Synthetic A/A/B construction proof reduces allocation by 38 percent with lower CPU and identical context bytes.
|
🦞👀 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 Summary: ✅ CompletedThis 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 lets the transcript copier freeze verified plain output without repeating generic validation. Example: Prepare initial context for the supplied synthetic 4,000-entry conversation.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this PR makes a focused, useful performance improvement that current main does not contain, with no actionable correctness or security findings. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherSessionManager projects transcript entries into model context; the transcript copier detaches mutable containers, shares immutable payloads, and publishes frozen internal context. flowchart TD
A[SessionManager history] --> B[Model context projection]
B --> C[Transcript copier]
C --> D[Verified plain output]
C --> E[Opaque or symbol output]
D --> F[Trusted freezing]
E --> G[Inspected freezing]
F --> H[Initial model context]
G --> H
Technical reviewBest possible solution: Keep the optimization in the existing copier while retaining inspected freezing for opaque and symbol-bearing SDK graphs. Do we have a high-confidence way to reproduce the issue? Source confirms the redundant generic inspection after cloning; the supplied benchmark reports a failing parent allocation budget, but no code was executed during this read-only review. Is this the best way to solve the issue? The copier already owns container construction, so recording its plain-data guarantee removes redundant work without another cache, wrapper, or publication owner. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 4dbd70ff5fd3. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +21, Tests +58, Other +156. Total +235 across 4 files. Added test files: 0. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. 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 Reviewed November 17, 2026, 8:16 PM ET / November 18, 2026, 01:16 UTC. |
|
Merged via squash.
|
…0888) Let the transcript copier certify its plain output before trusted freezing. Preserve inspected freezing for opaque and symbol-bearing SDK data, mutable detachment, and frozen payload sharing. Synthetic A/A/B construction proof reduces allocation by 38 percent with lower CPU and identical context bytes.
What Problem This Solves
Preparing an agent session from a long conversation clones mutable model-context data, then validates all of those newly created containers again before freezing them. That repeated inspection allocates unnecessary keys and descriptors during attempt preparation and compaction.
User Impact
Long conversations require less allocation and CPU during initial-context preparation. Prompt bytes, writable SDK views, stored snapshot sharing, and opaque SDK values retain their existing behavior. No configuration or migration is required.
Why This Change Was Made
The transcript copier already knows which containers it creates. It now optionally freezes its output, using trusted freezing only when its existing traversal established the plain-data guarantee. Maps, Sets, symbol members, and native structured-clone fallbacks retain inspected freezing. A blanket trusted-freezer substitution would be unsafe for those SDK inputs.
Existing frozen-payload sharing and revision-bound prepared-context reuse remain the owners of those optimizations. Runtime delta is +21 lines to preserve the opaque-value contract; there is no new cache or session-row projection change.
Evidence
Five counterbalanced A1/A2/B process groups on Node 26.12.1/macOS arm64, each with 20 warmups and 100 measured operations. A1 and A2 use the same parent copier/codec. Synthetic workload: 4,000 entries, 1,000 user/tool-call/tool-result/answer turns, 2 KiB tool output, 3,171,895 serialized input bytes. Acceptance was fixed before measurement: B must beat both controls on allocation and CPU, preserve context bytes, and avoid a material latency regression.
Construction wall median/p95: A1 29.719/36.586 ms, A2 30.327/37.498 ms, B 28.073/35.405 ms. Mutable owner median/p95: 21.351/29.054, 21.924/28.027, 19.256/27.374 ms. Frozen owner median/p95: 3.569/4.361, 3.569/4.504, 3.316/4.325 ms. Host one-minute load ranged 4.61–6.66. Allocation uses exact cumulative V8 counters, including later-collected objects; CPU uses thread CPU counters. CPU profiles confirm the removed validating traversal at this call site. Profiled timings are excluded from the table.
Every measured model-context hash matches across all arms. The 20 MB mutable-owner regression budget fails on the parent at 30.19 MB/operation and passes with this change. The SDK construction measurement includes
fromEntriesimport cloning; owner measurements separately cover mutable and deeply frozen branches. These are owner measurements, not whole-Gateway throughput or production deployment claims.Reproduce with
node --import ./scripts/tsx.mjs scripts/perf/session-manager-context-freeze-measure.ts --output <json>. For A, save the parent'ssession-manager-codec.tsandtranscript-snapshot.ts, then pass--codec-file <file> --snapshot-file <file>. Add--max-owner-bytes 20000000for the allocation regression check.Validation: 94 focused tests passed across codec, transcript snapshot, stored-context isolation, retained data, and prompt-prefix stability. New SDK coverage exercises mutable nested arguments, Maps/Sets, typed arrays, symbol members, and frozen payload identity. Codec test file: 30 tests; initial full invocation 43.73 s including compilation and the snapshot shard. Consumer invocation: 62 tests, 135.46 s including compilation. CI timing pending.
Independent local Codex autoreview of the parent-to-working-tree change and full ownership sources is scoped-clean through P2, with no actionable findings. Production and full-tree unused-file scans pass. Browser output-fidelity E2E: 4 passed; Chromium tool-card tests: 3 passed. The first component run could not launch because the pinned headless shell was absent; installing that exact Playwright shell resolved setup, and all component tests then passed. All selected
pnpm check:changedstages now have passing proof: the full invocation found one benchmark-only unique-symbol typing error; the module-namespace fix passed the exact failed scripts typecheck and reran the allocation budget successfully. Every other stage passed in that invocation, including all core/test typechecks, lint, format, export scans and runtime guards. No inherited-main failure is being claimed.