Skip to content

fix(gateway): prevent large history from blocking chat startup - #124994

Merged
steipete merged 4 commits into
mainfrom
steipete/ecstatic-golick-aa32b7
Aug 17, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/ecstatic-golick-aa32b7

Conversation

@steipete

@steipete steipete commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where opening chat with a large SQLite transcript or a bound Claude CLI history could block Gateway startup/history responses. Multiple clients connecting together multiplied the Claude JSONL read and parse work, while SQLite could parse large event_json payloads before applying the response byte limit.

Why This Change Was Made

SQLite history now selects a contiguous suffix from metadata and serialized byte lengths before materializing message or reset/compaction payloads. The recent-tail metadata query reads only the newest maxMessages candidates, whose public cap remains below SQLite's bind-variable limit. Reset/compaction payloads are fetched through one event-sequence range joined back to the active-event projection, avoiding both unbounded bindings and abandoned-branch payloads.

Claude CLI history is streamed through a process-owned, strong-fingerprint single-slot snapshot with event-loop yields and cross-client singleflight. Oversized records are parsed in a worker: supported user/assistant records retain their role, external ID, timestamp, and bounded metadata through a visible placeholder, while unsupported external record types remain ignored. Messages are coalesced and redacted before the shared snapshot is frozen; each caller receives isolated clones. A request reuses the same snapshot for both the recent-tail and full-local merge.

The synchronous import API is intentionally retained for embedded-gateway-stub, whose injected runtime contract is synchronous. The server Gateway path never performs the external read through that API: it supplies the prepared async snapshot. Both paths share the same parser, tool-call coalescing, reseed, and redaction helpers so their semantics cannot drift independently.

The existing external IDs, reseed handling, redaction, marker ordering, cursor behavior, and terminal imported-snapshot contract remain unchanged. The assertion-safety ratchet is lowered for two removed assertions, and the contributor guidance now records that exact shrink-only ratchet maintenance needs no separate approval.

The PR also repairs a current-main browser test failure exposed by the broad exact-head matrix: eager lazy-registration coverage left two newer command groups real and tore down while their OAuth imports were loading. The test now mocks and awaits every declared group.

User Impact

Chat startup remains responsive with large histories and concurrent clients instead of serially blocking the Gateway event loop. History content and pagination behavior are unchanged.

Release note: Prevent large local or Claude CLI histories from blocking chat startup.

Evidence

  • Pre-fix payload regression failed by parsing an excluded malformed SQLite payload before the byte cutoff (SyntaxError through readVisibleHistoryRange).
  • Pre-fix binding regressions both failed with too many SQL variables: the widened recent-tail metadata query and the boundary payload query.
  • Pre-fix inactive-branch regression failed by parsing a malformed abandoned compaction payload between two active sequence bounds; the fixed read joins the active projection.
  • Pre-fix oversized-record regression proved the multi-megabyte line reached main-thread JSON.parse; the fixed path parses it in a worker and preserves supported record identity through a bounded placeholder.
  • Pre-fix cache regression observed six redaction calls for three imported messages across two concurrent readers; the fixed snapshot redacts three times during construction and serves isolated clones.
  • SQLite history and marker coverage: 4 dedicated metadata/binding/active-path tests plus 16 active-event tests passed.
  • Claude import, redaction, freshness, singleflight, and oversized-record coverage: 47 passed.
  • Concurrent 34 MiB single-record Claude history Gateway coverage: 151 tests passed across the owning Gateway files, including the real 5 ms event-loop heartbeat across separate clients.
  • Production caller audit: the synchronous API is used by src/agents/tools/embedded-gateway-stub.ts; server history passes preparedImportedMessages from the async snapshot owner.
  • Browser teardown repair: focused coverage passed 28/28 and the full browser plugin suite passed 188 files / 2,577 tests with no teardown errors.
  • Full check:changed: green across formatting, production/test types, lint, dead exports, import cycles, database guards, extension tests, and ratchets. Remote delegation was unavailable (Blacksmith readiness failure and Daytona memory quota), so trusted-source fallback ran on the prepared local checkout.
  • Exact committed branch autoreview through P1: clean, no accepted/actionable findings.
  • ClawSweeper rank-up moves addressed: bounded metadata bindings, active-only boundary fetch, redaction before shared caching, off-thread oversized-record projection, and rerun owner/concurrent-history proof.
  • Production LOC: +525/-120 (net +405). Tests: +610/-9 (net +601). Docs/tooling: net 0.

AI-assisted; implementation and proof reviewed by the maintainer.

@clawsweeper

clawsweeper Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: L maintainer Maintainer-authored PR labels Aug 17, 2026
@steipete steipete self-assigned this Aug 17, 2026
@steipete
steipete marked this pull request as ready for review August 17, 2026 02:48
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. 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 Aug 17, 2026
@clawsweeper

clawsweeper Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 17, 2026, 2:37 AM ET / 06:37 UTC.

ClawSweeper review

