Repository navigation
perf(gateway): transfer chat history activity as JSON bytes - #186071
Conversation
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.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex review: needs maintainer review before merge. What this changesThis 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.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe 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]
Technical reviewBest 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
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +21, Tests +37, Other +264. Total +322 across 11 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 27, 2026, 11:27 AM ET / 15:27 UTC. |
|
Landing at the pinned head
That test covers managed image/document artifact downloads. This PR changes only how A separate root-cause lane owns the flake. No CI reruns were used. |
…#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.
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.
The real
chat.historyhandler, 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:
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.
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.ts0.75 s,serialized-json.test.ts0.10 s,chat-history-worker.test.ts10.48 s,session-transcript.worker.schema-freshness.test.ts2.43 s,ws-connection.serialized-json.test.ts1.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 failedsrc/gateway/managed-image-actions.e2e.test.ts→ “downloads fresh image and document bytes by run scope and rejects stale IDs” withSessionMutationFactsUnavailableErrorduringartifacts.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.