Repository navigation
fix(usage): prevent refresh OOMs on large SQLite sessions - #156937
Conversation
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.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: blocked before merge. Reviewed September 23, 2026, 10:29 PM ET / September 24, 2026, 02:29 UTC. ClawSweeper reviewWhat this changesThe 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 Review scores
Verification
How this fits togetherA 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]
Before merge
Findings
Agent review detailsSecurityNone. PR surfaceSource +152, Tests +208, Docs +6, Other +314. Total +680 across 10 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest 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:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against f626e618a764. LabelsLabel changes:
Label justifications:
EvidenceAcceptance criteria:
What I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
|
…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.
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]>
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.usageresponse.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, profileopenclaw-check). Primary measurements and typechecks: leasetbx_01m38g2xckkz1apk1smezhftg1, Node 24.19.0, run. Final lint, guards, paging tests, and benchmark replay: leasetbx_01m38k1hj8p9r5ay910z20s2sv, run. CI entry-point repair: leasetbx_01m38m3g0gfjjhek1n72nmmd9k, run. Standalone test-cost measurement: leasetbx_01m38mt6r9b7cbwsq61vanjncq, run. All leases stopped after validation.The opt-in
pnpm bench:usage-refresh-memoryfixture 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 from57f912b5f701before executing the same harness with--expect-oom.ERR_WORKER_OUT_OF_MEMORYThe 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 optionalWorker.resourceLimitstyping; lint caught parameter reassignment and benchmark brace/untyped-throw issues. All were corrected and their failed checks replayed successfully.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.node --import tsx scripts/bench-usage-refresh-memory.ts: passed, same rollup hash as the paired measurement.bench:usage-refresh-memorypackage command fixed discovery without a scanner suppression.node --import ./scripts/tsx.mjs scripts/check-deadcode-unused-files.mtspassed 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.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.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.