Repository navigation
perf(agents): reuse frozen Responses reasoning serialization - #193553
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. |
721faeb to
6f50717
Compare
|
Codex review: needs maintainer review before merge. What this changesThis PR reuses serialized deeply frozen Responses reasoning items while preserving existing context fingerprints. Example: Repeated context accounting for 2,000 history items containing 400 frozen reasoning blocks of approximately 4 KiB each.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this is a useful, focused optimization of work still repeated on main, with no actionable correctness or security findings. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherResponses transports record measured context usage against replayed conversation history; later admission validates that fingerprint before using the measurement instead of a conservative estimate. flowchart TD
A[Responses transport] --> B[Context usage owner]
C[Replayed history] --> B
B --> D[Continuation prefix hash]
B --> E[Weak reasoning serialization cache]
D --> F[Persisted context fingerprint]
E --> F
F --> G[Context admission validation]
Technical reviewBest possible solution: Retain this owner-local optimization and merge after the existing required CI gates pass. Do we have a high-confidence way to reproduce the issue? Current-main source unconditionally copies and serializes reasoning on every fingerprint calculation; the PR supplies comparative measurements and a reported red/green encoding-count regression, which were inspected but not executed during this read-only review. Is this the best way to solve the issue? The change uses the existing accounting owner, preserves canonical hash bytes and mutable ordering, and adds only weak source-identity state; no smaller complete replacement was identified. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against c4d8a5ae1715. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +24, Tests +142, Other +225. Total +391 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. Review metrics
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 5, 2026, 10:42 AM ET / 15:42 UTC. |
…w#193553) * perf(agents): reuse frozen Responses reasoning serialization * perf(agents): type Responses benchmark output metadata
What Problem This Solves
Long OpenAI Responses conversations repeatedly serialize encrypted reasoning when binding measured context usage to replayed history, even when the historical items are unchanged.
User Impact
Less allocation and main-thread CPU during context accounting. Provider requests, persisted fingerprint bytes, and context-usage validation remain unchanged; no migration or operator action is needed.
Why This Change Was Made
Reuse each deeply frozen reasoning item's stable serialized representation, keyed weakly by the complete source item. Mutable input still takes a fresh copy before prefix evaluation and serializes afterward, preserving payload-hook getter ordering. One hashing path preserves the existing SHA-256 input exactly and removes per-call
flatMaparrays, repeated frozen reasoning copies/encoding, generic outer serialization, and unused byte-weight accounting.The existing digest places the continuation-prefix hash before reasoning, so appends still require hashing historical reasoning bytes. Changing that format would invalidate persisted fingerprints; this change only removes repeated preparation of those bytes. The necessary production delta is +24 lines (+33/−9) for weak identity reuse and mutable-input ordering under that persisted contract.
There is a retention tradeoff: with 2,000 items / 400 reasoning blocks of 4 KiB, the cache adds approximately 1.62 MiB of live encoded text. All 2,000 source objects were collectible after release, and post-release heap was effectively unchanged (20.18 MiB on both arms).
Evidence
Measured base:
6d49ef1c4b364218f2470df9b069c7a1e5b020d0.Acceptance rule: preserve every digest byte, eliminate repeated frozen ciphertext encoding, improve owner allocation/main-thread CPU across five alternating samples per arm, and prove weak-key release. Fixtures contain frozen user messages, tool calls/results, assistant messages, reasoning and a compaction item; request arrays are fresh. Preparation is excluded; allocation and timing use separate processes. Each table cell is the median of 5 × 1,000 requests per side per mode, Node 26.12.1.
At 2,000 items, untraced GC time per 1,000 requests fell from 17.06 to 0.55 ms; collection counts were 177–183 vs 3 (all scavenges), and observed maximum pauses were 33.88 vs 0.29 ms. GC sample counts are too low for tail-percentile claims. Post-run RSS ranged 161.96–164.36 vs 125.45–129.29 MiB. Host one-minute load ranged 21.44–28.05 vs 20.44–26.79. No adverse metric was used to reject a candidate, so no A/A rejection controls were needed.
#193515 is included in the measured base and does not remove this residual. Instrumented owner probes showed 100% warm prefix checkpoint hits with fully frozen identity-stable histories while context allocation still scaled with reasoning size. Real conversion probes also found early mutable items can stop the checkpoint chain (1/84 retained items without an inline system message, 0/85 with one); the system message is rebuilt on conversion. This change does not claim to fix that separate prefix-cache limitation.
Reproduce using
scripts/perf/responses-context-usage.ts(usage and baseline-module recipe in its header), with--items 200,1000, and2000; run timing,--allocation, and--retentionseparately. The baseline and candidate produced identical persistedcontextUsagein every arm.Regression:
does not re-encode frozen reasoning across interleaved context-usage recordingsfails on the base with four repeated ciphertext encodings instead of zero, passes with the change, and still requires mutable clones to encode. Differential proof covers IDs/status omission, compaction, appended reasoning, edits/reordering, frozen interleaving, Unicode, and mutable getter ordering. The exact +142 test-line allocation protects the persisted-byte and work-reuse contracts.Validation: 65 focused tests passed across the context observer, provider-compaction replay, admission replay, and prompt-prefix stability files. Root-test, standalone-script, and package-test typechecks passed. Export-name guard and both import-closure guards passed (23 tests). Scoped lint and formatting passed. The original lint preparation was interrupted by probe-file cleanup; the completed retry passed. Independent subagent review (autoreview route unavailable): clean P0/P1/P2 review of the complete local candidate against
6d49ef1c4b364218f2470df9b069c7a1e5b020d0, using an isolated fresh context containing only the diff, source, and proof brief. Autoreview refused the requested provider route because it did not match operator configuration; no configuration was changed. All reported base/candidate digest values were compared separately and matched.No Gateway or live-server stress was run: this uses the requested fast-path owner-proof exception for deterministic duplicate serialization removal. Whole-Gateway CPU, allocation rate, GC s/min, event-loop p99, sessions.list p99 and server-handler latency remain unmeasured; these owner measurements are not end-to-end claims. PR CI owns broad validation.
CI follow-up: the first
check-test-typesrun caught missing requiredid/statusmetadata on the benchmark assistant-output fixture. Added that metadata, reranpnpm tsgo:scriptsandpnpm tsgo:test:rootsuccessfully, and obtained a clean independent P0/P1/P2 review of the two-line fixture repair. The corrected fixture produces exactly the original measuredcontextUsagedigest; its 2,000-item smoke run used 776.5 µs/request. Production code is unchanged by this repair.