Skip to content

fix(sessions): keep large rewinds from exhausting the shared database worker - #198786

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-micro-agent-db-worker-oom-single-request-20260919
Nov 14, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-micro-agent-db-worker-oom-single-request-20260919

Conversation

@steipete

@steipete steipete commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes large local session rewinds exhausting the shared database worker's heap and failing unrelated requests using that worker.

User Impact

Large local histories can be rewound without holding every message body in memory. Rewind, fork, and branch-switch preserve their existing history and editor results. Requests exceeding the safe navigation or individual-event budget fail clearly without changing the conversation or killing its database worker. Workspace preflight retains its existing full-history read with an explicit 8 MiB budget.

The limits are 8 MiB per event, 8 MiB of retained navigation/editor/header data, and 100,000 events. These reject an oversized operation rather than truncate its result. No configuration, schema, worker heap limit, or integrity-gate change.

Why This Change Was Made

The transaction previously loaded the entire transcript into JavaScript before planning the cut. It now reads SQLite's navigation projection, hydrates only the selected editor/header content, and feeds retained full events one at a time through the existing append owner. The existing typed read-budget error survives worker transport and reaches the caller.

The simplification removes full-body materialization and the redundant stringify pass used to decide whether to rebuild the index synchronously. Production code grows by 128 lines: bounded navigation and exact-payload streaming need an explicit reader, plus error transport. No new state or cache is introduced.

Evidence

On main parent 159df507ba665110e28f1f28859d60360ced6082, the real public rewind API killed sqlite-store.worker with ERR_WORKER_OUT_OF_MEMORY for 20,000 synthetic messages containing 32 KiB each. The worker retained its actual 512 MiB old-generation / 32 MiB young-generation limits.

On production source at 3018a73ff478 (byte-identical on current head 7130b866ab0b), the public rewindSessionToMessage API also succeeds against the real shared sqlite-store worker on the 36.55 GiB synthetic database: created in 23.616 s, 32 KiB editor text restored, a subsequent session-entry write succeeds, and all 20,000 copied payloads compare exactly after closing the runtime handles. Worker construction reports the unchanged 512/32 MiB resource limits; there are no worker errors. This public-path timing includes admission/lifecycle work and is separate from the owner-only comparison.

The fixed transaction succeeds on the same 36.55 GiB synthetic database with 17,690 sessions. All 20,000 retained payloads compare exactly against the originals in SQLite. Peak sampled worker heap is 127.3 MiB; elapsed time including the payload equality assertion is 10.17 s, with 9.92 s thread CPU.

Five paired controls with 2,000 messages on the same database, fresh workers, and Node 26.12.1:

Metric (median) Main Fixed
Owner wall time 1,116 ms 1,110 ms
Worker thread CPU 1,091 ms 1,102 ms
Peak sampled V8 heap 177.4 MiB 111.5 MiB
Total V8 allocation 521.0 MiB 525.8 MiB

A/A wall controls were 1,131 / 1,100 ms and CPU controls 1,055 / 1,072 ms. Separate allocation sampling showed 436.4 / 445.7 MiB medians. This fixes retained heap, not allocation volume or a demonstrated latency bottleneck. The synthetic fixture and reproduction scripts are included; no production data was used. Measurements are local filesystem owner proof, not a remote deployment or filesystem-workspace benchmark.

Focused coverage: 51 session/accessor/native-binding/Gateway tests pass, including a new oversized-history regression that fails on the exact main parent and verifies request rejection, unchanged session identity, and a subsequent successful write. Control UI browser history-settlement test and 17 chat lifecycle e2e tests pass. Codex autoreview is clean.

pnpm check:changed has two independently reproduced main regressions in its export scan: normalizeDiscoveredAgentModel became unused in #198591 (730ce41827c40c9075685e5601e0371687ff05fa), and MEMBER_ROLE_PRESETS was exported without a production consumer in #197739 (4fc7acf90a736eb92cd8690ec8036ace5f212abc). The same two failures reproduce on the exact main parent; this change does not edit either owner. pnpm build passes (3m 18s). Exact-head CI results will be recorded before landing.

First CI run 43580654616 found one PR-caused failure: the benchmark added two lint suppressions. The observer now binds methods to the owned connection/statements without suppressions; targeted lint, all 14 suppression tests, a synthetic control replay (6,151 statements / 2,001 rows), and fresh Codex autoreview pass. Production code and its measured behavior are unchanged.

Four native Talk post-cancel assertions reproduce on exact parent 159df507; #198100 (bf0b8002c2b9) enabled the prefix assertion that exposes the native consult-history mismatch, and #198248 (f52d9254a99c) records these same remaining failures and their overlap with open #179237. A controlled parent probe using the exact pre-#198100 test/setup.shared.ts makes the cancel/transcript-first/rejection case pass; restoring the current setup restores the existing failure. The final test gate remains enabled.

