Skip to content

improve: reduce per-turn work after Responses compaction - #200715

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-responses-continuation-equality-alloc-20260919
Nov 17, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-responses-continuation-equality-alloc-20260919

Conversation

@steipete

@steipete steipete commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Long OpenAI Responses conversations repeatedly deep-compare unchanged history after compaction. A reparsed checkpoint forces the entire prefix through normalization and projected JSON comparison, creating avoidable allocation and CPU work on every turn.

User Impact

Responses turns after compaction require less local CPU and allocation. Request bytes, continuation decisions, persisted context hashes, and mutable payload-hook behavior remain unchanged. No configuration or migration is required.

Why This Change Was Made

Compaction already publishes immutable per-item identities, which incremental prefix hashing consumes. Continuation comparison now consumes the same owner-provided fact. Ordinary frozen items retain reference comparison; edits, opaque/toJSON values, and sparse arrays retain full validation. The comparison lives in the existing JSON projection module to keep the continuation owner within its file-size limit.

No new cache or fingerprint algorithm. Production delta: +19 lines; focused test delta: +41 lines. The remaining growth implements the immutable identity check and its comparison boundary. This change does not claim to remove full hashing on cold or mutable inputs.

Evidence

A/A/B acceptance was declared in the committed workload before measurement: identical continuation decisions, request deltas and persisted contextUsage/prefixHash; candidate beats both A controls for CPU and allocation on compacted histories, without regressing ordinary history.

Four synthetic histories, eight appended assistant/user turns each, 2,000-entry scale, including reasoning and tool-call/results. Five counterbalanced samples per arm; 640 timed decisions and 96 allocation decisions per sample. V8 sampling includes objects collected by both major and minor GC. Conversion is outside owner timing; these are owner measurements, not Gateway latency or provider cache-hit claims.

| History | Metric per request | A1 | A2 | B |
|---|---|---:|---:|---:|---:|
| Plain | CPU ms, median | 0.17225 | 0.16628 | 0.13627 |
| Plain | Allocation MB, median | 0.00577 | 0.00577 | 0.00651 |
| Checkpoint | CPU ms, median | 2.17330 | 2.14643 | 0.32075 |
| Checkpoint | Allocation MB, median | 2.81234 | 2.80931 | 0.09547 |
| Complete window | CPU ms, median | 1.59184 | 1.57363 | 0.31657 |
| Complete window | Allocation MB, median | 0.78802 | 0.78789 | 0.06439 |

All arms had identical 100% continuation decision hits. Per 32 requests, recursive equality calls fell from 300,384 to 512 for checkpoint histories and from 450,464 to 512 for complete windows. Plain history stayed at 512. Warm historical prefix serialization was already avoided on the baseline; only new response output is encoded by the prefix hasher. Persisted hash parity includes compaction, reasoning and tool history; existing tests cover toJSON evaluation ordering.

The committed workload is scripts/perf/responses-continuation-equality-measure.ts (run under node --expose-gc --import ./scripts/tsx.mjs, with adjacent baseline continuation and context-usage modules supplied through --baseline and --baseline-context). The context baseline must import the baseline continuation module. The allocation/work-count guard fails on the original owner and passes with this change. CPU profiling was also collected.

  • 78 focused tests passed: retained compaction, prompt/context usage, reasoning updates, and real SSE/WebSocket continuation integration. Five-file command: 38.01 s including compiler preparation; changed test file under 0.1 s.
  • Chromium transcript-boundary test: 1 passed. Models/reasoning UI E2E: 9 passed (25.11 s). No UI import of the touched transport modules was found; no new Node-only import was added.
  • Codex autoreview through P2: final production logic scoped-clean. The first benchmark concern was checked against the context-usage owner: the compared replay metadata contains the persisted prefixHash. The final review includes that owner.
  • Final pnpm check:changed passed. Exact-head CI attempt 2 passed; attempt 1 failed before tests because the Git PPA returned HTTP 503, and one failed-only retry succeeded. The strengthened fixture also passed its targeted script typecheck and lint.
Five-sample spread and host load
History/arm CPU ms min / p95 Wall ms min / p95 Allocation MB min / p95
plain/A1 0.1540 / 0.1764 0.1254 / 0.1491 0.0054 / 0.0079
plain/A2 0.1620 / 0.1807 0.1380 / 0.1473 0.0054 / 0.0065
plain/B 0.1311 / 0.1559 0.1173 / 0.1766 0.0062 / 0.0069
checkpoint/A1 2.1354 / 2.2205 1.9408 / 2.0285 2.7966 / 2.8249
checkpoint/A2 2.1265 / 2.2026 1.9442 / 1.9977 2.8021 / 2.8290
checkpoint/B 0.3114 / 0.3238 0.3027 / 0.3138 0.0936 / 0.0968
window/A1 1.5713 / 1.7261 1.4540 / 1.6151 0.7733 / 0.7945
window/A2 1.4745 / 1.6983 1.3689 / 1.5905 0.7770 / 0.7926
window/B 0.2891 / 0.3277 0.2275 / 0.2632 0.0633 / 0.0658

Nearest-rank p95 is the maximum for five samples. Node v26.12.1; observed one-minute load 9.81–12.04

The final workload supplies provider replay provenance for synthetic reasoning and asserts that reasoning survives conversion; its final A/A/B results above supersede the earlier fixture.

