Skip to content

fix: prevent compaction worker OOM on large session histories - #194536

Merged
RomneyDa merged 5 commits into
mainfrom
openclaw/sqlite-oom-repro-fix
Nov 9, 2026
Merged

RomneyDa merged 5 commits into
mainfrom
openclaw/sqlite-oom-repro-fix

Conversation

@RomneyDa

@RomneyDa RomneyDa commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Related: #191847

Problem and solution

Large transcripts can exhaust the compaction worker before the next agent turn. Complete compaction intentionally disables bounded-replay limits; the previous selector parsed and retained every selected payload in a worker-side Map.

The existing selector now produces a payload-free compaction plan, retaining ancestry/selection metadata and at most two full anchors for existing predicates. Selected payloads stream through the existing acknowledged hydration transport under the same read snapshot. The host verifies completeness and reconstructs semantic sequence order before returning the existing bounded result. Ordinary bounded hydration and cold-archive restoration retain their owners.

The heap rig adds a synthetic single-session fixture and cold-restart path for real Gateway RPC reproduction. No heap-limit increase, new configuration, schema migration, retention change, release, or backport is included.

Original reproduction and evidence

  • Base: efb980423985b290f5c294ba7b13ad4c2bd074d8. At initial publication, the eight files matched the validated/reviewed snapshot (working-patch SHA-256 a6fa353076c61612fd4a73a2a2ce05b4b7e0a1b832d22cb23f8bf74c0c6af9f3). Follow-up changes are recorded separately below.
  • Two base cold runs failed; one candidate cold run completed, using Node 24.22.1/Linux x64, the same 33,000 × 15,000-character history (495,000,000 injected text bytes), one session/client, and unchanged resource limits. Both base runs failed during preflight compaction with ERR_WORKER_OUT_OF_MEMORY; attribution observed 516,952,160 bytes of worker heap before failure.
  • Candidate completed cold restart, two real chat.send/agent.wait turns with verified 8,192-byte mock replies, and one minute of UI/status/history/catalog/subscription RPC workload. Harness and Gateway exited successfully. Compaction took 2,610 ms; sampled worker heap reached 104,388,736 bytes (99.55 MiB), with the same effective 560 MiB V8 / 512 MiB old-generation setting.
  • Heap samples are lower bounds, not allocator maxima. These are individual observations, not median/p95 or statistically qualified performance claims; five interleaved samples per variant were not run.
  • 131 tests passed: 87 across five affected files plus 44 cold lifecycle/restoration sibling tests across two files. The selected-window streaming regression fails on the exact base at the absent streaming receiver and passes on the candidate, covering reset retention, abandoned branches, compaction ordering, acknowledged transport, and snapshot equivalence.
  • Isolated Gateway build, core/focused-test typechecks, targeted production/test/harness lint, formatting, syntax, and git diff --check passed. Default test-lint preparation refused external dependency links; the owning core-config targeted lint passed without bypassing safeguards or reinstalling shared dependencies.
  • Fresh independent review and local canonical autoreview of the initial eight-file snapshot reported no actionable P0–P2 findings. Local ClawSweeper is unavailable; the documented autoreview plus hosted-review fallback applies.

Review follow-up — November 8, 2026

  • Fixed both hosted ClawSweeper findings: discriminate streamed hydration replies and use eventCount, retaining the nine-current-entry and obsolete-history assertions; enforce exact completed-turn counts only for finite requests, while rejecting duration runs with no completed turns.
  • Also fixed the PR-introduced database-worker ratchet failure. Full anchors are retained during the existing payload cursor rather than queried again; the selection Map is reused. No baseline exception or new SQL was added.
  • Red/green: both complete-context delegate cases failed at the observer before the fix; duration mode failed after six successful turns with 6/Infinity. The database-worker ratchet failed at 167 -> 168 before the anchor change and passes at 167 -> 167 afterward.
  • 62 tests passed: complete compact.delegate, bounded-context, hydration-worker, and cache-TTL-prefix suites. Core and expanded focused-test typechecks, four-file targeted lint, formatting, script syntax, and diff checks passed.
  • Isolated diagnostic runs completed and wrote result.json: duration mode completed six turns; finite mode completed exactly two. Both used ten synthetic history events and verified 8,192-byte mock replies. These validate the harness fix, not a repeat of the large-history allocation benchmark.
  • Fresh independent review plus canonical authenticated-host autoreview of both the local diff and committed follow-up range reported no actionable P0–P2 findings. Published files were verified byte-identical to the reviewed local commit. Hosted re-review is requested separately; new-head CI is not yet claimed green.
  • Previous-head CI also reported a Control UI fresh-visit assertion at gateway-fresh-visit.http.e2e.test.ts:204 (expected diagnostic heading not visible within 15 seconds). This is outside the changed files; it remains recorded, not classified as a baseline failure or silently waived.

