Skip to content

fix: reduce memory during SQLite usage refresh - #201064

Merged
vincentkoc merged 1 commit into
openclaw:mainfrom
Fuma2013:fix/usage-rollup-197430
Nov 26, 2026
Merged

vincentkoc merged 1 commit into
openclaw:mainfrom
Fuma2013:fix/usage-rollup-197430

Conversation

@Fuma2013

@Fuma2013 Fuma2013 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Related: #197430

What Problem This Solves

The background usage refresh can run out of memory on long SQLite chat histories, leaving token and cost totals stale. The paged reader limits decoded payloads, but the worker retains the navigation projection and every parsed billing entry while building the exact-timestamp rollup.

User Impact

Lower peak heap during SQLite usage refresh without widening time buckets, dropping entries, or changing the cache format. No configuration change or migration.

Why This Change Was Made

Resolve billing, latency ancestry and the checkpoint first. Release the navigation projection, then drain the owned billing list in the same order into the existing pricing batches. The latency lookup uses weak keys so it does not keep processed entries alive. Exact buckets still scale with the number of distinct timestamps; this reduces overlapping memory, not the size of the final rollup.

Evidence

  • On current main (6ec27bd), the production SQLite scan with an in-memory SQLite fixture of 270,391 billed rows at unique millisecond timestamps reached 473 MiB maximum sampled post-GC JS heap. The candidate reached 297 MiB (37% lower), with identical exact-timestamp bucket output (SHA-256 d86644baa3562655253cf070d3254feee0fa59bdeb7cbb3e7108c429bad5cb53). This measures the scan and aggregation, not a production worker restart or an end-to-end cache publication.
  • 60 targeted tests passed across refresh, snapshots, scan, codec and SQLite cache, including append, inherited history, rewinds, and branch-local latency. Targeted type-aware lint, format and diff checks passed.
  • Reviewed the final diff locally against the billing and checkpoint contracts; the standalone autoreview helper was not installed.

End-to-end Gateway proof

Tested the unchanged PR head 91e8b402593a1fbd9ef07a32963d481ca7a3f67d (macOS arm64, Node 24.22.3). Seeded a fresh, isolated agent SQLite store through the existing transcript batch writer with 270,391 synthetic billed messages, each at a distinct millisecond. Started the real loopback Gateway with its usage sidecar enabled, without a heap override or mocks for the worker, SQLite, or cache. Polled sessions.usage from an empty cache until fresh, asserted exact expected totals, and checked the persisted SQLite cache after clean shutdown.

Redacted terminal evidence (selected fields; the worker measurement uses sampling, not forced GC):

SQLite input: 270391 rows, 270391 unique generated timestamps
sessions.usage: cacheStatus=fresh input=540782 output=270391 totalTokens=811173 totalCost=33798.875
usage-cost refresh worker: old-generation limit=512 MiB, sampled peak JS heap=440 MiB (3526 samples)
Persisted cache: session-cost-usage-rollup-v3=1, session-cost-usage-projection-v2=1, session-cost-usage-quarters-v1=1
Gateway shutdown: completed cleanly; harness exit=0

The worker was sampled externally with Node's Worker.getHeapStatistics() while the Gateway owned the real refresh. This is a candidate-only end-to-end pass; the separate post-GC benchmark above is the before/after comparison. No production logs, personal chat data, or credentials were used.

@clawsweeper

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

@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. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. 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 18, 2026
@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR releases navigation records and consumed billing entries earlier during SQLite usage aggregation.

Example: Refresh 270,391 billed messages with distinct millisecond timestamps.

  • Before: The contributor measured 473 MiB maximum sampled post-GC heap during scanning and aggregation.
  • After: The comparable scan measured 297 MiB with identical bucket output; a separate real Gateway run completed and published 811,173 tokens.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong production-path evidence and a correct, narrowly scoped patch; overall scope remains a partial repair of the linked production failure, and broad production CI has not run.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The new exact-head terminal evidence exercises the actual Gateway usage worker against 270,391 distinct-timestamp SQLite messages under its existing heap limit, reaches fresh expected totals, verifies persisted cache partitions, and completes shutdown; this clears the earlier scan-only proof hold.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Partial
User problem: Long SQLite histories can exhaust the background usage worker and leave token and cost totals stale.
Reason: Measured memory savings justify the small change, which preserves exact accounting and uses existing owners; retaining Related rather than claiming complete resolution is appropriate.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR provides a focused, useful memory reduction with no identified correctness defect; the new Gateway evidence satisfies the previous proof request, while draft status and production CI remain outstanding.

Priority: P2
Reviewed head: 91e8b402593a1fbd9ef07a32963d481ca7a3f67d