Ordinary-history sampled allocation moved from 5.77/5.77 KB to 6.51 KB per request (+0.74 KB, with overlapping five-sample control ranges); work counts stayed identical and CPU improved. No ordinary-history allocation reduction is claimed. Compacted-history B beats both A controls by a wide margin.

Avoid deep projected-JSON comparison of unchanged compacted prefixes by consuming the immutable identity already published by the compaction owner. Preserve persisted hashes and mutable hook semantics. Synthetic reasoning/tool histories retain identical continuation decisions while reducing per-turn CPU and allocation.
@clawsweeper

clawsweeper Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: M labels Nov 17, 2026
@steipete
steipete marked this pull request as ready for review November 17, 2026 17:24
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper review

Please review final head d45ad4d. Focus on the existing compaction publication identity preserving continuation decisions, mutable/toJSON/sparse fallback behavior, and the synthetic benchmark's byte-identical persisted contextUsage proof. Local tests, check:changed, and Codex P2 autoreview are complete.

@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T17:26:51.226842Z d45ad4d Draft marked ready
ℹ️ 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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 17, 2026
@clawsweeper

clawsweeper Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR reuses compaction-published immutable identities to avoid repeatedly comparing unchanged Responses history.

Example: An unchanged compacted conversation receives eight appended turns at a 2,000-entry scale.

  • Before: The reported checkpoint workload spends about 2.15 ms per request normalizing and comparing history.
  • After: The reported candidate spends about 0.32 ms while preserving continuation decisions, request deltas, and context hashes.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation is focused and appears correct; evidence establishes synthetic owner-level gains, while broad exact-head validation remains incomplete.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored internal optimization supplies synthetic production-owner measurements and parity assertions; it claims no changed user-visible output or Gateway latency result.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Long compacted Responses conversations repeatedly spend local CPU and allocate temporary objects comparing unchanged history.
Reason: The maintainer-authored direction removes measured redundant work using an existing ownership contract, with no new configuration or persistent state.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR makes a useful, focused performance improvement with no concrete correctness or security findings; exact-head CI is still incomplete.

Priority: P2
Reviewed head: d45ad4d0ab3d9b2a48efeeb1bb79bb3921c82a0d

Before merge

None.

Findings

None.

Agent review details

How this fits together

Responses conversion publishes immutable request items; continuation validation compares prior and current histories and emits either a delta referencing the previous response or the full request.

flowchart TD
  A[Conversation history] --> B[Conversion and compaction]
  B --> C[Immutable input identities]
  C --> D[Continuation validation]
  D --> E[Delta or full request]
  B --> F[Context usage fingerprint]
Loading

Technical review

Best possible solution:

Retain the existing compaction identity owner and consume its immutable publication facts while preserving the complete mutable-history fallback.

Do we have a high-confidence way to reproduce the issue?

Source confirms that reparsed compaction items miss the prior reference-only shortcut; the supplied A/A/B measurements exercise that owner path, but no target code was executed during this read-only review.

Is this the best way to solve the issue?

This is the smallest complete approach: reuse the producer's existing immutable identities, retain historical comparison when identity cannot establish equality, and leave persisted hashing unchanged.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 9aed3620c57f.

Provenance checked

  • Immutable continuation shortcut keeps the original intent (2896c3f: Avoid rebuilding historical normalization and ownership maps for producer-owned immutable prefixes while preserving mutable fallback checks.)
  • Compaction publication identities keeps the original intent (fix: reduce repeated history hashing in Responses requests #189796: Publish data-free identities for reparsed immutable compaction entries so exact persisted hashes can reuse prepared work.)
  • Projected JSON comparison and evaluation order keeps the original intent (41ffd20: Compare normalized JSON without generic comparator allocation while preserving mutable payload semantics and left-before-right projection.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 41ffd20 adds packages/ai/src/transports/openai-responses-json-projection.ts:94 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 41ffd20207ea; files: packages/ai/src/transports/openai-responses-json-projection.ts)
  • Markus Hartung: Raw commit 906dccd adds packages/ai/src/transports/openai-responses-continuation.ts:74 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 906dccdd6aeb; files: packages/ai/src/transports/openai-responses-continuation.ts)

PR surface

Source +19, Tests +41, Other +313. Total +373 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 41 22 +19
Tests 1 41 0 +41
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 313 0 +313
Total 4 395 22 +373

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 coverage Production net +19 lines; tests +41 lines The growth extends the existing immutable-prefix check and covers unchanged, edited, opaque, and sparse histories without adding state or another comparison owner.

Labels

Label changes:

  • add P2: This is a bounded CPU and allocation improvement for long compacted Responses conversations.
  • 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 is a bounded CPU and allocation improvement for long compacted Responses conversations.
  • 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 17, 2026, 12:30 PM ET / 17:30 UTC.

@steipete
steipete merged commit 6d381eb into main Nov 17, 2026
249 of 254 checks passed
@steipete
steipete deleted the steipete/perf-micro-responses-continuation-equality-alloc-20260919 branch November 17, 2026 17:55
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
Avoid deep projected-JSON comparison of unchanged compacted prefixes by consuming the immutable identity already published by the compaction owner. Preserve persisted hashes and mutable hook semantics. Synthetic reasoning/tool histories retain identical continuation decisions while reducing per-turn CPU and allocation.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. scripts Repository scripts size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant