Skip to content

fix(usage): prevent refresh OOMs on large SQLite sessions - #156937

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-micro-usage-refresh-worker-oom-20260919
Sep 24, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-micro-usage-refresh-worker-oom-20260919

Conversation

@steipete

@steipete steipete commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Closes #156898

What Problem This Solves

Large SQLite sessions can repeatedly exhaust the usage-refresh worker's 512 MiB heap, leaving usage totals missing or stale after an otherwise successful sessions.usage response.

User Impact

Large sessions can finish refreshing without increasing the worker limit. Doctor reports bounded, per-session refresh failures and successful refreshes clear their warnings. No configuration, rollup format, database schema, or migration changes are required. Thanks @Conan-Scott for the detailed report and allocation control.

Why This Change Was Made

The reader eagerly decoded the entire requested range before aggregation's 128-record batches. It now reads at most 1,024 rows and 8 MiB of decoded JSON per page, with one lookahead event (an individual oversized identity event is still accepted). A first pass retains compact navigation facts; selected bodies then feed the existing aggregation in ancestry order. Append validation, reset/leaf fallback, checkpoint checks, and conditional publication remain in place. Navigation metadata still scales with event count; payload bodies do not. The existing incognito host-frame reader is unchanged.

Refresh failures use the existing asynchronous core plugin-state storage, capped at 256 session facts, without storing raw error or transcript content. The cache owner clears each fact after successful publication; Doctor displays unresolved failures.

Evidence

All heavy validation ran on Blacksmith Testbox (blacksmith-testbox, profile openclaw-check). Primary measurements and typechecks: lease tbx_01m38g2xckkz1apk1smezhftg1, Node 24.19.0, run. Final lint, guards, paging tests, and benchmark replay: lease tbx_01m38k1hj8p9r5ay910z20s2sv, run. CI entry-point repair: lease tbx_01m38m3g0gfjjhek1n72nmmd9k, run. Standalone test-cost measurement: lease tbx_01m38mt6r9b7cbwsq61vanjncq, run. All leases stopped after validation.

The opt-in pnpm bench:usage-refresh-memory fixture uses 24,000 events, 6,000 identity rows and 18,000 production zstd rows: 1,186,945,771 decoded bytes (1.105 GiB), with each event below 4 MiB. Both runs use the real refresh worker and its production 512 MiB limit; the baseline substitutes the original reader/scanner from 57f912b5f701 before executing the same harness with --expect-oom.

Measurement Original reader Bounded reader
Outcome ERR_WORKER_OUT_OF_MEMORY Complete, exact reference rollup
Sampled peak worker heap 489.8 MiB 228.9 MiB (53.3% lower)
Refresh duration Failed after 2.39 s Completed in 4.64 s

The final-source replay completed in 4.40 s at 234.4 MiB sampled peak, again with exact rollup equality and below the asserted 384 MiB bound.

Heap sampling uses Worker.getHeapStatistics() every 10 ms; these are observed peaks, not complete allocation profiles. Failure time is not a throughput comparison. The complete rollup matched the bounded JSONL worker reference, independently checked for 24,000 records, 240,000 tokens, and 24,000 synthetic cost units. Rollup SHA-256: f0f184c9b958a74211b6d66678bb1808497d07a96b6b8a84cfb1caabfdc9a856.

  • node scripts/run-vitest.mjs src/infra/session-cost-usage-worker-refresh.test.ts src/infra/session-cost-usage-cache.worker.test.ts src/commands/doctor-usage-cost-cache.test.ts src/infra/session-cost-usage-worker-io.test.ts --maxWorkers=1: 27 tests passed, 65.98 s total including cold worker compilation. New paging file: 5 tests / 7 ms. Changed worker file: 8 tests / 14.93 s; new failure→Doctor→recovery test: 1.76 s.
  • node scripts/check-changed.mjs: all selected checks completed successfully across the initial run and resumed native-plan commands. Core types and all 25 test-typecheck shards passed; script/root-test types, lint, formatting, storage/import-cycle/security guards also passed. The initial run caught optional Worker.resourceLimits typing; lint caught parameter reassignment and benchmark brace/untyped-throw issues. All were corrected and their failed checks replayed successfully.
  • Final node scripts/run-vitest.mjs src/infra/session-cost-usage-worker-refresh.test.ts --maxWorkers=1: 5 passed / 7 ms test time, 22.28 s wrapper wall including cold worker compilation.
  • Final node --import tsx scripts/bench-usage-refresh-memory.ts: passed, same rollup hash as the paired measurement.
  • CI initially flagged the standalone benchmark as an unused file. Registering the real bench:usage-refresh-memory package command fixed discovery without a scanner suppression. node --import ./scripts/tsx.mjs scripts/check-deadcode-unused-files.mts passed with zero findings on Testbox, and the new package command passed the full fixture at 239.3 MiB sampled heap with the same rollup hash.
  • Standalone pnpm test src/infra/session-cost-usage-cache.worker.test.ts --maxWorkers=1: 8 passed, 40.72 s wall with cold worker compilation (14.88 s compiler preparation), 14.918 s summed test time; new failure-health case 1.884 s. Real worker custody, admitted write failures, and persisted Doctor warnings require the worker/host boundary; a helper mock cannot prove that flow.
  • Measured CI cost (run 35946960808, production source unchanged by the later entry-point fix): paging file 5 tests / 0.007 s summed test time on Bun; worker file 8 tests / 12.403 s on Node, including 1.483 s for the new failure-health case. CI did not expose separate per-file wall times.
  • Independent Codex review: no actionable P0–P2 findings.

Initial proof attempts exposed two fixture/setup issues, both corrected before collecting the measurements: missing Testbox checkout dependencies and a synthetic session row that bypassed canonical admission. The final fixture creates the session through its owner. Two later native checksum sync attempts timed out before validation; publishing the reviewed branch and warming a fresh lease recovered native targeted sync. No production data or Gateway deployment was used; this proves the synthetic allocation defect and rollup equality, not attribution of all reported Gateway RSS growth.

Bound decoded SQLite payload pages before parsing, retain compact navigation
facts, and aggregate selected records in their original ancestry order.
Preserve append validation, checkpoint checks, and conditional publication.
Record bounded per-session refresh failures for Doctor and clear them after
successful publication.

The real 512 MiB worker OOMs on the baseline 1.105 GiB synthetic transcript.
The fix completes at 228.9 MiB sampled heap with an identical reference rollup.

Fixes #156898.
@clawsweeper

clawsweeper Bot commented Sep 24, 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 docs Improvements or additions to documentation scripts Repository scripts commands Command implementations size: L labels Sep 24, 2026
@steipete
steipete enabled auto-merge (squash) September 24, 2026 02:27
@clawsweeper

clawsweeper Bot commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 23, 2026, 10:29 PM ET / September 24, 2026, 02:29 UTC.

ClawSweeper review

What this changes

The branch pages SQLite transcript reads for usage rollups, records failed refreshes for Doctor, and adds tests, documentation, and a memory benchmark.

Merge readiness

⛔ Blocked before merge - 4 items remain

Current main still eagerly decodes SQLite transcript ranges, and the linked worker OOM report and real-worker benchmark establish a useful repair that remains needed.

Priority: P1
Reviewed head: 3dae65ad7dfe7ce2e64e9f8b17dfe5a587601541

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong production-worker memory proof supports a useful repair, but warning retirement and existing-state compatibility remain unresolved.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The PR's recorded benchmark exercises the changed production refresh worker against a canonical synthetic SQLite session under the 512 MiB limit: the original reader OOMs, while the bounded reader completes with a matching reference rollup and 234.4 MiB sampled peak. That proves the allocation repair for this scenario, not all reported Gateway RSS growth. The new durable Doctor state has fresh-state coverage but no existing-release upgrade proof.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR's recorded benchmark exercises the changed production refresh worker against a canonical synthetic SQLite session under the 512 MiB limit: the original reader OOMs, while the bounded reader completes with a matching reference rollup and 234.4 MiB sampled peak. That proves the allocation repair for this scenario, not all reported Gateway RSS growth. The new durable Doctor state has fresh-state coverage but no existing-release upgrade proof.
Evidence reviewed 10 items Current main still has the defect: The fetched main reader returns all rows for the requested range, then parses every event JSON string.
Introduced bounded read: The introduced reader limits each SQLite query to 1,024 rows and stops accumulating decoded JSON after roughly 8 MiB, allowing one oversized event.
Branch selection retained: The first pass retains navigation fields; selected event bodies are fetched again in ancestry order before rollup publication.
Findings 1 actionable finding [P2] Retire warnings for deleted sessions
Security None None.

How this fits together

A usage request returns cached cost totals while a background worker refreshes stale session transcripts. The worker writes new rollups, and Doctor reads stored failure facts to explain incomplete totals.

flowchart LR
A[Usage request] --> B[Cached totals]
B --> C{Session stale?}
C --> D[Refresh worker]
D --> E[Bounded SQLite pages]
E --> F[Rollup cache]
D --> G[Failure history]
G --> H[Doctor warning]
Loading

Before merge

  • Retire warnings for deleted sessions (P2) - A failed session can be deleted before it refreshes successfully. This branch clears its durable failure fact only after a rollup write, while Doctor prints every stored fact and --fix leaves it in place, so a deleted session can produce a permanent, unactionable warning. Clear the fact through an owner-checked deletion or liveness path and cover that lifecycle.
  • Resolve merge risk (P1) - The new durable failure records and Doctor read were tested with fresh synthetic state, but no v2026.9.6-to-candidate run demonstrates behavior with an existing shared state database.
  • Complete next step (P2) - Retire warnings for deleted sessions, then demonstrate the new durable Doctor state with a sanitized existing-release state copy before merge.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.

Findings

  • [P2] Retire warnings for deleted sessions — src/infra/session-cost-usage-worker-runtime.ts:505-513
Agent review details

Security

None.

PR surface

Source +152, Tests +208, Docs +6, Other +314. Total +680 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 6 165 13 +152
Tests 2 208 0 +208
Docs 1 6 0 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 1 314 0 +314
Total 10 693 13 +680

Review metrics

Metric Value Why it matters
Implementation and proof footprint production +139 net lines; tests +208; opt-in benchmark +314 The two-pass reader and failure tracking account for the production growth; the new coverage does not exercise warning retirement after session deletion.
Persistent diagnostic state 1 new namespace capped at 256 entries Its lifetime and behavior with existing state matter before merge.

Stored data model

Persistent data-model change detected: serialized state: scripts/bench-usage-refresh-memory.ts, unknown-data-model-change: scripts/bench-usage-refresh-memory.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #156898
Summary: This PR is the linked candidate fix for the open usage-refresh worker OOM report.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Prove the upgrade path (recommended)
    Exercise candidate Doctor and usage refresh with a sanitized v2026.9.6 state copy, recording that existing rows remain usable and the new warning namespace works.

Technical review

Best possible solution:

Keep the bounded SQLite reader, retire failure facts when their sessions are removed, and verify the new Doctor state path against an existing-release state copy.

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

Yes. The PR records an OOM from the original reader in the production 512 MiB worker using a 1.105 GiB synthetic SQLite transcript, and current main retains that eager read; this review did not run current main.

Is this the best way to solve the issue?

Mostly yes. Paging before parsing and preserving branch selection addresses the allocation owner, but the persistent warning needs a deletion lifecycle and existing-state verification.

Full review comments:

  • [P2] Retire warnings for deleted sessions — src/infra/session-cost-usage-worker-runtime.ts:505-513
    A failed session can be deleted before it refreshes successfully. This branch clears its durable failure fact only after a rollup write, while Doctor prints every stored fact and --fix leaves it in place, so a deleted session can produce a permanent, unactionable warning. Clear the fact through an owner-checked deletion or liveness path and cover that lifecycle.
    Confidence: 0.91