Before merge

None.

Findings

None.

Agent review details

How this fits together

The background usage worker reads SQLite transcript events, resolves billing and branch ancestry, aggregates timestamp buckets, and prepares usage-cache partitions.

flowchart TD
A[SQLite transcript events] --> B[Paged transcript reader]
B --> C[Billing and ancestry selection]
C --> D[Release navigation records]
D --> E[Drain entries through pricing batches]
E --> F[Exact timestamp rollup]
F --> G[Usage cache publication]
Loading

Technical review

Best possible solution:

Retain this small lifetime optimization in the existing scan owner while keeping the broader production OOM report open.

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

Source confirms overlapping retention of navigation, billing entries, and growing timestamp buckets; contributor measurements demonstrate the reduction, but this review did not independently reproduce the reported production OOM.

Is this the best way to solve the issue?

The patch is a small, appropriate optimization: compute navigation facts first, release the owned projection, preserve billing order, and avoid strong timing keys without changing accounting or storage contracts.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Billing ancestry and latency lookup keeps the original intent (d59fe05: Preserve historically billed branches and resolve each reply's latency against its canonical user ancestor after in-place navigation.)
  • SQLite scan projection and checkpoints keeps the original intent (23dee30: Decode pages once, retain compact navigation contributions, and resume incremental scans using the transcript rewrite watermark.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 23dee30 adds src/infra/session-cost-usage-worker-refresh.ts:278 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 23dee30706d6; files: src/infra/session-cost-usage-worker-refresh.ts)
  • Ayaan Zaidi: Raw commit d59fe05 adds src/infra/session-cost-usage-inherited.ts:148 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: d59fe0563f66; files: src/infra/session-cost-usage-inherited.ts)

PR surface

Source +11. Total +11 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 14 3 +11
Tests 0 0 0 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 14 3 +11

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.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Reduces memory pressure in background usage reporting; the demonstrated impact is stale token/cost totals while Gateway and chat remain operational.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster 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 (1 earlier review cycle)
  • reviewed 2026-11-18T07:35:16.808Z sha 91e8b40 :: needs real behavior proof before merge. :: none

Reviewed November 18, 2026, 12:42 PM ET / 17:42 UTC (Revision 2).

@Fuma2013

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Nov 18, 2026
@Fuma2013
Fuma2013 marked this pull request as ready for review November 19, 2026 03:11
@vincentkoc vincentkoc self-assigned this Nov 26, 2026
@vincentkoc
vincentkoc merged commit 625045f into openclaw:main Nov 26, 2026
117 checks passed
@vincentkoc

Copy link
Copy Markdown
Member

Merged via squash.

vincentkoc added a commit that referenced this pull request Nov 26, 2026
…irement-rule

* origin/main: (172 commits)
  test(gateway): expect a revoked person's Goal retry to be hidden as not found (#205698)
  fix: keep browser disabled when only hardening relay authentication (#203137)
  fix: recover Linux stream automations after command-anchor crashes (#203149)
  fix(whatsapp): identify voice-note captions as text in delivery receipts (#205381)
  fix(test): unblock restart-auth plugin and worker publication qualification (#205679)
  chore(ui): refresh control ui locales (#205691)
  fix: reduce memory during SQLite usage refresh (#201064)
  fix(plugins): readmit native captures with a dangling host link
  chore(i18n): refresh native locales (#205680)
  fix(update): hash SQLite lock bytes as zeros so Windows exclusion cannot fail verification (#205668)
  fix(skill-workshop): skip the skill diet for skills with Markdown outside support directories (#204881)
  fix(plugins): clarify dated SDK migration notices (#200932)
  fix: keep the resident launcher when reinstalling Gateway (#205655)
  fix: show the whole reply when you reopen a TUI session (#200455)
  test(ui): wait for restored speech player authorization (#199502)
  feat: let agents post approved GitHub comments (#204301)
  fix(agents): honor imageMaxDimensionPx at the provider and CLI image handoffs (#205663)
  chore(ui): refresh control ui locales (#205664)
  fix(google): preserve playback when Google Live splits audio into parts (#205364)
  fix: show named characters in exported session messages (#205362)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 26, 2026
tideclaw-bot pushed a commit that referenced this pull request Nov 28, 2026
Co-authored-by: Fuma2013 <[email protected]>
(cherry picked from commit 625045f)
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
Co-authored-by: Fuma2013 <[email protected]>
(cherry picked from commit 625045f)

Companion audit: 740dfdb changes UI throughput metrics and c821a8a changes whole-refresh history building; independent of draining consumed inherited projections.

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

P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XS 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.

2 participants