Repository navigation
perf(ai): avoid copying Responses history for retention and fingerprints - #184885
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. |
9eb3742 to
eed376d
Compare
|
Codex review: needs maintainer review before merge. What this changesThis PR reuses encoded string sizes and existing JSON projection and hashing helpers to reduce Responses continuation allocations. Example: A follow-up turn retains an unchanged 1 MiB user message.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this PR open: it removes measurable redundant work through existing owners, and no actionable introduced defect was found; exact-head CI remains unresolved. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherThe AI Responses transport receives prepared requests and completed responses, retains bounded continuation baselines, and computes fingerprints consumed by reasoning replay and context-usage accounting. flowchart TD
A[Prepared Responses request] --> B[Continuation owner]
C[Completed provider response] --> B
B --> D[Bounded baseline and string sizes]
A --> E[JSON projection and canonical hash]
C --> E
E --> F[Replay and context usage metadata]
Technical reviewBest possible solution: Retain this focused optimization within the existing continuation and canonical-hash owners, preserving exact accounting and replay fingerprints. Do we have a high-confidence way to reproduce the issue? Base source directly shows full-state serialization on each commit and full-prefix JSON encoding/parsing for fingerprints; the PR supplies before/after owner measurements and reports base-failing work-count regressions, which were not executed during this read-only review. Is this the best way to solve the issue? The patch follows the smallest complete approach: reuse the existing JSON projection and streaming hash writer, and carry exact immutable-string sizes with the existing baseline instead of caching mutable history items. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 03b45525d9cc. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +24, Tests +115, Other +185. Total +324 across 5 files. Added test files: 0. View PR surface stats
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 October 26, 2026, 2:45 PM ET / 18:45 UTC. |
|
Admin-merged at the pinned head |
…nts (openclaw#184885) * perf(ai): avoid copying Responses history for retention and fingerprints * test(ai): preserve narrow continuation fixture types
What Problem This Solves
Long Responses conversations repeatedly copy the full history while accounting continuation retention and computing replay fingerprints, adding CPU and allocation on every turn.
User Impact
Lower per-turn CPU and allocation with unchanged requests, continuation decisions, persisted fingerprint bytes, and the exact 64 MiB / 1,000-entry cache limits. No configuration or migration is required.
Why This Change Was Made
Continuation entries now carry exact encoded byte counts for their current immutable string values. Commit reuses those counts, serializes only a small structural skeleton, and replaces the per-entry map on each commit. Changed strings are measured again; hooks still run through native JSON, and expiration/eviction/session cleanup release the counts with the baseline. Fingerprints reuse the existing JSON-semantic projection instead of serializing and parsing the whole conversation; context hashing uses the existing streaming canonical writer.
The change adds 24 net runtime lines to retain exact accounting and its lifecycle; there is one counting path. A standalone benchmark is separate tooling. Mutable history-item/conversion caching is deliberately omitted: converters reconstruct items and there is no immutable-item or revision contract. Prefix hashing still visits all history; this removes redundant serialization without changing persisted digests.
Evidence
Synthetic owner benchmark: 200-turn conversations with user messages, assistant tool calls, tool results and ~4 KiB added text/turn. Five alternating base/candidate pairs, 2,000 iterations per process / 10,000 iterations per arm per flow, with separate untraced timing and sampled-allocation processes. Base
e923309c2978268898f7b57a11879fdfa174ca38; Node 26.12.1, macOS. CPU is main-thread CPU, not loaded-host wall time. Allocation includes collected objects at 32 KiB sampling.Timing-arm GC was 0.0281 → 0.0101 ms/turn for commit and 0.1512 → 0.1890 ms/turn for prefix. The latter is +0.0378 ms/turn, below the 1 ms/op absolute materiality threshold, with allocation and CPU both improved. All collections in the five main comparison pairs were scavenges; these short owner runs make no major-GC/promotion claim. Paired maximum GC pauses (base/candidate, ms): commit 2.44/20.16, 19.25/13.04, 25.66/13.83, 19.58/5.23, 18.58/0.30; prefix 30.69/12.74, 72.89/35.78, 16.74/83.96, 56.36/53.07, 77.47/72.60. One prefix pair crossed the maximum-pause safeguard (16.74 → 83.96 ms). Four matched untraced A/A pairs were clean: maxima 3.27/2.14, 3.36/1.95, 2.47/2.26, and 2.37/4.18 ms, with 146 scavenges per arm and 1–2 major collections (major tails remain context-only). Their host load had fallen to 33–38, so they cannot attribute the earlier loaded-host spike to the code. Following the mixed-sign rule, one additional reversed A/B pair was declared before running: maximum 14.60 → 0.38 ms at host load ~26, total GC 65.45 → 34.98 ms, with 146 vs 175 scavenges and 2 vs 0 majors. Across all six A/B timing pairs, the signed mean maximum-pause delta is −1.70 ms (−3.8%); no original pause was removed. The short-window maximum-pause result remains load-sensitive context, not evidence of a repeatable regression.
End-of-timing-process RSS averaged 147.1 → 115.7 MiB (commit), 233.1 → 153.7 MiB (prefix); heap used was 25.6 → 30.1 MiB and 68.1 → 36.9 MiB respectively, without a post-run forced GC. Endpoint heap is not retained-heap proof; the existing weak-reference lifecycle test passes. Per-arm 1-minute host loads were 68.5–71.6 for commit and 65.2–73.9 for prefix. The benchmark reports every arm's CPU, GC, heap/RSS, host load, source checksum and digest.
Reproduce with
node --expose-gc --import ./scripts/tsx.mjs scripts/perf/responses-continuation.ts --flow commit --conversations 10, then--flow prefix, and repeat both with--allocation. Script header documents alternate-module baseline usage. Commit measurements carry the cache across turns and use explicit previous-response IDs to isolate commit from history validation. They are not Gateway latency measurements. Validation is scoped to owner benchmarks and transport integration: no Gateway load campaign, production-server access, or sessions.list/event-loop latency claim.Regression proof:
Validation: 104 focused tests across continuation, context-usage/prompt observer, retention, client continuation and real SSE/WebSocket continuation integration; 26 import/wrapper closure checks; export collision check; changed-file formatting/type-aware lint. Focused integration batch took 193 s including compiled-fixture preparation (test execution ~1 s); owner batch 7.8 s and closure batch 127 s. An earlier local attempt failed because formatting changed source during compiled-fixture preparation; rerunning on frozen source passed. No Testbox/Crabbox lease or broad local suite/build was used.
Independent subagent review (autoreview route unavailable): the configured helper rejected the requested provider route because it did not match the operator configuration. The authorized fresh-context fallback returned no P2+ findings. CI validation will be attached to the exact PR head.
Exact-head CI status
Head
eed376db03d1a5c0b754e62a5788ce51d25115c7: the two PR-caused fixture typing errors from the first CI run are fixed, independently reviewed, and passing their CI checks. The package test-type leaf also passes locally; the 48-test owner file passes after the correction. Production code and benchmark workload are unchanged.The remaining type failure is inherited: check-test-types-core-2 reports TS2345 at
src/auto-reply/reply/reply-agent-turn-preparation.test.ts:646, where the mocked operation lacksReplyOperationmembers. A single-file typecheck, retaining the owning shard's ambient declarations, returns exit 2 with byte-identical diagnostics on this head and the exact main parentb33227f35cceff9294df688ef29e35c4c269585c. For the baseline run all five PR paths were replaced with their main-parent contents, then restored; the worktree is clean. The failed fixture and its owner are untouched by this PR. No CI rerun was requested to chase green. All other substantive CI jobs passed on this exact head. The aggregate gate remains red because of this inherited failure; this is not a claim of green CI.