Overall correctness: patch is incorrect
Overall confidence: 0.88

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P1: The linked release report records repeated usage-refresh worker OOMs that prevent background cost updates for large sessions.
  • add merge-risk: 🚨 compatibility: Doctor now reads newly persisted failure records, but the PR shows no existing-state upgrade run.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR's recorded benchmark exercises the changed production refresh worker against a canonical synthetic SQLite session under the 512 MiB limit: the original reader OOMs, while the bounded reader completes with a matching reference rollup and 234.4 MiB sampled peak. That proves the allocation repair for this scenario, not all reported Gateway RSS growth. The new durable Doctor state has fresh-state coverage but no existing-release upgrade proof.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.

Label justifications:

  • P1: The linked release report records repeated usage-refresh worker OOMs that prevent background cost updates for large sessions.
  • merge-risk: 🚨 compatibility: Doctor now reads newly persisted failure records, but the PR shows no existing-state upgrade run.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR's recorded benchmark exercises the changed production refresh worker against a canonical synthetic SQLite session under the 512 MiB limit: the original reader OOMs, while the bounded reader completes with a matching reference rollup and 234.4 MiB sampled peak. That proves the allocation repair for this scenario, not all reported Gateway RSS growth. The new durable Doctor state has fresh-state coverage but no existing-release upgrade proof.

Evidence

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/infra/session-cost-usage-worker-refresh.test.ts src/infra/session-cost-usage-cache.worker.test.ts src/commands/doctor-usage-cost-cache.test.ts --maxWorkers=1.
  • [P1] node --import tsx scripts/bench-usage-refresh-memory.ts.
  • [P1] node scripts/check-changed.mjs.

What I checked:

Likely related people:

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

Rank-up moves

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

  • Cover failure, session deletion, and subsequent Doctor output at the owning boundary.
  • Record a v2026.9.6-state to candidate Doctor and refresh check.

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.

@steipete
steipete merged commit 5b90a73 into main Sep 24, 2026
248 of 251 checks passed
@steipete
steipete deleted the steipete/perf-micro-usage-refresh-worker-oom-20260919 branch September 24, 2026 02:50
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 24, 2026
…56937)

Closes openclaw#156898

## What Problem This Solves

Large SQLite sessions can repeatedly exhaust the usage-refresh worker's 512 MiB heap, leaving usage totals missing or stale after an otherwise successful `sessions.usage` response.

## User Impact

Large sessions can finish refreshing without increasing the worker limit. Doctor reports bounded, per-session refresh failures and successful refreshes clear their warnings. No configuration, rollup format, database schema, or migration changes are required. Thanks @Conan-Scott for the detailed report and allocation control.

## Why This Change Was Made

The reader eagerly decoded the entire requested range before aggregation's 128-record batches. It now reads at most 1,024 rows and 8 MiB of decoded JSON per page, with one lookahead event (an individual oversized identity event is still accepted). A first pass retains compact navigation facts; selected bodies then feed the existing aggregation in ancestry order. Append validation, reset/leaf fallback, checkpoint checks, and conditional publication remain in place. Navigation metadata still scales with event count; payload bodies do not. The existing incognito host-frame reader is unchanged.

Refresh failures use the existing asynchronous core plugin-state storage, capped at 256 session facts, without storing raw error or transcript content. The cache owner clears each fact after successful publication; Doctor displays unresolved failures.

## Evidence

