Skip to content

fix(gateway): read usage-cost cache once per agent in sessions.usage - #100054

Merged
vincentkoc merged 1 commit into
openclaw:mainfrom
NianJiuZst:fix/sessions-usage-cache-reparse
Jul 4, 2026
Merged

vincentkoc merged 1 commit into
openclaw:mainfrom
NianJiuZst:fix/sessions-usage-cache-reparse

Conversation

@NianJiuZst

@NianJiuZst NianJiuZst commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Closes #100041

What Problem This Solves

Resolves an issue where operators running the openclaw-control-ui dashboard get chronic false-positive memory pressure: level=warning reason=rss_growth warnings that advise restarting the gateway when nothing is wrong. On every dashboard connect/reconnect, the bootstrap RPC batch calls sessions.usage (default limit=50), which spikes gateway RSS 200-600 MiB in a single ~30s window and trips the rss_growth diagnostic (threshold 512 MiB). GC reclaims it immediately, so it is a transient over-allocation, not a leak.

Why This Change Was Made

The sessions.usage handler loaded each visible session's summary through loadSessionCostSummaryFromCache, and that function unconditionally does a full fs.readFile + JSON.parse of the entire .usage-cost-cache.json on every call with no request-scoped memoization. At limit=50 that is ~50 full re-parses of the whole cache per connect — the burst tracks the limit parameter, not on-disk store size (the reporter confirmed limit=1 → ~19 MiB vs limit=50 → ~450 MiB on an identical store).

The hidden-session path already avoided this by using the batched loadSessionCostSummariesFromCache, which reads and parses the cache at most once per agent. This change unifies the visible and hidden session paths onto that batched loader, so the cache is read once per agent regardless of limit. The visible path already ran in background refresh mode, so no refresh semantics change.

User Impact

A routine dashboard connect no longer allocates hundreds of MiB or trips the memory-pressure alarm. Cache read/parse cost for sessions.usage is now O(agents) instead of O(sessions requested), and no longer grows with the limit request parameter.

Evidence

  • node scripts/run-vitest.mjs src/gateway/server-methods/usage.sessions-usage.test.ts → 36 passed. Tests updated to assert the whole cache is read once per agent (loadSessionCostSummariesFromCache called once) rather than once per session.
  • pnpm tsgo:core and pnpm check:test-types → clean.
  • git diff --numstat: net -49 prod LOC (removes the duplicate per-session load path).
  • Note: one pre-existing DST test (fills every calendar day ... spring-forward) fails on this macOS checkout at the base commit too, unrelated to this change (timezone/Intl environment dependent; CI truth is Linux Node 24).

Maintainer Validation

  • Blacksmith Testbox tbx_01kwqd945cj8jmjdffd0j8g40t (jade-prawn), exact base vs exact head with 50 real session transcripts and a ~20 MiB durable usage cache: base transient Gateway RSS growth +1431.01 MiB; head +0.11 MiB. Both RPC calls returned all 50 sessions; the head stays safely below the 512 MiB rss_growth warning threshold.
  • corepack pnpm test:serial src/gateway/server-methods/usage.sessions-usage.test.ts -> 36/36 passed.
  • corepack pnpm check:changed -- src/gateway/server-methods/usage.ts src/gateway/server-methods/usage.sessions-usage.test.ts -> passed on the same Testbox.
  • Fresh branch autoreview: no accepted or actionable findings.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M labels Jul 4, 2026
@clawsweeper

clawsweeper Bot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 4, 2026, 6:36 PM ET / 22:36 UTC.

Summary
The PR changes the gateway sessions.usage handler and focused tests to group visible and hidden included sessions by agent and call the batched usage-cost cache loader once per agent.

PR surface: Source -48, Tests -24. Total -72 across 2 files.

Reproducibility: yes. at source/proof level. Current main builds one visible-session cache-summary task per included visible session and that helper reads/parses the durable cache, while Testbox proof showed the validated head eliminating the RSS spike on a real session/cache setup.

Review metrics: 1 noteworthy metric.

  • Usage-cost cache read fanout: up to one read per visible included session -> one batched read per agent. This is the central performance invariant that prevents dashboard reconnects from repeatedly reparsing the same durable cache.

Stored data model
Persistent data-model change detected: persistent cache schema: src/gateway/server-methods/usage.sessions-usage.test.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #100041
Summary: This PR is the direct candidate fix for the linked memory-pressure report; adjacent usage-cache and gateway-outage items do not supersede it.

Members:

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

