Skip to content

perf(gateway): transfer chat history activity as JSON bytes - #186071

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-chat-history-allocation-20261027
Oct 27, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-chat-history-allocation-20261027

Conversation

@steipete

@steipete steipete commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Tool-heavy history pages still reconstructed tool activity objects and serialized them on the Gateway main thread even though messages already crossed the worker boundary as JSON bytes.

User Impact

Less main-thread allocation and CPU when opening conversations or paging back through tool-heavy history. Response bytes, paging, omission budgets, model visibility, and internal object-based adapters are unchanged. No configuration, migration, or stored-data change.

Why This Change Was Made

Extend the existing owned JSON-array handoff to activity: encode in the history worker, transfer the buffer, share immutable bytes among coalesced receivers, and forward them through the existing segmented serializer. Mutable page metadata remains isolated. No new cache, serializer, or compatibility path.

Runtime production delta: +21 LOC; the growth carries the second array across the existing typed worker/host boundary and transfer list. Benchmark tooling adds 264 LOC. The removed work is object reconstruction, follower deep clones, and main-thread activity stringification.

Evidence

Acceptance was fixed before candidate runs: byte-identical first/back-page responses; consistently lower main-thread allocation/CPU; report worker CPU too so relocated work is visible. Baseline: 982bf5ee16d1e3f320daeeaf526cb929b00f9704.

Real-worker response-owner benchmark, five counterbalanced pairs, 1,000 iterations per side per shape per mode. Timing and allocation runs were separate. Each page has synthetic text, thinking, tool calls/results, images and activity; 2,000-message inputs exercise the 512 KiB response cap. All four byte-equivalence checks passed in each run.

Input / offset Main allocation B/call Main CPU µs/call Worker CPU µs/call Combined CPU µs/call
200 / 0 427,933 → 9,522 (-97.8%) 432.51 → 131.44 974.48 → 924.70 1406.99 → 1056.14
200 / 4,000 429,121 → 8,736 (-98.0%) 327.25 → 107.19 739.92 → 742.95 1067.17 → 850.14
2,000 / 0 1,172,046 → 8,539 (-99.3%) 777.06 → 155.42 5161.23 → 4919.64 5938.29 → 5075.07
2,000 / 4,000 1,166,230 → 8,931 (-99.2%) 731.74 → 154.83 5591.57 → 5584.93 6323.31 → 5739.77

The real chat.history handler, storage worker, and frame serializer were also profiled on a 2,000-message synthetic transcript (30 warmed calls per side at offset 0 and 400). Sampled main-thread allocation fell 544,707 → 424,354 B/call (−22.1%) for the first page and 507,293 → 376,853 B/call (−25.7%) for back-scroll. Activity stringification/buffer creation and MessagePort deserialization disappeared from the dominant leaf frames. This diagnostic includes test-assertion overhead and excludes socket/auth dispatch; it is not a whole-Gateway latency result.

Reproduction:

node --expose-gc --import ./scripts/tsx.mjs scripts/perf/chat-history-activity-transfer-measure.mjs \
  --base-source <baseline-encoder-with-checkout-relative-imports-resolved.ts> --iterations 200 --pairs 5
# Repeat with --allocation. Current encoder as --base-source provides A/A.
Untraced GC and host context

GC is main-thread only. The short owner runs include minor, major, and incremental GC; major collection counts are too small for percentile gates. Counts below include all kinds; pause maxima are context, not percentile gates. No adverse decision was based on these measurements. RSS includes both benchmark workers and is not a retained-heap comparison. Host load and per-arm heap/RSS are emitted by the script.

Input / offset / pair GC ms/call, base → candidate Collections, base → candidate Max pause ms, base → candidate
200/0/1 0.0769 → 0.0140 32 → 4 2.70 → 1.40
200/0/2 0.0189 → 0.0054 12 → 2 1.45 → 0.98
200/0/3 0.0149 → 0.0000 12 → 0 0.88 → 0.00
200/0/4 0.0624 → 0.0000 12 → 0 5.59 → 0.00
200/0/5 0.0116 → 0.0000 7 → 0 1.05 → 0.00
200/4000/1 0.0050 → 0.0000 6 → 0 0.18 → 0.00
200/4000/2 0.0067 → 0.0000 6 → 0 0.36 → 0.00
200/4000/3 0.0093 → 0.0000 6 → 0 0.59 → 0.00
200/4000/4 0.0086 → 0.0000 6 → 0 0.46 → 0.00
200/4000/5 0.0070 → 0.0000 6 → 0 0.32 → 0.00
2000/0/1 0.0293 → 0.0041 8 → 2 1.69 → 0.63
2000/0/2 0.0518 → 0.0089 26 → 2 1.89 → 1.60
2000/0/3 0.0550 → 0.0128 14 → 2 3.75 → 2.43
2000/0/4 0.0464 → 0.0006 26 → 1 1.43 → 0.11
2000/0/5 0.0195 → 0.0044 14 → 2 0.49 → 0.76
2000/4000/1 0.0139 → 0.0042 8 → 2 0.49 → 0.76
2000/4000/2 0.0212 → 0.0050 8 → 2 1.00 → 0.81
2000/4000/3 0.0111 → 0.0041 8 → 2 0.45 → 0.74
2000/4000/4 0.0132 → 0.0036 8 → 2 0.54 → 0.63
2000/4000/5 0.0117 → 0.0029 6 → 2 0.78 → 0.48

Across 4,000 calls per arm, GC by kind (base → candidate): minor 229 / 97.65 ms → 1 / 0.11 ms; major 1 / 1.09 ms → 12 / 12.31 ms; incremental 1 / 0.13 ms → 12 / 1.61 ms. Total GC fell 98.87 → 14.02 ms; sparse major counts are context only.

Host 1-minute load range: 42.0–53.4. Wall-clock timing was noisy; the reported CPU is per-thread CPU, not wall time.

Validation: coalesced activity-buffer identity regression fails on baseline and passes on candidate. Existing tests cover transferred-buffer detachment, mutable metadata isolation, cancellation, adapter object mode, direct/subscription response bytes, and compressed/uncompressed socket delivery. 101 focused tests (including model-policy and closure guards), targeted core typecheck, changed-file lint/format, and export-name guard passed. Summed reported test time: session-history-worker-runtime.test.ts 0.75 s, serialized-json.test.ts 0.10 s, chat-history-worker.test.ts 10.48 s, session-transcript.worker.schema-freshness.test.ts 2.43 s, ws-connection.serialized-json.test.ts 1.03 s; startup/compilation is additional. The actual storage/handler test verifies worker isolation that a cheaper helper test cannot prove. Test-line ratchet: 6,283,728 / 6,285,000 (1,272 slack); ceiling unchanged.

Full ten-minute Gateway stress omitted under the redundant-work fast-path exception: this extends the existing immutable byte handoff, with actual worker transfer measured and combined CPU accounted for. No production access/load test, external model calls, or full-Gateway performance claim. Broad validation is delegated to PR CI.

Independent subagent review (autoreview route unavailable): clean through P2. The configured Codex autoreview provider did not match the operator configuration; no configuration was changed. Exact-head CI at 45919773c91d567f4ac091bcb0d3f388977ef06c: 66 checks passed, 52 skipped. One execution job failed, with two aggregate gate failures: checks-node-changed. Its Bun shard failed src/gateway/managed-image-actions.e2e.test.ts → “downloads fresh image and document bytes by run scope and rejects stale IDs” with SessionMutationFactsUnavailableError during artifacts.download.

The failed case passed five fixed repetitions on both the exact parent (6492dea35391e5db09a4fa4e3639d5cd832ccc27) and candidate under Node. It also passed five repetitions on each revision using the repository-pinned Bun. Thus all 20 fixed repetitions passed across the two revisions and two runtimes. Command: OPENCLAW_VITEST_RUNTIME=<node|bun> node scripts/run-vitest.mjs src/gateway/managed-image-actions.e2e.test.ts --maxWorkers=1 --repeats 4 -t 'downloads fresh image and document bytes'. These are repetitions, not failure retries.

Source tracing: artifact/session-fact metadata reads can execute the edited shared worker transfer-list callback, but both versions return an empty transfer list for those responses. Artifact reads bypass the changed history RPC encoder, handler, and coalesced-page clone branch. No changed artifact or session-authorization semantics were found; the original throwing condition remains unresolved. This evidence does not establish an inherited defect or make CI green. No CI rerun was requested, and this PR remains unmerged for the lead's review.

Reuse the history worker serialized-array handoff for tool activity, preserving paging, budgets, model policy and object adapters. Avoid main-thread activity object reconstruction, follower clones and JSON encoding.
@clawsweeper

clawsweeper Bot commented Oct 27, 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 27, 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-27T15:14:13.726097Z 4591977 PR opened
ℹ️ 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 gateway Gateway runtime scripts Repository scripts size: M labels Oct 27, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. 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. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 27, 2026
@clawsweeper

clawsweeper Bot commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR transfers prepared chat-history activity as JSON bytes alongside messages to reduce Gateway main-thread allocation and serialization.

Example: Opening a tool-heavy conversation with 2,000 source messages and a 512 KiB response budget.

  • Before: The worker returns activity objects that the Gateway reconstructs, clones for coalesced readers, and serializes.
  • After: The worker transfers activity JSON bytes that readers share and the existing serializer forwards with unchanged response content.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused optimization with credible production-owner measurements and useful boundary coverage; confidence is limited by harness-scoped performance evidence and unresolved CI attribution.
Proof confidence 🦐 gold shrimp (3/6) The ordinary contributor proof gate is waived by the supplied maintainer-authored classification. Available evidence exercises the real response encoder, worker transfer, storage worker, handler, and serializer; socket/auth dispatch is outside the reported performance measurements.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Opening and paging through tool-heavy conversations spends avoidable Gateway main-thread CPU and allocation on activity objects.
Reason: The supplied measurements support the narrow optimization, and the maintainer-authored direction extends the feature owner's existing design.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR removes measurable history-processing overhead using existing owners, with no actionable correctness or security findings; exact-head CI remains unresolved.

Priority: P2
Reviewed head: 45919773c91d567f4ac091bcb0d3f388977ef06c

Before merge

None.

Findings

None.

Agent review details

How this fits together

The history worker reads and prepares transcript pages, then passes bounded responses to the Gateway handler and WebSocket serializer for conversation clients.

flowchart LR
  A[History request] --> B[History worker]
  B --> C[Bounded page preparation]
  C --> D[Transferred message and activity bytes]
  D --> E[Gateway history handler]
  E --> F[Segmented serializer]
  F --> G[Conversation client]
Loading

Technical review

Best possible solution:

Extend the existing immutable byte handoff to activity while preserving bounded responses, object adapters, and publication policy.

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

Current-main source shows activity retained as objects across worker replies and follower cloning; supplied benchmarks quantify that overhead, but this review ran no target code.

Is this the best way to solve the issue?

The patch is a small, coherent extension of the established byte-transfer owner, with no new cache, serializer, persisted representation, or competing policy.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 2bddc783d2a8.

Provenance checked

  • Worker-prepared response encoding keeps the original intent (df12738: Prepare bounded history JSON in the worker while preserving response bytes, policy projection, and object-consuming adapters.)
  • Coalesced immutable byte sharing keeps the original intent (2ef9f40: Transfer owned message buffers and share immutable bytes among readers while isolating mutable metadata.)
  • Worker transfer list and compressed segments keeps the original intent (3ef6f14: Transfer exact worker-produced buffers and retain negotiated compression behavior without changing decoded frames.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit df12738 adds src/gateway/server-methods/chat-history-response-page.ts:120 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: df1273803188; files: src/gateway/server-methods/chat-history-response-page.ts)

PR surface

Source +21, Tests +37, Other +264. Total +322 across 11 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 5 29 8 +21
Tests 5 43 6 +37
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 264 0 +264
Total 11 336 14 +322

Review metrics

Metric Value Why it matters
Runtime versus supporting code Runtime +29/-8 LOC; tests +43/-6 LOC; benchmark tooling +264 LOC. Runtime growth carries a second array through existing boundaries; test extensions cover distinct transfer, sharing, adapter, serialization, and transport contracts.

Labels

Label changes:

  • add P2: A bounded performance improvement for tool-heavy conversation history, 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 tool-heavy conversation history, 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.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Establish the cause of the managed-image E2E failure and obtain a passing exact-head CI gate.

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 27, 2026, 11:27 AM ET / 15:27 UTC.

@steipete

Copy link
Copy Markdown
Contributor Author

Landing at the pinned head 45919773c91d567f4ac091bcb0d3f388977ef06c. The only red is one unrelated end-to-end test.

checks-node-changed (and openclaw/ci-gate, which aggregates it) failed on src/gateway/managed-image-actions.e2e.test.ts > managed image actions Gateway E2E > downloads fresh image and document bytes by run scope and rejects stale IDs with SessionMutationFactsUnavailableError.

That test covers managed image/document artifact downloads. This PR changes only how chat.history activity bytes move from the transcript worker to the response frame. Across 20 focused repetitions, the test passed on both the parent and this head, under Node and Bun. All other checks passed, including core typecheck, lint, and the changed-test shards.

A separate root-cause lane owns the flake. No CI reruns were used.

@steipete
steipete merged commit b92d0bd into main Oct 27, 2026
143 of 148 checks passed
@steipete
steipete deleted the steipete/perf-chat-history-allocation-20261027 branch October 27, 2026 16:15
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 28, 2026
…#186071)

Reuse the history worker serialized-array handoff for tool activity, preserving paging, budgets, model policy and object adapters. Avoid main-thread activity object reconstruction, follower clones and JSON encoding.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime 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