The pagination timeout was a newer main test regression introduced by #198775 (ea4f8e02c973), which groups cold archive reads by sorting their identities. It reproduces at 120 seconds on CI's exact main parent e3f1538c6e11; substituting only the pre-sort owner makes the same case pass. The fixture had held the alphabetically first store while awaiting progress from the second. This PR renames that held store to sort after main, preserving every assertion, timeout, and production read behavior. The complete 22-case file passes on both the PR branch and exact CI-parent source with the corrected fixture (formerly hanging case: 699 / 524 ms). Fresh Codex review is clean. The exact-parent replay also reproduces all four Talk assertions and passes all six archive cases, including the large case in 11.237 seconds.

Run 43583302321 also timed out the unchanged large archive-reader test at 30 seconds. That same test passed in the previous Linux CI run in 5.709 seconds with identical session/state source, dependency lock, and Bun pin; local parent and candidate replays pass in roughly 3–4 seconds. No timeout, skip, or archive behavior was changed. A passing local replay is not a claim that the CI timeout was fixed; the final-head CI result remains the gate.

Final head 7130b866ab0b1b94ab80d8abd349242fcc9ab9cb: CI run 43586539993 completed with 88 successful jobs, 24 skipped jobs, and only the four native Talk cancellation assertions plus their aggregate gate failing. Both the repaired pagination shard and the archive-read shard passed; security-fast passed. ClawSweeper reviewed this exact head with zero findings and zero open items.

The Talk cases reproduce on the unmodified exact CI main parent 93fdc3d9ada2d1f34957aeacde112f74c594adfe (4 failed, 10 unselected, 66.17s). CI tested merge 993e5800c9b55dcbac76bf664bb5acfa36d3afa5; test, support, and setup blobs are identical to the parent. The #198100 / #198248 attribution above applies. This scoped landing uses the native inherited-failure exception; it does not claim all CI is green. Main has separately retired the unused model normalization wrapper in #198768; that repair is preserved by the merge.

@clawsweeper

clawsweeper Bot commented Nov 14, 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 docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts size: M labels Nov 14, 2026
@steipete
steipete marked this pull request as ready for review November 14, 2026 09:27
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper review

Ready for review at 3018a73ff478d08efb238a4afd80b10d434bd769. The synthetic OOM reproduction, exact payload comparison, A/A and paired memory/CPU measurements, base-red regression, focused tests, browser tests, build, and clean Codex autoreview are complete. The PR body records two export-check failures reproduced on the exact main parent and their introducing PRs.

@clawsweeper

clawsweeper Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 14, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-14T10:04:51.222881Z 1348f23 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper

clawsweeper Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR bounds history-cut planning memory, streams retained transcript payloads, and preserves typed budget errors across the worker boundary.

Example: Rewind a local history containing 20,000 messages with 32 KiB bodies.

  • Before: The reported reproduction exhausts the shared SQLite worker's heap and disrupts unrelated requests.
  • After: The recorded public-API replay completes, restores 32,768 bytes of editor text, preserves copied payloads, and permits a subsequent write.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, focused repair with real-worker behavioral evidence, a base-red refusal regression, preserved storage format, and no actionable findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The recorded public accessor replay exercises the changed transaction through the real shared SQLite worker on synthetic large persisted history, verifies editor content and copied payloads, and confirms subsequent writes; its production source is unchanged at the reviewed head.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Rewinding a large local conversation can kill the database worker and fail unrelated session requests.
Reason: The maintainer-authored change addresses a demonstrated failure with measured heap reduction and explicitly accepts bounded rejection while preserving history semantics.

Merge readiness

✅ Ready for maintainer review

This PR addresses a current shared-worker OOM path; no actionable introduced defects were found, including in the final fixture repair, while exact-head CI remains pending.

Priority: P2
Reviewed head: 7130b866ab0b1b94ab80d8abd349242fcc9ab9cb

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway history actions call the session accessor, which plans and commits transcript cuts in the database worker and returns the new session identity and editor content.

flowchart TD
  A[Gateway history action] --> B[Session accessor]
  B --> C[Database worker transaction]
  C --> D[Bounded navigation reader]
  D --> E[Existing cut planner]
  E --> F[Streaming append owner]
  F --> G[SQLite transcript and session rows]
Loading

Technical review

Best possible solution:

Keep bounded planning and streamed copying inside the existing session transaction and append owners, preserving exact history and atomic refusal.

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

Current main materializes every transcript body before planning, matching the recorded 20,000-message public-worker OOM reproduction; this read-only review executed no target code.

Is this the best way to solve the issue?

