Skip to content

perf(ai): avoid copying Responses history for retention and fingerprints - #184885

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-responses-continuation-commit-bytes-20261026
Oct 26, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-responses-continuation-commit-bytes-20261026

Conversation

@steipete

@steipete steipete commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

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.

Owner flow CPU µs/turn, before → after Sampled KiB/turn, before → after
Continuation commit 410.5 → 207.4 (−49.5%) 483.9 → 109.5 (−77.4%)
Prefix fingerprint 1,340.1 → 1,110.9 (−17.1%) 2,680.2 → 2,136.4 (−20.3%)

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:

  • Retention work-count test fails on base (1,048,728 serialized characters for unchanged 1 MiB text; expected <1,024) and passes on candidate.
  • Prefix work-count test fails on base (one whole-container serialization; expected zero), passes on candidate, and rejects nested edits on the same item. All benchmark digests match.
  • Exact 64 MiB boundary, one-byte overflow after mutating a cached string, JSON hooks/escaping, eviction order, continuation/restart, and resource-retention checks pass.

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 lacks ReplyOperation members. 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 parent b33227f35cceff9294df688ef29e35c4c269585c. 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.

@clawsweeper

clawsweeper Bot commented Oct 26, 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 26, 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-26T18:33:20.720283Z eed376d 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 size: M labels Oct 26, 2026
@steipete
steipete force-pushed the steipete/perf-responses-continuation-commit-bytes-20261026 branch from 9eb3742 to eed376d Compare October 26, 2026 18:31
@clawsweeper

clawsweeper Bot commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This 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.

  • Before: Committing the continuation serializes the full message again for byte accounting.
  • After: The commit reuses the string’s encoded size while preserving the exact 64 MiB retention limit.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Focused, coherent optimization with useful owner-level evidence and no identified defect; supplied proof stops below the shipped entry point and CI failure attribution remains unavailable.
Proof confidence 🦐 gold shrimp (3/6) The ordinary contributor proof gate does not apply to this maintainer-authored PR; supplied evidence covers the changed continuation owner through synthetic macOS benchmarks and reported transport integration.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Long Responses conversations spend avoidable CPU and allocation preparing each turn.
Reason: The maintainer-authored direction has concrete owner-level measurements and preserves existing behavior without adding product settings or another state owner.

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
Reviewed head: eed376db03d1a5c0b754e62a5788ce51d25115c7

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Supplied evidence exercises owner benchmarks and transport integration, rather than a shipped Gateway turn.
Agent review details

How this fits together

The 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]
Loading

Technical review

Best 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

  • Continuation JSON projection keeps the original intent (d181181: Avoid full-history encoding and parsing for comparisons while preserving native JSON semantics.)
  • Persisted continuation fingerprints keeps the original intent (76c9dc1: Use incremental canonical hashing while retaining normalized persisted fingerprint bytes.)
  • Context-usage fingerprint keeps the original intent (8432c13: Bind measured context usage to the admitted request and persisted replay representation.)
  • Continuation retention accounting keeps the original intent (13ed30a: Bound completed baselines by count and serialized content while retaining ordinary idle continuations.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit d181181 adds packages/ai/src/transports/openai-responses-continuation.ts:57 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: d181181113cc; files: packages/ai/src/transports/openai-responses-continuation.ts)
  • Markus Hartung: Raw commit 13ed30a adds packages/ai/src/transports/openai-responses-continuation.ts:28 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 13ed30a6603d; files: packages/ai/src/transports/openai-responses-continuation.ts)

PR surface

Source +24, Tests +115, Other +185. Total +324 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 43 19 +24
Tests 2 117 2 +115
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 185 0 +185
Total 5 345 21 +324

Review metrics

Metric Value Why it matters
Runtime versus regression-test delta Runtime +43/-19, net +24; tests +117/-2, net +115 Runtime growth carries exact per-entry string sizes through existing cleanup; tests protect serialization work, mutation detection, and exact byte-budget boundaries.

Labels

Label changes:

  • add P2: A bounded performance improvement for long Responses conversations, with no demonstrated urgent user-facing regression.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: A bounded performance improvement for long Responses conversations, with no demonstrated urgent user-facing regression.
  • 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.

Reviewed October 26, 2026, 2:45 PM ET / 18:45 UTC.

@steipete
steipete merged commit a4b60a5 into main Oct 26, 2026
113 of 116 checks passed
@steipete

Copy link
Copy Markdown
Contributor Author

Admin-merged at the pinned head eed376db03d1. The only failing job is check-test-types-core-2 (plus ci-gate): TS2345 in src/auto-reply/reply/reply-agent-turn-preparation.test.ts:646. It is inherited from main commit bd6807a336d6, reproduces on the unchanged parent, and is outside this PR's files. The test-only fix #184907 is queued with auto-merge. Every other job passed or was skipped; equivalence was reviewed by the TS session before merge.

@steipete
steipete deleted the steipete/perf-responses-continuation-commit-bytes-20261026 branch October 26, 2026 18:53
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 27, 2026
…nts (openclaw#184885)

* perf(ai): avoid copying Responses history for retention and fingerprints

* test(ai): preserve narrow continuation fixture types
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

scripts Repository scripts size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant