Skip to content

perf(gateway): serve transcript pages as transferred bytes instead of cloning entry objects onto the main thread - #163771

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-history-worker-bytes-20260919
Oct 2, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-history-worker-bytes-20260919

Conversation

@steipete

@steipete steipete commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Concurrent chat history requests still copy worker reply buffers, and smaller pages or pages with profile, automation, or compaction metadata return complete message objects to the Gateway thread.

User Impact

Durable history pages keep their existing JSON, pagination, redaction, sharing, and model-visibility behavior while moving page presentation and serialization into the history worker. No schema, stored transcript, retention, configuration, or update changes are required.

Why This Change Was Made

The existing large-page byte path did not transfer its buffer and the coalesced-read owner cloned that buffer for followers. The worker now transfers its owned UTF-8 array, and coalesced readers share the immutable bytes with separate mutable metadata. Profile avatars and automation labels resolve through their existing shared-state owners before serialization. Legacy compaction token metrics travel as prepared facts. This removes size/content eligibility scans, duplicate host decoration, and duplicate entry capture.

Explicit object adapters, operator model restrictions, cursor deltas, and HTTP/SSE readers retain their existing contracts. Current sessions.messages.subscribe replays pending approvals, not transcript pages; cursor replay is measured separately.

Production delta after the CI repair: 123 additions / 106 deletions, net +17 lines. The 20-line legacy metric adapter preserves the documented pre-removal compaction-checkpoint upgrade contract without transferring stored archive paths or unrelated entry metadata; the rest of production is net -3 lines, including one comment explaining startup ordering.

CI exposed an existing embedded-startup race: model preparation acquired an auth read owner while session maintenance could retire its database. The follow-up moves initial model publication behind maintenance and joins config-listener registration during shutdown. The original CI shard reproduces the failure on the old code; the repaired owner passes it.

Evidence

Small tail pages use 64–66% less sampled main-thread heap allocation and 43–50% less main-thread CPU. Already-encoded large tail pages use 16–24% less CPU, with essentially unchanged sampled heap.

The synthetic Node 26.8.1 Linux rig exercises the actual chat.history handler and production frame serializer with 2,000 entries, 500 append/read rounds, and 3 or 10 readers. Complete content, identity, and order are checked outside the measured region. It does not measure network/socket latency.

The coalesced byte-buffer regression fails on the original owner for both first-reader and last-reader cancellation; retained object-isolation and capacity cases pass. Earlier proof ran on blacksmith-testbox lease tbx_01m3yzvnjat2z8005zms2dfwjs. Final continuation validation is recorded below.

Node 26.8.1 synthetic benchmark measurements
Source message Phase Readers Main heap MB/page Main CPU ms/page p50 ms p95 ms
4 KiB tail-page 3 0.54 → 0.55 6.65 → 5.03 28.48 → 24.14 113.35 → 108.10
4 KiB tail-page 10 0.50 → 0.50 4.02 → 3.38 35.37 → 32.59 108.43 → 114.47
4 KiB append-and-tail-read 3 0.74 → 0.72 6.26 → 6.07 37.14 → 37.98 144.19 → 63.65
4 KiB append-and-tail-read 10 0.55 → 0.55 3.54 → 3.26 48.39 → 47.75 67.91 → 69.80
4 KiB cursor-replay-100-messages 3 8.13 → 8.15 28.48 → 27.66 66.32 → 64.29 105.86 → 94.05
4 KiB cursor-replay-100-messages 10 7.98 → 7.98 26.51 → 28.47 239.58 → 256.99 284.93 → 343.80
256 B tail-page 3 1.48 → 0.54 5.01 → 2.85 22.56 → 17.61 35.68 → 34.81
256 B tail-page 10 1.42 → 0.49 3.37 → 1.68 38.58 → 24.05 66.39 → 36.45
256 B append-and-tail-read 3 1.62 → 0.68 4.10 → 2.49 26.61 → 24.12 45.56 → 44.32
256 B append-and-tail-read 10 1.47 → 0.53 3.38 → 1.82 43.34 → 31.64 59.10 → 48.45
256 B cursor-replay-100-messages 3 5.76 → 5.81 25.36 → 25.43 54.38 → 55.47 87.83 → 82.18
256 B cursor-replay-100-messages 10 5.61 → 5.64 23.67 → 24.43 213.30 → 218.34 243.23 → 263.25

Before → after. Tail and replay phases each contain 100 rounds; append phases contain 500 appends and read rounds, starting from 2,000 entries. Append-phase heap includes append/projection work; CPU/page measures the read group only. Heap is sampled V8 allocation including collected objects and excludes external ArrayBuffer backing storage. Tail pages contain 200 messages; cursor replay contains 100. Each fixture uses deterministic synthetic text, verifies complete message content/identity/order, and checks the final appended head. Session presentation timestamps are excluded only from replay hash comparisons.

The unchanged replay path still allocates roughly 8 MB/page with 4 KiB source messages and remains follow-up work. Timing varies across cells; the 10-reader large-page tail p95 and replay timings did not improve. These are production-handler/frame-serialization measurements, not socket latency or a production deployment.

Validation and Follow-up

All heavy checks ran on provider blacksmith-testbox, profile openclaw-check. All task leases were stopped after use. Source/head checks preceded validation, and all rebases preserved the stable patch identity. The final head is 336edc5af7d0, based on main a97e007542ef; final CI validates that rebased tree.

Lease Command / scope Result Wall time
tbx_01m3z2eeg1mtd27gbq84hamcjd node scripts/check-changed.mjs --staged Passed: production/test types, lint, formatting, and guards 10m38.27s
Same node scripts/run-vitest.mjs <nine focused files> --maxWorkers=1 95 passed; one existing opt-in benchmark skipped 2m36.55s
Same pnpm build Passed: CLI bootstrap imports, SDK exports, built-module checks, and UI budgets 10m52.65s
tbx_01m3z6jqmg51eprvx91c9jst0f Original CI trio plus src/tui/embedded-backend.test.ts, via node scripts/run-vitest.mjs ... --maxWorkers=1 Repaired startup: 166 passed; one existing opt-in benchmark skipped 86.64s wrapper
Same Startup ordering negative control and final TUI suite Old code fails the intended ordering assertion; repaired suite passes all 132 tests 17.82s final wrapper
tbx_01m3z9njqf770skz6ddqprd684 node scripts/check-changed.mjs --staged for the startup repair Passed, including all test type graphs and zero lint warnings/errors 25m16.92s

The nine history files cover transfer/schema behavior, automation labels, worker replies, cursor history, coalesced reads, legacy metrics, CLI-imported anchors, model visibility, and read-only worker boundaries. Changed-file test execution was 0.66s for transfer/schema, 4.18s for automation labels, 7.06s for history-worker behavior, 6.49s for cursor history, and 0.56s for coalesced handoff. The three wrapper shards took 107.14s, 19.19s, and 9.36s. History proof ran on base 2ea5f1b5907a plus the history patch; startup proof ran on published head 9895b4411827 plus the repair.

Initial CI 37062649719 exposed the startup race in checks-node-changed-compact-small-14. Its test step took 173.56s; the failing child shard took 42.73s. The original trio (session-list-viewers.perf, session-message-events, and sessions-list-persisted-worker) reproduced the same auth-owner failure on the old startup method in 42.26s, then passed with the repair. Shutdown coverage also verifies that a listener installed after shutdown begins is unregistered. Final CI 37073163314 passed for 336edc5af7d0: all 76 workflow jobs completed successfully or were intentionally skipped, with no failing jobs. Workflow wall time was 469s (7m49s); aggregate Node-job time, including setup, was 4,026s. The PR-level rollup reported 78 passing checks and no failed or pending checks.

Independent Codex reviews of the history change and final startup repair completed scoped-clean, exit 0, with no findings at the configured P0 threshold. Each received the full 3,600-second engine allowance and returned normally. Fixture lint issues were corrected without suppressions. Native checksum-sync timeouts required a clean replacement lease; no check was bypassed. An initial baseline worktree had incomplete workspace dependency links and failed before collection; it is excluded from regression evidence.

Known limits: the earlier import-closure failure followed the unchanged provider-failover → plugin-loader → auth-store chain and reproduced on the original page kernel. The prior Linux rig measured the actual source handler and production serializer, not a dist-Gateway WebSocket connection or production traffic. Its worktree was removed. Cursor replay still allocates about 8 MB/page with 4 KiB source messages and needs a separate worker-byte cutover; this PR does not claim to improve it.

@clawsweeper

clawsweeper Bot commented Oct 2, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: M labels Oct 2, 2026
@steipete
steipete marked this pull request as ready for review October 2, 2026 20:45
@steipete
steipete enabled auto-merge (squash) October 2, 2026 20:48
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 2, 2026
@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 2, 2026, 6:39 PM ET / 22:39 UTC (Revision 2).

ClawSweeper review

What this changes

The PR prepares and transfers chat-history JSON bytes in the history worker, preserves presentation metadata, and delays local TUI model preparation until startup maintenance finishes.

Merge readiness

✅ Ready for maintainer review

The optimization remains useful: current main and the latest release retain the size/content exclusions and buffer-copying behavior. No actionable correctness or security defect was found in the introduced patch.

Priority: P2
Reviewed head: 336edc5af7d071086282bd4f8b77eef5add5c510

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization with useful production-boundary measurements, compatibility coverage, and no supported blocking findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied Linux benchmark exercises the changed history owner through the actual chat.history handler and production serializer, verifies complete response content, and records lower after-fix allocation and CPU. Socket latency is outside its claim; TUI ordering has supplemental regression evidence. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied Linux benchmark exercises the changed history owner through the actual chat.history handler and production serializer, verifies complete response content, and records lower after-fix allocation and CPU. Socket latency is outside its claim; TUI ordering has supplemental regression evidence. No stored-data contract changes.
Evidence reviewed 9 items Pinned introduction and merge ownership: Inspected the merge-base-to-head diff. The verified test merge has the pinned main parent followed by the exact PR head; its result preserves the unrelated main-branch transport changes.
Still necessary on current main: Current main excludes small pages and pages containing forwarded messages, compaction markers, or profile identities from worker encoding.
Latest-release comparison: The supplied latest release, v2026.9.7, contains the same size/content eligibility restrictions, so it does not supersede this optimization.
Findings None None.
Security None None.