The change removes full-body retention at its producer, reuses the planner and append owner, and preserves workspace preflight and transactional settlement.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 93fdc3d9ada2.

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +128, Tests +20, Docs +3, Other +291. Total +442 across 10 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 5 139 11 +128
Tests 2 22 2 +20
Docs 1 4 1 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 2 291 0 +291
Total 10 456 14 +442

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production versus regression-test growth Production +139/-11 lines; tests +22/-2 lines The net 128 production lines provide bounded navigation, streamed hydration, and typed error transport; test growth covers atomic budget refusal and repairs the archive fixture without weakening assertions.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Large local history operations can exhaust a shared database worker, but the demonstrated trigger is a particularly large transcript.
  • merge-risk: 🚨 compatibility: Existing histories exceeding the new budgets will be refused; this tradeoff is explicitly documented and accepted in the maintainer-authored change.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (3 earlier review cycles)
  • reviewed 2026-11-14T09:33:35.094Z sha 3018a73 :: needs maintainer review before merge. :: none
  • reviewed 2026-11-14T10:08:10.305Z sha 1348f23 :: needs maintainer review before merge. :: none
  • reviewed 2026-11-14T10:14:27.504Z sha 1348f23 :: needs maintainer review before merge. :: none

Reviewed November 14, 2026, 5:47 AM ET / 10:47 UTC (Revision 4).

@steipete

Copy link
Copy Markdown
Contributor Author

Final-head public-entry-point proof for the review's Tests note is now complete at 3018a73ff478d08efb238a4afd80b10d434bd769.

The public rewindSessionToMessage API ran against the real shared sqlite-store worker on the same 36.55 GiB synthetic database (17,690 sessions; selected history: 20,000 messages × 32 KiB). The worker reported its unchanged 512 MiB old / 32 MiB young limits. It returned created in 23.616 s with the exact 32,768-byte editor text. A subsequent public session-entry update succeeded; after closing runtime handles, native comparison verified all 20,000 copied payloads and the expected successor row count. No worker error occurred and the process exited 0.

This public-path timing includes admission/lifecycle work and is separate from the controlled owner measurements already in the body. The body now includes both boundaries. No source changes were needed; the review has zero findings and no open checklist items on this head. CI remains in progress with a failed shard being investigated.

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The head is now 1348f23ea5dd198b7cfdfe6ac1718f06723df6de. The previous review had zero findings and zero open items. This follow-up fixes the PR-caused suppression-policy failure in the benchmark: methods bind to their owned connection/statements, with no suppressions or allowlist changes. Targeted lint, all 14 suppression tests, a synthetic control replay, and fresh Codex autoreview pass.

Production source is byte-identical to the previously reviewed head, so its large public-worker proof and payload comparison remain applicable. The body now includes that public proof and accurately records the first CI run's other failures. A new exact-head CI run is required before landing.

@clawsweeper

clawsweeper Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 14, 2026
Main #198775 groups exact archive reads by store identity. The pinned-page
fixture held archive-pin before main while waiting for main to progress,
causing a reproducible 120-second timeout on the CI main parent.

Sort the held fixture store after main without changing assertions,
timeouts, or production behavior. All 22 cases pass on both the PR branch
and CI parent with this fixture correction; Codex review is clean.
@steipete

Copy link
Copy Markdown
Contributor Author

The final head is 7130b866ab0b1b94ab80d8abd349242fcc9ab9cb. The production OOM fix is unchanged from the reviewed/publicly proven source. This follow-up repairs the pagination fixture deadlock introduced on main by #198775: exact CI parent times out at 120 seconds; the corrected held-store identity makes all 22 cases pass on both parent and PR source, preserving every assertion and timeout. Fresh isolated Codex autoreview is clean. The PR body records attribution, proof, and the remaining unrelated CI failures.

The previous review has zero findings and zero open items. Please verify the test-only follow-up on this head.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added the clawsweeper:intake:bug Preliminary submission classification; full source review pending. label Nov 14, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 14, 2026
@steipete
steipete merged commit b62210f into main Nov 14, 2026
189 of 194 checks passed
@steipete
steipete deleted the steipete/perf-micro-agent-db-worker-oom-single-request-20260919 branch November 14, 2026 11:18
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 15, 2026
… worker (openclaw#198786)

* fix(sessions): bound worker memory during large history cuts

* test(sessions): bind benchmark observers to their native owners

* test(sessions): preserve held archive read ordering

Main openclaw#198775 groups exact archive reads by store identity. The pinned-page
fixture held archive-pin before main while waiting for main to progress,
causing a reproducible 120-second timeout on the CI main parent.

Sort the held fixture store after main without changing assertions,
timeouts, or production behavior. All 22 cases pass on both the PR branch
and CI parent with this fixture correction; Codex review is clean.
RomneyDa added a commit that referenced this pull request Nov 17, 2026
Backport #198786 onto the existing stable message-cut path. Plan with
compact navigation and hydrate copied rows lazily inside the existing
transaction. Refuse oversized history before it reaches the worker heap
and preserve the canonical actionable error through Gateway responses.

Retain existing SQL/navigation helpers and append ownership. Do not import
newer worktree preflight, in-place rewind migration, or performance fixtures.
The real SQLite baseline accepted an oversized row and rotated the session;
121 targeted tests now pass across six files, including native settlement.
No measured performance or full release qualification is claimed.

(cherry picked from commit b62210f)

Co-authored-by: RomneyDa <[email protected]>
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 merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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. scripts Repository scripts size: M 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