All heavy validation ran on Blacksmith Testbox (`blacksmith-testbox`, profile `openclaw-check`). Primary measurements and typechecks: lease `tbx_01m38g2xckkz1apk1smezhftg1`, Node 24.19.0, [run](https://github.com/openclaw/openclaw/actions/runs/35942606687). Final lint, guards, paging tests, and benchmark replay: lease `tbx_01m38k1hj8p9r5ay910z20s2sv`, [run](https://github.com/openclaw/openclaw/actions/runs/35946363096). Both leases stopped after validation.

The opt-in `node --import tsx scripts/bench-usage-refresh-memory.ts` fixture uses 24,000 events, 6,000 identity rows and 18,000 production zstd rows: 1,186,945,771 decoded bytes (1.105 GiB), with each event below 4 MiB. Both runs use the real refresh worker and its production 512 MiB limit; the baseline substitutes the original reader/scanner from `ef700b53f142` before executing the same harness with `--expect-oom`.

| Measurement | Original reader | Bounded reader |
| --- | --- | --- |
| Outcome | `ERR_WORKER_OUT_OF_MEMORY` | Complete, exact reference rollup |
| Sampled peak worker heap | 489.8 MiB | 228.9 MiB (53.3% lower) |
| Refresh duration | Failed after 2.39 s | Completed in 4.64 s |

The final-source replay completed in 4.40 s at 234.4 MiB sampled peak, again with exact rollup equality and below the asserted 384 MiB bound.

Heap sampling uses `Worker.getHeapStatistics()` every 10 ms; these are observed peaks, not complete allocation profiles. Failure time is not a throughput comparison. The complete rollup matched the bounded JSONL worker reference, independently checked for 24,000 records, 240,000 tokens, and 24,000 synthetic cost units. Rollup SHA-256: `f0f184c9b958a74211b6d66678bb1808497d07a96b6b8a84cfb1caabfdc9a856`.

- `node scripts/run-vitest.mjs src/infra/session-cost-usage-worker-refresh.test.ts src/infra/session-cost-usage-cache.worker.test.ts src/commands/doctor-usage-cost-cache.test.ts src/infra/session-cost-usage-worker-io.test.ts --maxWorkers=1`: 27 tests passed, 65.98 s total including cold worker compilation. New paging file: 5 tests / 7 ms. Changed worker file: 8 tests / 14.93 s; new failure→Doctor→recovery test: 1.76 s.
- `node scripts/check-changed.mjs`: all selected checks completed successfully across the initial run and resumed native-plan commands. Core types and all 25 test-typecheck shards passed; script/root-test types, lint, formatting, storage/import-cycle/security guards also passed. The initial run caught optional `Worker.resourceLimits` typing; lint caught parameter reassignment and benchmark brace/untyped-throw issues. All were corrected and their failed checks replayed successfully.
- Final `node scripts/run-vitest.mjs src/infra/session-cost-usage-worker-refresh.test.ts --maxWorkers=1`: 5 passed / 7 ms test time, 22.28 s wrapper wall including cold worker compilation.
- Final `node --import tsx scripts/bench-usage-refresh-memory.ts`: passed, same rollup hash as the paired measurement.
- Independent Codex review: no actionable P0–P2 findings.

Initial proof attempts exposed two fixture/setup issues, both corrected before collecting the measurements: missing Testbox checkout dependencies and a synthetic session row that bypassed canonical admission. The final fixture creates the session through its owner. Two later native checksum sync attempts timed out before validation; publishing the reviewed branch and warming a fresh lease recovered native targeted sync. No production data or Gateway deployment was used; this proves the synthetic allocation defect and rollup equality, not attribution of all reported Gateway RSS growth.
@roboclaw-bot roboclaw-bot mentioned this pull request Sep 24, 2026
2 of 8 tasks
roboclaw-bot added a commit that referenced this pull request Sep 26, 2026
Backport #156446: a050a07
Selected backport #156937: 5b90a73

Project Incognito content at all four existing durable task writers while
retaining lifecycle, cancellation and live completion behavior. Page the
SQLite usage reader and separate navigation from selected payload bodies,
keeping checkpoint, branch and publication semantics.

The original real worker OOMs on the paired synthetic fixture; the repaired
worker completes the exact independent rollup under the unchanged 512MiB
heap limit. This bounds payload retention, not arbitrary navigation size.
38 targeted cases and scoped/composed gates pass; independent review is clean.

No assignment SDK rewrite, durable health namespace, Doctor feature,
schema, version or dependency change. Preserve the usage source's thanks
to @Conan-Scott for the report and allocation control.

Co-authored-by: Vincent Koc <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vyctorbrzezowski <[email protected]>
Co-authored-by: steipete <[email protected]>
Co-authored-by: jalehman <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations docs Improvements or additions to documentation scripts Repository scripts size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] 2026.9.6: usage-cost background refresh repeatedly exhausts worker heap; SQLite refresh materializes full transcript

1 participant