Skip to content

improve(gateway): reduce work for oversized chat history updates - #138655

Merged
steipete merged 2 commits into
mainfrom
codex/perf9-delta-budget
Sep 5, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/perf9-delta-budget

Conversation

@steipete

@steipete steipete commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor
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

  • Current-main integration: 10 focused tests passed. The existing SQLite fixture covers eight exact-boundary cases: four omitted-budget cases, two requested 64 KiB cases, and two requested 2 MB cases clamped to 1,000,000 bytes. The existing public chat.history and chat.startup request-budget cases also passed. Before the comparison was updated, the 64 KiB plus one-byte case failed by returning a delta instead of reset.
  • Original validation: 54 selected tests passed: four real SQLite boundary cases cover one/two envelopes at exactly 1,000,000 bytes and one byte over, with escaping, Unicode, a lone surrogate and private-field stripping; 23 existing cursor cases, 25 byte-helper cases and both public empty-delta handler cases also passed.
  • Canonical changed-file gate passed again, including formatting, core/test type checks, lint and repository guards. A fresh independent managed P0–P2 review found no actionable issues, and the full build passed on the reconciled commit.
  • Production +7/−3, net +4; tests +124. The local counter moves the existing budget decision into the projection owner, enabling early exit. Later projections cannot modify earlier envelopes, and skipped profile lookups are read-only; there is no additional helper, cache or persistence path.

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.

Workload Wall time change CPU change Total sampled allocation change
One 8 KiB result −2.37% +9.37% −0.32%
One 900 KB result +5.52% −3.27% −0.12%
64 results below the cap −10.12% −7.76% −0.44%
112 results over the cap −9.95% −8.03% −5.41%
64 results with valid 16 KiB plugin metadata −46.76% −49.26% −48.40%

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 8f0facca5e0bc990b2949a73afea69e7cc2a19f4 and integrated candidate 15216423e92cfff6a530f57441781b31a176c322, 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 requested maxBytes parameter, 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.

@clawsweeper

clawsweeper Bot commented Sep 4, 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.

@steipete
steipete marked this pull request as ready for review September 4, 2026 22:02
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S maintainer Maintainer-authored PR labels Sep 4, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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 Sep 4, 2026
@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 4, 2026, 10:44 PM ET / September 5, 2026, 02:44 UTC.

ClawSweeper review

What this changes

The 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
Reviewed head: 509fc7a4577b73886489dff1b9845acf4b84a24d

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused owner-level optimization with strong runtime evidence, exact boundary coverage, appropriately qualified measurements, and no blocking findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The captured exact-head built-Gateway/CLI evidence exercises the changed delta owner through real SQLite-backed RPC reads, showing requested-budget reset, lossless history recovery, and stable empty-cursor behavior; separate frozen runs cover the default budget.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured exact-head built-Gateway/CLI evidence exercises the changed delta owner through real SQLite-backed RPC reads, showing requested-budget reset, lossless history recovery, and stable empty-cursor behavior; separate frozen runs cover the default budget.
Evidence reviewed 10 items Verified introduced change: The local head matches the pinned original PR head and its recorded parents. The base-to-head diff contains only the incremental counter and its boundary tests; it does not change storage, configuration, authorization, or protocol schemas. The stale test-merge reference was not used to infer merge behavior.
Current-main necessity: Fetched main still prepares every envelope and then measures JSON.stringify(messages). Its delta-owner source matches the pinned base, so the proposed early exit remains distinct useful work.
Exact accounting and implementation boundary: The existing helper measures native JSON serialization in UTF-8. The new counter includes two brackets and one comma between envelopes. Public history requests require at least 1,024 bytes, so removing the final check does not alter valid empty-delta behavior. This is OpenClaw-owned display accounting, not a Codex runtime or protocol change.
Findings None None.
Security None None.

How this fits together

The 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]
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +4, Tests +124. Total +128 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 7 3 +4
Tests 1 124 0 +124
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 131 3 +128

Review metrics

Metric Value Why it matters
Production versus test growth Production +7/−3, net +4; tests +124 The small production increase replaces whole-page serialization with a local early-exit counter; it introduces no helper, cache, configuration option, or persistence path.

Stored data model

Persistent data-model change detected: serialized state: src/gateway/server-methods/chat-history-delta.ts. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best 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.

Labels

Label justifications:

  • P3: This is a bounded performance improvement that preserves existing history responses, rather than an urgent broken user workflow.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The captured exact-head built-Gateway/CLI evidence exercises the changed delta owner through real SQLite-backed RPC reads, showing requested-budget reset, lossless history recovery, and stable empty-cursor behavior; separate frozen runs cover the default budget.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured exact-head built-Gateway/CLI evidence exercises the changed delta owner through real SQLite-backed RPC reads, showing requested-budget reset, lossless history recovery, and stable empty-cursor behavior; separate frozen runs cover the default budget.

Evidence

What I checked:

  • Verified introduced change: The local head matches the pinned original PR head and its recorded parents. The base-to-head diff contains only the incremental counter and its boundary tests; it does not change storage, configuration, authorization, or protocol schemas. The stale test-merge reference was not used to infer merge behavior. (src/gateway/server-methods/chat-history-delta.ts:80, 509fc7a4577b)
  • Current-main necessity: Fetched main still prepares every envelope and then measures JSON.stringify(messages). Its delta-owner source matches the pinned base, so the proposed early exit remains distinct useful work. (src/gateway/server-methods/chat-history-delta.ts:103, 6832f3b61ebc)
  • Exact accounting and implementation boundary: The existing helper measures native JSON serialization in UTF-8. The new counter includes two brackets and one comma between envelopes. Public history requests require at least 1,024 bytes, so removing the final check does not alter valid empty-delta behavior. This is OpenClaw-owned display accounting, not a Codex runtime or protocol change. (src/infra/json-utf8-bytes.ts:19, 509fc7a4577b)
  • Finalized-envelope ownership: Each projection returns a fresh envelope containing the prepared session snapshot. Later calls receive only projection flags, not earlier envelopes; display composition reorders values without changing their contents. Counting after projection therefore preserves the existing serialized-array budget. (src/gateway/session-transcript-message.ts:54, 509fc7a4577b)
  • Shared public caller and recovery: Both chat.history and chat.startup use the same handler, which passes the prepared requested budget into the delta owner and forwards reset responses unchanged. The Control UI's existing reset branch clears the cursor and requests a normal history page. (src/gateway/server-methods/chat-history-handler.ts:534, 509fc7a4577b)
  • Prior migration concern resolved: The transcript snapshot read finishes before the changed loop. Potentially skipped profile-display lookups explicitly use the existing read-only state-database accessor. The earlier review's migration request has no introduced persistent-data boundary to attach to, consistent with the PR body's disposition. (src/state/user-profile-list.ts:188, 509fc7a4577b)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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 (3 earlier review cycles)
  • reviewed 2026-09-04T22:10:03.437Z sha fb2f382 :: blocked before merge. :: none
  • reviewed 2026-09-04T23:06:03.748Z sha fb2f382 :: blocked before merge. :: none
  • reviewed 2026-09-05T00:02:13.706Z sha fb2f382 :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Sep 5, 2026
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.
@steipete
steipete merged commit bb14737 into main Sep 5, 2026
179 of 181 checks passed
@steipete
steipete deleted the codex/perf9-delta-budget branch September 5, 2026 02:51
@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 5, 2026
vincentkoc added a commit to LiuwqGit/openclaw that referenced this pull request Sep 5, 2026
* 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime maintainer Maintainer-authored PR P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S 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