CI follow-up — November 9, 2026

  • Commit cafd67afbb96b26146d714ffa38d5822182f5a64 consolidates the standalone streaming test into the existing reset/compaction lifecycle regression. Five stages now compare the complete worker-hydrated snapshot with synchronous selection, including a persisted branch that excludes an abandoned message. Existing delegate tests retain large-payload and explicit streamed-bounded coverage. No production code or ratchet policy changed.
  • Removed duplicated transport setup and its 65-line allocation: the complete PR now adds zero net test lines. Reproduced the failing CI merge d5e6ac43282256eb2085aff930402555109cbc60 against base f01b0aae3cfcb426c703e9313a3bcb5693e33d2e: before, 6,574,514 lines versus a 6,574,502 ceiling with delta +65; after applying this patch, delta 0 and the ratchet passes despite the inherited 12-line debt. No baseline increase or exception was added.
  • 75 distinct focused tests validated across invocations: 30 compactor delegate cases, 20 unchanged bounded-context cases, the final revised lifecycle case, and 24 hydration-worker/reader cases. The revised lifecycle case was rerun successfully after correcting its branch-persistence fixture. Focused typecheck, lint, formatting, and diff checks passed. Fresh canonical autoreview of the final patch found no actionable P0–P2 issues.
  • ClawSweeper's latest completed review of 290e3d5dd5581b5309947311cd20dc3380789958 reports no findings and confirms the earlier two issues are fixed. There are no inline review comments. That hosted review predates this test-only follow-up; new-head CI is not claimed green.
  • The previous CodeQL failure was a GitHub API rate-limit error during SARIF upload, not a reported source finding. This follow-up does not change CodeQL configuration.

Limits and remaining proof gap

This is a worker-allocation fix, not constant-memory summarization: the host still reconstructs the full selected context. In the original successful reproduction, observed main heap reached 2,330.26 MiB and whole-process RSS reached 4,477.75 MiB. One exceptionally large row can still exhaust worker memory while decoded.

Evidence is an isolated real Gateway with a mock model, not live-model/channel or Raspberry Pi proof. Live-provider preflight was blocked by missing approved portable authentication; host file-backed credentials were not copied. Live-model qualification requires an operator-approved portable credential source. No unrelated rebase was performed; publication remains an open PR, not a merge.

RomneyDa and others added 2 commits November 7, 2026 07:32
Stream selected compaction payloads through the acknowledged hydration transport instead of retaining the complete payload graph in the transcript worker.

Co-authored-by: RomneyDa <[email protected]>
OpenClaw-Publication: a8d89037-eea4-4dff-bad6-38b73565346c
@clawsweeper

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

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: M labels Nov 7, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 7, 2026
@clawsweeper

clawsweeper Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR streams selected compaction payloads through the existing hydration transport instead of retaining their complete decoded contents in the worker.

Example: A cold session contains 33,000 messages of 15,000 characters each.

  • Before: The reported base runs exhaust the worker heap during preflight compaction.
  • After: The reported candidate run completes compaction and two agent turns without increasing worker heap limits.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused implementation preserves existing owners and fixes both previous findings; runtime confidence relies on reported Gateway results and supporting integration coverage.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its body reports real Gateway chat.send/agent.wait turns after cold restart on Linux with 495 MB of synthetic text, while raw runtime artifacts and live-model qualification are not supplied.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: A large session can exhaust the transcript worker during compaction and fail before the next agent reply.
Reason: The maintainer-authored direction addresses a demonstrated allocation failure while preserving complete summary coverage; Related wording correctly leaves the broader linked issue open.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it addresses a concrete compaction allocation defect that remains on main, both previous findings are fixed, and no new actionable defect was found.

Priority: P1
Reviewed head: 290e3d5dd5581b5309947311cd20dc3380789958

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The body reports shipped Gateway reproduction with a mock provider, but supplies no inspectable runtime artifact or live-model qualification; the new selection test proves streaming equivalence rather than a worker-memory ceiling.
Agent review details

How this fits together

Compaction requests a complete semantic transcript window from the history worker; SQLite supplies selected records, acknowledged chunks carry their payloads to the host, and the host reconstructs the existing context result for the compactor.

flowchart LR
  A[Compaction request] --> B[Existing context selector]
  B --> C[Selection metadata]
  C --> D[Snapshot payload stream]
  D --> E[Host completeness and ordering]
  E --> F[Existing compactor]
Loading

Technical review

Best possible solution:

Retain the existing complete-context selection policy while transferring selected payloads through its existing acknowledged transport.

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

Current-main source retains every selected decoded payload when compaction disables replay limits, matching the PR's reported cold-Gateway OOM reproduction; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The change fixes the owning allocation boundary without truncating compaction input, increasing heap limits, or introducing another selector, cache, or persistence owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +119, Tests +62, Other +114. Total +295 across 10 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 5 171 52 +119
Tests 3 71 9 +62
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 154 40 +114
Total 10 396 101 +295

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
Diagnostic options 5 new heap-rig options runtime-root, legacy-workshop, event-chars, large-session-events, and restart-after-seed support isolated reproduction; production configuration and worker limits remain unchanged.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Worker heap exhaustion can prevent every subsequent turn in a large session from completing.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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 (1 earlier review cycle)
  • reviewed 2026-11-07T07:48:29.469Z sha 6652632 :: needs changes before merge. :: [P2] Migrate the hydration observer to the streamed result | [P2] Skip exact-count comparison for duration-based runs

Reviewed November 8, 2026, 2:19 AM ET / 07:19 UTC (Revision 2).

RomneyDa and others added 2 commits November 8, 2026 07:11
OpenClaw-Publication: 12f6f8de-6a33-4c77-806e-36a038852180
@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Nov 8, 2026
@RomneyDa

RomneyDa commented Nov 8, 2026

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 8, 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-repro Preliminary submission classification; full source review pending. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 8, 2026
Reuse the reset lifecycle regression for full streamed snapshot parity and abandoned-branch exclusion. Remove duplicated transport setup and its allocation so the PR adds no net test lines even when the base has existing ratchet debt.

Co-authored-by: RomneyDa <[email protected]>
@RomneyDa
RomneyDa merged commit 7cfc564 into main Nov 9, 2026
110 checks passed
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 10, 2026
…aw#194536)

* fix: prevent compaction worker OOM on large session histories

Stream selected compaction payloads through the acknowledged hydration transport instead of retaining the complete payload graph in the transcript worker.

Co-authored-by: RomneyDa <[email protected]>

* fix: prevent compaction worker OOM on large session histories

OpenClaw-Publication: a8d89037-eea4-4dff-bad6-38b73565346c

* fix: address compaction streaming review regressions

Co-authored-by: RomneyDa <[email protected]>

* Publish openclaw/sqlite-oom-repro-fix

OpenClaw-Publication: 12f6f8de-6a33-4c77-806e-36a038852180

* test: consolidate compaction streaming coverage

Reuse the reset lifecycle regression for full streamed snapshot parity and abandoned-branch exclusion. Remove duplicated transport setup and its allocation so the PR adds no net test lines even when the base has existing ratchet debt.

Co-authored-by: RomneyDa <[email protected]>

---------

Co-authored-by: RomneyDa <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 12, 2026
Adapt approved #194536 to the release ancestry owner without importing
background-result dependencies or persisted active facts. Plan the complete
semantic window using lightweight metadata, then stream its selected payloads
through the acknowledged transport in the same read snapshot. Validate exact
selected sequences and counts before restoring semantic event order.

Bound PostgreSQL planning queries because its iterator buffers results; keep
SQLite cursor reads and preserve indivisible oversized events. Reuse the reset
lifecycle and real manual/budget compaction regressions.

(cherry picked from commit 7cfc564)

Co-authored-by: vincentkoc <[email protected]>
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

agents Agent runtime and tooling P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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