How this fits together

The Gateway history subsystem reads stored conversations, prepares bounded display pages, and returns them to chat clients. This change moves presentation and serialization into its worker while preserving the Gateway’s final access and model-visibility checks.

flowchart LR
  A[Chat history request] --> B[Session selection]
  B --> C[History worker]
  D[Stored transcript] --> C
  E[Profile and automation metadata] --> C
  C --> F[Transferred JSON bytes]
  F --> G[Current access and model checks]
  G --> H[Chat history response]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +17, Tests +195, Docs +9. Total +221 across 20 files.

View PR surface stats
Area Files Added Removed Net
Source 12 123 106 +17
Tests 7 247 52 +195
Docs 1 9 0 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 20 379 158 +221

Review metrics

Metric Value Why it matters
Production growth justification production net +17 lines; tests/support net +195 lines The 20-line legacy metric adapter preserves the existing upgrade contract; the remaining production changes are net −3 lines.

Technical review

Best possible solution:

Keep one worker-owned presentation and serialization path, with explicit object adapters and current permission checks at response publication.

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

Yes, source establishes the copying path and current encoding exclusions; the supplied production-handler benchmark measures their cost. This review did not execute a runtime reproduction.

Is this the best way to solve the issue?

Yes, extending the existing worker and serializer owners removes copying while retaining object adapters, pagination, legacy metrics, and final visibility policy.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a measured history-performance improvement and bounded startup repair without evidence of an urgent user-facing outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The supplied Linux benchmark exercises the changed history owner through the actual chat.history handler and production serializer, verifies complete response content, and records lower after-fix allocation and CPU. Socket latency is outside its claim; TUI ordering has supplemental regression evidence. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied Linux benchmark exercises the changed history owner through the actual chat.history handler and production serializer, verifies complete response content, and records lower after-fix allocation and CPU. Socket latency is outside its claim; TUI ordering has supplemental regression evidence. No stored-data contract changes.

Evidence

What I checked:

  • Pinned introduction and merge ownership: Inspected the merge-base-to-head diff. The verified test merge has the pinned main parent followed by the exact PR head; its result preserves the unrelated main-branch transport changes. (40aa1925f546)
  • Still necessary on current main: Current main excludes small pages and pages containing forwarded messages, compaction markers, or profile identities from worker encoding. (src/gateway/server-methods/chat-history-response-page.ts:119, 9feb364cc960)
  • Latest-release comparison: The supplied latest release, v2026.9.7, contains the same size/content eligibility restrictions, so it does not supersede this optimization. (src/gateway/server-methods/chat-history-response-page.ts:119, c074824a27c9)
  • Buffer and presentation contracts: The worker transfers its encoded ArrayBuffer; coalesced readers share the bytes while cloning mutable metadata. Profile and automation decoration uses the captured shared-state database. Existing final model projection materializes encoded messages when restrictions apply. (src/gateway/session-history-worker-reader.ts:189, 336edc5af7d0)
  • Startup and shutdown repair: Initial model publication follows session maintenance and reads current config. Shutdown awaits projection startup before unregistering the config listener; first-turn admission still awaits both readiness owners. (src/tui/embedded-backend.ts:256, 336edc5af7d0)
  • Production-boundary measurements: The captured PR body reports a Node 26.8.1 Linux benchmark exercising the actual chat.history handler and production frame serializer with 2,000 entries, 3 or 10 readers, and content/identity/order verification. Small tail pages show 64–66% lower sampled main-thread allocation and 43–50% lower CPU. These measurements exclude socket latency and do not claim cursor-replay improvement. Captured body source identity: 07fe8523d63228eac3e83ccee6ea35dc10fa4009764a9d1bb145b57cc2f2109f.

Likely related people:

  • Peter Steinberger: Raw commit df12738 adds src/gateway/server-methods/chat-history-response-page.ts:154 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)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-02T20:51:44.268Z sha 9895b4411827df4259a4d1ab463458111fe3eb5b :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the steipete/perf-micro-history-worker-bytes-20260919 branch from 9895b44 to 336edc5 Compare October 2, 2026 22:33
@steipete
steipete merged commit 2ef9f40 into main Oct 2, 2026
136 of 138 checks passed
@steipete
steipete deleted the steipete/perf-micro-history-worker-bytes-20260919 branch October 2, 2026 22:42
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 3, 2026
… cloning entry objects onto the main thread (openclaw#163771)

* perf(gateway): transfer transcript page bytes from workers

* fix(tui): prepare model runtime after session maintenance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L 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