What this changes

The PR bounds SQLite transcript-history reads and adds a shared asynchronous Claude CLI snapshot so large local histories do not stall concurrent Gateway chat startup.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

No blocking correctness finding. This maintainer-owned PR remains necessary: current main still synchronously reads and parses bound Claude CLI history and materializes SQLite boundary payloads before recent-history byte selection.

Priority: P1
Reviewed head: 6a461c323776518692a166010f0b9ec1ccaa51b6

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch is a well-targeted owner-boundary repair with credible regression coverage and no blocking finding.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-owned PR is outside the external-contributor proof gate; its body nevertheless records a two-client 34 MiB Gateway harness scenario and after-fix result.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-owned PR is outside the external-contributor proof gate; its body nevertheless records a two-client 34 MiB Gateway harness scenario and after-fix result.
Evidence reviewed 7 items Current-main blocking path: Current main synchronously reads the complete bound Claude JSONL file, splits it, and parses each line on the history path; the PR replaces that server use with the prepared asynchronous snapshot.
Async snapshot owner boundary: The proposed snapshot streams the external file, yields between bounded work, parses oversized records in a worker, redacts before freezing the shared cache, and returns clones to callers.
Gateway caller uses one prepared import: The server awaits one import snapshot and passes it to both tail and full-local merges, avoiding duplicate external reads within one request.
Findings None None.
Security None None.

How this fits together

Gateway chat history combines the local SQLite transcript with an optional bound Claude CLI transcript before returning startup and history pages to connected clients. The changed code selects the local page, imports external history once, merges both sources, and projects the response.

flowchart LR
  A[Connected chat clients] --> B[Gateway history reader]
  B --> C[SQLite active transcript]
  B --> D[Claude CLI snapshot]
  C --> E[Bounded history selection]
  D --> F[Redacted imported messages]
  E --> G[Merged chat history]
  F --> G
  G --> H[Startup or history response]
Loading

Before merge

  • Resolve merge risk (P1) - The bug fix adds net +405 production lines on a Gateway and session-history hot path; the growth is justified by the server-owned streaming/singleflight boundary, but should remain covered by the focused large-history regression suite.
  • Resolve merge risk (P1) - The branch is behind main and exact-head checks are still completing, so merge should wait for GitHub's refreshed exact-head result.
  • Complete next step (P2) - No discrete repair remains from this review; wait for the current head's normal merge validation.
Agent review details

Security

None.

PR surface

Source +405, Tests +601, Docs 0, Other 0. Total +1006 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 5 525 120 +405
Tests 4 610 9 +601
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 2 0
Total 11 1138 132 +1006

Review metrics

Metric Value Why it matters
Production versus test delta production +525/-120 (net +405); tests +610/-9 (net +601) The substantive production growth implements streaming, snapshot ownership, and bounded SQLite reads; the accompanying tests cover the stated failure modes at their owner boundaries.

Stored data model

Persistent data-model change detected: serialized state: src/config/sessions/session-accessor.sqlite-history-events.test.ts, serialized state: src/config/sessions/session-accessor.sqlite-history-events.ts, serialized state: src/gateway/cli-session-history.claude-snapshot.ts, serialized state: src/gateway/cli-session-history.claude.ts, serialized state: src/gateway/server.chat.gateway-server-chat-b.test.ts, unknown-data-model-change: src/config/sessions/session-accessor.sqlite-history-events.test.ts, and 1 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Gate the current head (recommended)
    Refresh the branch only if GitHub requires it, then require the remaining exact-head Gateway and session-history checks before merge.

Technical review

Best possible solution:

Keep the server-owned asynchronous snapshot as the single external-history path, retain the embedded stub's synchronous contract, and land after exact-head validation confirms the bounded SQLite and concurrent Gateway regressions.

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

Yes, from source: current main synchronously reads, splits, and parses the complete bound Claude JSONL transcript on the Gateway history path; this read-only review did not execute the reproduction.

Is this the best way to solve the issue?

Yes. Moving external-history work to a server-owned prepared snapshot fixes the blocking owner while retaining the synchronous embedded-runtime contract and avoiding duplicate reads during a request.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against ac5c8be00196.

Labels

Label justifications:

  • P1: Current-main large transcript reads can block Gateway chat startup and history responses for connected users.
  • merge-risk: 🚨 availability: The PR changes the Gateway hot path that constructs chat history under large local and external transcripts.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This maintainer-owned PR is outside the external-contributor proof gate; its body nevertheless records a two-client 34 MiB Gateway harness scenario and after-fix result.

Evidence

What I checked:

Likely related people:

  • Patrick Erichsen: Current-main blame and file history tie the original synchronous Claude history importer and SQLite history reader to the prompt-cache work. (role: feature introducer; confidence: high; commits: 9e4ba15f4c37; files: src/gateway/cli-session-history.claude.ts, src/config/sessions/session-accessor.sqlite-history-events.ts)
  • steipete: The supplied timeline assigns this maintainer-authored PR to steipete, and the repair commits own the changed Gateway and SQLite paths. (role: current repair owner; confidence: high; commits: 1aeab03a6ea4, 6a461c323776; files: src/gateway/cli-session-history.claude-snapshot.ts, src/gateway/server-methods/chat-history-pages.ts, src/config/sessions/session-accessor.sqlite-history-events.ts)

Rank-up moves

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

  • Allow the remaining exact-head checks to finish after the normal branch refresh.

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 (7 earlier review cycles)
  • reviewed 2026-08-17T02:56:55.102Z sha 8007c16db8040c32a6cf7347aa484e4508a7c48e :: needs maintainer review before merge. :: none
  • reviewed 2026-08-17T03:20:01.389Z sha 3e88261655300232d317606a721fa6daaf61db84 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-17T03:41:14.690Z sha 3105492b1b48dba29b51780d2cce76b126d0555c :: needs changes before merge. :: [P1] Avoid exceeding SQLite’s bind-variable limit | [P1] Redact imported messages before caching them
  • reviewed 2026-08-17T03:58:02.751Z sha 3295073b765182be5a007fdee81ef2eddff2de66 :: found issues before merge. :: [P1] Avoid SQLite bind-variable overflow in the tail metadata query | [P1] Redact imported transcript messages before caching the snapshot | [P2] Bound the compaction/reset sequence query
  • reviewed 2026-08-17T04:22:47.816Z sha 4ea8062 :: needs changes before merge. :: [P1] Bound the metadata query’s SQLite bindings | [P1] Cache redacted imported messages | [P2] Bound the selected boundary-event query
  • reviewed 2026-08-17T05:36:00.518Z sha 470729d :: found issues before merge. :: [P1] Fetch only active boundary payloads | [P1] Keep single-record JSONL parsing off the event loop
  • reviewed 2026-08-17T05:57:01.118Z sha a9d3056 :: needs changes before merge. :: [P1] Restrict boundary payload reads to active events | [P1] Move oversized JSONL parsing off the Gateway event loop

@steipete
steipete force-pushed the steipete/ecstatic-golick-aa32b7 branch from 8007c16 to 3e88261 Compare August 17, 2026 03:13
@clawsweeper clawsweeper Bot added merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed 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 Aug 17, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 17, 2026
@steipete
steipete force-pushed the steipete/ecstatic-golick-aa32b7 branch from 3295073 to 4ea8062 Compare August 17, 2026 04:14
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Aug 17, 2026
@steipete
steipete force-pushed the steipete/ecstatic-golick-aa32b7 branch from 4ea8062 to f77d4cd Compare August 17, 2026 05:22
@steipete
steipete force-pushed the steipete/ecstatic-golick-aa32b7 branch from f77d4cd to 470729d Compare August 17, 2026 05:29
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Aug 17, 2026
Apply SQLite byte limits before loading history payloads and share a yielded, fingerprinted Claude CLI snapshot across concurrent startup clients. Preserve marker, cursor, redaction, and external identity semantics, and clarify that shrink-only ratchet updates need no separate approval.
@steipete
steipete force-pushed the steipete/ecstatic-golick-aa32b7 branch from 470729d to a9d3056 Compare August 17, 2026 05:49
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. label Aug 17, 2026
@clawsweeper clawsweeper Bot added 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. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 17, 2026
@steipete
steipete merged commit 59c661b into main Aug 17, 2026
226 checks passed
@steipete
steipete deleted the steipete/ecstatic-golick-aa32b7 branch August 17, 2026 06:43
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

jackjin1997 added a commit to jackjin1997/openclaw that referenced this pull request Aug 18, 2026
Refreshes the merge head after main's chat-history read-path changes
(openclaw#124994, openclaw#125123). Conflict resolution:

- cli-session-history.ts: take main's async snapshot/augment helpers.
  This PR originally deleted them as embedded-only duplicates; main's
  canonical page reader (chat-history-pages.ts) is now their consumer.
- embedded-gateway-stub.ts: keep the canonical readChatHistoryPage
  delegation and its pagination/budget handling; drop main's inlined
  offsetPage arithmetic, which belonged to the reader this PR removes.
- embedded-gateway-stub.test.ts: drop main's new offset-continuation
  case, which mocks readRecentSessionMessagesWithStatsAsync (removed
  from the embedded runtime facade here). The equivalent assertion runs
  through the canonical reader in the retained budgeted-page test.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 18, 2026
…law#124994)

* fix(gateway): bound startup history materialization

Apply SQLite byte limits before loading history payloads and share a yielded, fingerprinted Claude CLI snapshot across concurrent startup clients. Preserve marker, cursor, redaction, and external identity semantics, and clarify that shrink-only ratchet updates need no separate approval.

* test(browser): await all lazy command groups

* fix(gateway): bound history snapshot state

* fix(gateway): preserve oversized history responsiveness
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: browser gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL 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