Skip to content

perf(agents): reuse frozen Responses reasoning serialization - #193553

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-responses-context-fingerprint-20261105
Nov 5, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-responses-context-fingerprint-20261105

Conversation

@steipete

@steipete steipete commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

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 flatMap arrays, 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.

History items Allocation bytes/request, base → candidate Main-thread CPU µs/request, base → candidate
200 465,751 → 25,172 (-94.6%) 243.5 → 89.5 (-63.2%)
1,000 2,234,357 → 41,286 (-98.2%) 705.6 → 409.4 (-42.0%)
2,000 4,452,454 → 67,236 (-98.5%) 1,384.8 → 788.1 (-43.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, and 2000; run timing, --allocation, and --retention separately. The baseline and candidate produced identical persisted contextUsage in every arm.

Regression: does not re-encode frozen reasoning across interleaved context-usage recordings fails 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-types run caught missing required id/status metadata on the benchmark assistant-output fixture. Added that metadata, reran pnpm tsgo:scripts and pnpm tsgo:test:root successfully, and obtained a clean independent P0/P1/P2 review of the two-line fixture repair. The corrected fixture produces exactly the original measured contextUsage digest; its 2,000-item smoke run used 776.5 µs/request. Production code is unchanged by this repair.

@clawsweeper

clawsweeper Bot commented Nov 5, 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 Nov 5, 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-11-05T15:28:45.969778Z 6f50717 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 Nov 5, 2026
@steipete
steipete force-pushed the steipete/perf-responses-context-fingerprint-20261105 branch from 721faeb to 6f50717 Compare November 5, 2026 15:26
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Nov 5, 2026
@clawsweeper

clawsweeper Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

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

  • Before: Each recording copies and encodes the historical reasoning again.
  • After: Warm recordings reuse the encoded reasoning strings and produce the same fingerprint.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Focused implementation with meaningful owner-level measurements and regression contracts; evidence remains limited to the accounting owner rather than a shipped Gateway flow.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR records an explicit owner-proof exception: the committed benchmark exercises recordResponsesContextUsage with mixed frozen histories, reports preserved digests and lower preparation cost, and checks weak-key release; whole-Gateway performance remains unmeasured.
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 main-thread CPU and allocation preparing unchanged encrypted reasoning for context accounting.
Reason: The maintainer-authored direction is established, the measured owner gains are substantial, and the live-memory tradeoff is explicitly accepted.

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
Reviewed head: 6f50717d17a85c1eba50b90c1d8904b5c7279333

Before merge

None.

Findings

None.

Agent review details

How this fits together

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

Technical review

Best 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

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 8432c13 adds packages/ai/src/transports/openai-responses-context-usage.ts:50 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 8432c139340a; files: packages/ai/src/transports/openai-responses-context-usage.ts)

PR surface

Source +24, Tests +142, Other +225. Total +391 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 33 9 +24
Tests 1 143 1 +142
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 225 0 +225
Total 4 401 10 +391

Preflight source

Source 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

Metric Value Why it matters
Production versus regression-test growth Runtime +33/-9 lines; tests +143/-1 lines Runtime growth supports weak reuse and preserves mutable evaluation order; the tests protect persisted-byte parity and the distinct work-reuse invariant.

Labels

Label changes:

  • add P2: This reduces repeated CPU and allocation in long Responses conversations without changing user-facing contracts or addressing an urgent outage.
  • 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: This reduces repeated CPU and allocation in long Responses conversations without changing user-facing contracts or addressing an urgent outage.
  • 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 November 5, 2026, 10:42 AM ET / 15:42 UTC.

@steipete
steipete merged commit ffc2a0f into main Nov 5, 2026
120 of 122 checks passed
@steipete
steipete deleted the steipete/perf-responses-context-fingerprint-20261105 branch November 5, 2026 15:52
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 6, 2026
…w#193553)

* perf(agents): reuse frozen Responses reasoning serialization

* perf(agents): type Responses benchmark output metadata
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant