Repository navigation
improve(gateway): reduce work for oversized chat history updates - #138655
Conversation
|
🦞👀 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: blocked before merge. Reviewed September 4, 2026, 10:44 PM ET / September 5, 2026, 02:44 UTC. ClawSweeper reviewWhat this changesThe Gateway counts finalized chat-history messages incrementally and stops preparing oversized updates earlier, with SQLite-backed tests covering exact byte limits. Merge readiness⛔ Blocked before merge - 1 item remains Keep open as a useful, well-supported optimization with no blocking findings. Current main still performs the whole-array size check, and the earlier migration warning does not apply to this in-memory change. Priority: P3 Review scores
Verification
How this fits togetherThe Gateway serves saved conversation updates to web and native chat clients. It converts SQLite transcript rows into display messages, then returns either a complete bounded update or a reset response that makes the client reload history. flowchart TD
A[Chat client cursor request] --> B[Read SQLite transcript changes]
B --> C[Prepare display messages and session metadata]
C --> D[Count finalized JSON bytes]
D --> E{Within requested budget?}
E -->|Yes| F[Return complete delta and cursor]
E -->|No| G[Return reset]
G --> H[Client reloads history]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +4, Tests +124. Total +128 across 2 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Retain the local early-exit counter and existing reset/full-history recovery contract, without adding a cache, storage migration, or another projection path. Do we have a high-confidence way to reproduce the issue? Not applicable as a correctness-bug reproduction: this is a behavior-preserving optimization, and current-main source plus the supplied benchmarks establish the unnecessary projection work. Is this the best way to solve the issue? Yes. Finalized envelopes are the correct accounting boundary because raw transcript sizes omit repeated session metadata; reusing the existing JSON helper avoids constructing a whole-page JSON string without duplicating serialization logic. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 6832f3b61ebc. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
History |
Merge main and apply the existing incremental envelope counter to the prepared requested byte budget. Keep default and maximum limits intact, including exact boundaries, and cover smaller requested budgets with the existing SQLite fixture.
|
Merged via squash.
|
* refs/remotes/origin/main: (602 commits) fix(plugins): trace trust refusals and repair legacy provenance (openclaw#138746) perf(sqlite): reuse compiled plugin state point reads (openclaw#138758) refactor: type chat prefetch dependencies and clean loading tests (openclaw#138793) ci: reduce Doctor test startup and core lint jobs (openclaw#138796) feat(update): retain run history and share outcome reports (openclaw#138690) chore(deps): update @openclaw/fs-safe to 0.8.1 (openclaw#138500) fix: preserve global board ownership from pinning to notifications (openclaw#138675) fix(gateway): deliver session catalog updates from slow hosts (openclaw#138674) perf(sessions): index pending conversation replies (openclaw#127182) perf(auth): reuse ordered provider alias entries (openclaw#138805) docs(diagnostics): clarify whole-process CPU metrics (openclaw#138804) perf(memory): narrow source reads and stream embedding cache rows (openclaw#138766) fix: allow older source on newer Testbox checkouts (openclaw#138782) fix(agents): preserve recovered task progress and lifecycle ownership (openclaw#138785) perf(codex): reduce rollout tail scan CPU (openclaw#138784) perf(gateway): stop projecting history deltas at the byte budget (openclaw#138655) fix(build): bound native declaration inputs to checkout (openclaw#138742) fix(cli): preserve foreground Gateway argument handling (openclaw#138765) fix(ui): align task toolbar with side-panel tabs (openclaw#138769) fix(logbook): drain accepted work before closing SQLite (openclaw#138754) ... # Conflicts: # src/agents/embedded-agent-runner/compact.queued.ts
Additional instructions
MUST: Keep Allow edits from maintainers enabled for this PR so maintainers
can help update the branch when needed.
What Problem This Solves
Chat history catch-up can spend unnecessary CPU and temporary memory on updates that exceed the response size limit, especially in conversations with many tool results or substantial session metadata.
Why This Change Was Made
The raw transcript byte limit does not include the prepared session metadata repeated in every display envelope, so a complete raw page can become an oversized projected update. Count each finalized envelope with the existing native JSON byte helper, including array brackets and commas, and stop projecting as soon as the page exceeds its budget; this removes the final whole-array serialization.
User Impact
The Gateway does less work before returning the existing history reset response for an oversized update. Requested budgets, the one-million-byte ceiling, empty deltas, display order, sanitization and cursor behavior stay intact, and clients continue using the existing full-tail refresh path.
Evidence
chat.historyandchat.startuprequest-budget cases also passed. Before the comparison was updated, the 64 KiB plus one-byte case failed by returning a delta instead of reset.The original five workloads exercised real SQLite reads, display projection and session-snapshot construction on Node 26.8.1. These measurements remain the original frozen comparison; the current-main port adds functional boundary proof without a new performance claim. Allocation used three observations of 200 calls; separate uninstrumented timing used four fresh processes in baseline/candidate/candidate/baseline order, with 50 warmups and 200 calls per case.
Inputs, output hashes and byte counts matched across arms. Batch cases improved in these measurements; single-result controls were mixed, including one higher CPU observation for the small result. Timing has two process observations per arm. Sampled allocation includes collected objects and does not measure retained heap or RSS; these results do not establish uniform savings or whole-Gateway throughput.
Original default-budget built Gateway proof passed on both frozen arms: baseline
8f0facca5e0bc990b2949a73afea69e7cc2a19f4and integrated candidate15216423e92cfff6a530f57441781b31a176c322, which includes this change. Each run used a real isolated loopback Gateway, its built CLI, and synthetic transcript rows appended through that build's canonical SQLite accessor.A fitting one-message catch-up returned the exact expected 4,236-byte envelope array. The next 112 tool-result rows occupied 941,135 raw bytes with no continuation, but their complete projected envelope array was 1,279,519 bytes. Both Gateways returned exactly
{ "kind": "reset" }; a normal tail then recovered all 114 message IDs, contents and sequences, and the next cursor read returned an empty delta with an unchanged cursor. The projected-byte oracle was calibrated against the actual fitting RPC response and independently reconstructed from the recovered messages. Both complete recovered histories matched after normalizing only the opaque transcript display-source identifier.Both runs passed strict source/build/dependency identity checks before and after execution, complete capture checks, clean joined shutdown, port release and temporary-state removal. An initial harness attempt incorrectly required a cursor from zero-message history and stopped before seeding; that failure was preserved, and the corrected fixture adds one visible canonical anchor before obtaining the first cursor. No product change was needed for that correction. No model turns were requested. This proves built RPC behavior; the allocation and timing results above remain separate owner measurements.
Fresh requested-budget built Gateway proof passed on commit
509fc7a4577b73886489dff1b9845acf4b84a24d: the reconciled owner preserves main’s requestedmaxBytesparameter, its one-million-byte clamp, and the caller’s prepared budget. The real isolated Gateway and built CLI explicitly requested 65,536 bytes for cursor reads. A fitting update returned the calibrated 4,328-byte envelope array. Twenty further tool-result rows occupied 24,664 raw bytes but projected to 86,910 bytes, and the Gateway returned exactly{ "kind": "reset" }. A normal history read then recovered all 22 canonical messages; the next requested-budget cursor read was empty and unchanged.All source, build and physical dependency identities remained stable. The Gateway and owned CLI processes shut down cleanly, complete captures verified, the port was released and temporary state removed. No model turns were requested. The original default-budget proof above remains separate and unchanged.
Review disposition
Data-model compatibility checklist: not applicable. This changes only the in-memory response projection in
readChatHistoryDelta: it counts finalized envelopes using native JSON UTF-8 bytes, including array brackets and commas, and stops when the effective requested response budget, capped at 1,000,000 bytes, is exceeded. No persisted representation, schema, version, migration, retention or concurrency changes. The transcript read completes before this loop; potentially skipped profile display lookups are read-only and do not write the canonical store.The existing reset/cursor response contract remains intact. The real SQLite boundary cases cover the exact cap and one byte over with session metadata and sanitization.
Maintainer disposition: land this accepted owner refactor under the existing authorization for autonomous landing, after required checks and normal native gates pass. The original default-budget proof passed on both frozen arms, and the fresh requested-budget proof passed on the reconciled commit.