Merge readiness
Overall: 🦞 diamond lobster
Proof: 🦞 diamond lobster
Patch quality: 🦞 diamond lobster
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Risk before merge

  • [P1] The live RSS proof was recorded on the earlier equivalent head before the current rebase-style force-push; current head preserves the same narrow two-file patch, but maintainer landing should still wait for current-head gates.

Maintainer options:

  1. Decide the mitigation before merge
    Land the current-head batched-loader fix after normal gates, and keep broader gateway usage isolation or cache-storage redesign work in separate follow-up items.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Next step before merge

  • No ClawSweeper repair is needed; the remaining action is maintainer review plus current-head gates before landing the PR or closing the linked issue through the merge.

Security
Cleared: The diff only changes gateway usage aggregation code and colocated tests; it does not touch secrets, dependencies, workflows, install scripts, or other supply-chain surfaces.

Review details

Best possible solution:

Land the current-head batched-loader fix after normal gates, and keep broader gateway usage isolation or cache-storage redesign work in separate follow-up items.

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

Yes, at source/proof level. Current main builds one visible-session cache-summary task per included visible session and that helper reads/parses the durable cache, while Testbox proof showed the validated head eliminating the RSS spike on a real session/cache setup.

Is this the best way to solve the issue?

Yes. Reusing the existing batched helper is the narrowest maintainable fix for this bug; threshold tuning, dashboard debounce, a new memoization layer, or broader gateway isolation would be less direct for the reported false-positive RSS growth.

AGENTS.md: found and applied where relevant.

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

Label changes

Label justifications:

  • P2: The PR fixes a focused gateway memory-pressure false-positive path with limited blast radius and no reported data-loss or security impact.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Maintainer Testbox live output shows the validated head reducing transient Gateway RSS growth from +1431.01 MiB on base to +0.11 MiB with 50 real session transcripts and a durable cache; no contributor action is needed.
  • proof: sufficient: Contributor real behavior proof is sufficient. Maintainer Testbox live output shows the validated head reducing transient Gateway RSS growth from +1431.01 MiB on base to +0.11 MiB with 50 real session transcripts and a durable cache; no contributor action is needed.
Evidence reviewed

PR surface:

Source -48, Tests -24. Total -72 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 41 89 -48
Tests 1 56 80 -24
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 97 169 -72

What I checked:

  • Repository policy read: Read the full root AGENTS.md and scoped gateway AGENTS.md files; gateway hot-path and full-path review guidance shaped the caller, callee, sibling test, and proof checks. (AGENTS.md:1, 65e12328aa20)
  • Current main still has the repeated visible-session cache path: Current main slices visible sessions.usage entries and creates one loadSessionCostSummaryFromCache task per included visible session, which is the fanout the PR is replacing. (src/gateway/server-methods/usage.ts:1201, 65e12328aa20)
  • Single-session helper reads the durable cache per call: loadSessionCostSummaryFromCache calls readUsageCostCache, which performs a full file read and JSON parse; the existing batched helper reads one cache snapshot for the session batch. (src/infra/session-cost-usage.ts:1799, 65e12328aa20)
  • PR head uses the batched per-agent path: At current PR head, the handler groups every included visible and hidden session by agent, then calls loadSessionCostSummariesFromCache once for each agent group. (src/gateway/server-methods/usage.ts:1191, 1d19215a865d)
  • Focused tests cover the batching invariant: The updated tests assert same-agent sessions call the batched loader once and that limit-restricted pages still aggregate all sessions through the batched cache read. (src/gateway/server-methods/usage.sessions-usage.test.ts:320, 1d19215a865d)
  • Real behavior proof: Maintainer validation reports Blacksmith Testbox tbx_01kwqd945cj8jmjdffd0j8g40t with 50 real session transcripts and a ~20 MiB durable usage cache: base RSS growth +1431.01 MiB, validated head +0.11 MiB, focused tests passed, and path-scoped changed checks passed. (c61b347fc863)

Likely related people:

  • Takhoffman: Authored/merged the token usage dashboard PR that introduced the sessions.usage surface and later fixed multi-agent sessions.usage discovery in the same gateway path. (role: feature owner and merger; confidence: high; commits: 8a352c8f9dfd, 9271fcb3d49f; files: src/gateway/server-methods/usage.ts, src/infra/session-cost-usage.ts)
  • mcinteerj: Authored the original backend token usage dashboard commits in the merged feature PR, including the sessions.usage endpoint family and cost/session analytics work. (role: original feature contributor; confidence: medium; commits: cf7658da0f9b, 853a9b0e9b93; files: src/gateway/server-methods/usage.ts, src/infra/session-cost-usage.ts)
  • Marvinthebored: Authored the durable transcript aggregate cache work that introduced the .usage-cost-cache.json read/refresh path used by usage.cost and sessions.usage. (role: durable usage-cache feature contributor; confidence: high; commits: a64b30705fab; files: src/infra/session-cost-usage.ts, src/gateway/server-methods/usage.ts)
  • hclsys: Authored the merged background-refresh mitigation for the same gateway usage request path and usage-cost cache area. (role: adjacent fix contributor; confidence: high; commits: 845da0ed8f8c; files: src/gateway/server-methods/usage.ts, src/infra/session-cost-usage.ts, src/gateway/server-methods/usage.sessions-usage.test.ts)
  • vincentkoc: Is assigned on this PR, supplied the Testbox validation, and force-pushed the current rebase-style head that preserves the narrow two-file patch. (role: reviewer/validator and recent adjacent contributor; confidence: medium; commits: 1d19215a865d, e085fa1a3ffd; files: src/gateway/server-methods/usage.ts, src/infra/session-cost-usage.ts, src/gateway/server-methods/usage.sessions-usage.test.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.
Review history (5 earlier review cycles)
  • reviewed 2026-07-04T18:37:32.161Z sha c61b347fc8633607d734f221292128e772fae658 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-04T21:18:58.890Z sha c61b347fc8633607d734f221292128e772fae658 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-04T21:25:32.932Z sha c61b347fc8633607d734f221292128e772fae658 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-04T21:47:43.644Z sha c61b347fc8633607d734f221292128e772fae658 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-04T22:06:24.128Z sha c61b347fc8633607d734f221292128e772fae658 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added 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. P2 Normal backlog priority with limited blast radius. labels Jul 4, 2026
@vincentkoc vincentkoc self-assigned this Jul 4, 2026
@vincentkoc

vincentkoc commented Jul 4, 2026 •

Copy link
Copy Markdown
Member

maintainer validation is complete.

  • Blacksmith Testbox tbx_01kwqd945cj8jmjdffd0j8g40t (jade-prawn): exact base vs exact head, 50 real session transcripts, ~20 MiB durable usage cache.
  • base: transient Gateway RSS growth +1431.01 MiB
  • head: transient Gateway RSS growth +0.11 MiB
  • both calls returned all 50 sessions; head remains below the 512 MiB rss_growth warning threshold.
  • focused test: 36/36 passed.
  • path-scoped check:changed: passed.
  • fresh branch autoreview: no accepted or actionable findings.
  • repo-native review artifacts validated with recommendation READY FOR /prepare-pr.
  • contributor head synced onto current main via scripts/pr prepare-sync-head 100054; final head 1d19215a865d5bd7128f414c2e03ef1b1a83ecfe.
  • exact-head CI workflow 28721708115: passed with no failed jobs.
  • OPENCLAW_TESTBOX=1 scripts/pr prepare-run 100054: passed at final exact head; hosted exact-head gates passed.
  • known proof gaps: none.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. 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 Jul 4, 2026
The sessions.usage RPC loaded each visible session's summary via
loadSessionCostSummaryFromCache, which re-reads and re-parses the entire
.usage-cost-cache.json on every call. At the dashboard's default limit=50
that is ~50 full parses per connect, spiking RSS 200-600 MiB and tripping
the gateway rss_growth memory-pressure alarm with a false positive.

Unify the visible and hidden session paths onto the batched
loadSessionCostSummariesFromCache loader, which reads and parses the cache
at most once per agent regardless of limit.

Fixes openclaw#100041
@vincentkoc
vincentkoc force-pushed the fix/sessions-usage-cache-reparse branch from c61b347 to 1d19215 Compare July 4, 2026 22:30
@vincentkoc
vincentkoc merged commit efe4a59 into openclaw:main Jul 4, 2026
96 checks passed
@vincentkoc

Copy link
Copy Markdown
Member

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 5, 2026
…penclaw#100054)

The sessions.usage RPC loaded each visible session's summary via
loadSessionCostSummaryFromCache, which re-reads and re-parses the entire
.usage-cost-cache.json on every call. At the dashboard's default limit=50
that is ~50 full parses per connect, spiking RSS 200-600 MiB and tripping
the gateway rss_growth memory-pressure alarm with a false positive.

Unify the visible and hidden session paths onto the batched
loadSessionCostSummariesFromCache loader, which reads and parses the cache
at most once per agent regardless of limit.

Fixes openclaw#100041
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. 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.

[Bug]: memory pressure

2 participants