Skip to content

fix(gateway): bound all-agent usage cache concurrency - #101589

Merged
vincentkoc merged 2 commits into
openclaw:mainfrom
zw-xysk:fix/usage-all-agent-concurrency-101552
Jul 7, 2026
Merged

vincentkoc merged 2 commits into
openclaw:mainfrom
zw-xysk:fix/usage-all-agent-concurrency-101552

Conversation

@zw-xysk

@zw-xysk zw-xysk commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

usage.cost with agentScope: "all" started one usage-cost cache load for
every configured agent through an unbounded Promise.all. Large multi-agent
deployments could therefore multiply cache reads, transcript enumeration, and
background refresh work at once.

Fixes #101552.

Why This Change Was Made

  • The sibling sessions.usage path already bounds the same class of per-agent
    usage-cache work.
  • Both paths now share USAGE_AGENT_LOAD_CONCURRENCY = 12.
  • errorMode: "stop" plus rethrowing firstError preserves the original
    Promise.all failure behavior.
  • The handler remains the correct owner boundary because it creates the
    all-agent fan-out.

The issue originally described SQLite connection-pool starvation. Direct
inspection of loadCostUsageSummaryFromCache shows filesystem-backed usage
cache and transcript work instead, so this PR intentionally uses the narrower
source-backed wording.

User Impact

  • All-agent cost reports still include every configured agent and preserve the
    same aggregation result.
  • No more than 12 per-agent cache loads run concurrently.
  • A failed per-agent load still fails the request instead of returning partial
    totals.
  • No configuration, API, or persisted-data shape changes.

Evidence

  • node scripts/run-vitest.mjs src/gateway/server-methods/usage.test.ts
    (2 files, 62 tests passed)
  • node scripts/run-oxlint.mjs src/gateway/server-methods/usage.ts src/gateway/server-methods/usage.test.ts
  • ./node_modules/.bin/oxfmt --check src/gateway/server-methods/usage.ts src/gateway/server-methods/usage.test.ts
  • git diff --check
  • Blacksmith Testbox tbx_01kwyrv80bmm6hxj5xxyyatsdb:
    pnpm check:changed passed
  • Fresh branch autoreview found no actionable issues

The regression test uses a deterministic promise gate. It proves that only 12
of 13 configured agent loads start before release, then verifies all 13 totals
are aggregated after the gate opens.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S labels Jul 7, 2026
@zw-xysk

zw-xysk commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 7, 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 commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 7, 2026, 1:27 PM ET / 17:27 UTC.

Summary
The PR replaces unbounded all-agent usage.cost cache loads with the existing bounded concurrency runner and adds a regression test for the cap.

PR surface: Source +7, Tests +57. Total +64 across 2 files.

Reproducibility: yes. at source level rather than a live outage replay. Origin/main and v2026.6.11 call loadCostUsageSummaryFromCache once per configured agent inside raw Promise.all, and the PR adds a deterministic test for the bounded peak concurrency behavior.

Review metrics: none identified.

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

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #101552
Summary: This PR is the strongest current candidate fix for the open all-agent usage.cost fan-out issue; two sibling PRs target the same root cause with weaker proof/readiness, while the broader Gateway starvation issue remains only a partial overlap.

Members:

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

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🐚 platinum hermit
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

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

Rank-up moves:

  • none.

Risk before merge

  • [P1] The branch is behind current main, so exact-head validation should be refreshed before landing even though GitHub reports it mergeable.
  • [P1] This narrow cap does not settle the broader Gateway usage/cost memory-pressure and event-loop starvation tracker at Gateway event loop starvation and HTTP/WS outage during sessions usage/cost under memory pressure #86718.
  • [P0] No live 100-agent outage replay was run in this read-only review; the verdict relies on source proof, the focused regression test, and existing terminal/Testbox evidence.

Maintainer options:

  1. Decide the mitigation before merge
    Land the bounded gateway usage.cost fan-out fix after exact-head checks, close Unbounded concurrency in usage DB queries causes SQLite starvation #101552 after merge, and keep broader usage/cost workload isolation on Gateway event loop starvation and HTTP/WS outage during sessions usage/cost under memory pressure #86718.
  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 job is needed; the branch already contains the narrow fix and needs ordinary maintainer review plus exact-head checks.

Security
Cleared: The diff only changes gateway usage concurrency and a focused test; it does not add dependencies, workflows, credentials, downloads, package metadata, or other supply-chain surface.

Review details

Best possible solution:

Land the bounded gateway usage.cost fan-out fix after exact-head checks, close #101552 after merge, and keep broader usage/cost workload isolation on #86718.

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

Yes, at source level rather than a live outage replay. Origin/main and v2026.6.11 call loadCostUsageSummaryFromCache once per configured agent inside raw Promise.all, and the PR adds a deterministic test for the bounded peak concurrency behavior.

Is this the best way to solve the issue?

Yes. The gateway handler owns the all-agent fan-out, and reusing the existing bounded concurrency helper matches the sibling sessions.usage pattern while preserving aggregation and error behavior.

AGENTS.md: found and applied where relevant.

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

Label changes

Label justifications:

  • P2: This is a focused Gateway stability bug-fix PR for large all-agent usage-cost queries, with limited blast radius and no evidence of an active release emergency.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR has proof-sufficient review state and terminal/Testbox evidence for the changed backend behavior, including the focused all-agent concurrency regression test; no contributor proof action is needed.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR has proof-sufficient review state and terminal/Testbox evidence for the changed backend behavior, including the focused all-agent concurrency regression test; no contributor proof action is needed.
Evidence reviewed

PR surface:

Source +7, Tests +57. Total +64 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 21 14 +7
Tests 1 57 0 +57
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 78 14 +64

What I checked:

  • Repository policy read: Read the full root AGENTS.md plus the scoped gateway and server-methods AGENTS.md files; their gateway hot-path and whole-path review guidance shaped the caller/callee, sibling-path, and test inspection. (AGENTS.md:1, fa84741f93b9)
  • Current main still has unbounded fan-out: On origin/main, loadAllAgentCostUsageSummary maps every configured agent into loadCostUsageSummaryFromCache and awaits the full list through raw Promise.all. (src/gateway/server-methods/usage.ts:867, b88f80940add)
  • Latest release remains affected: The latest release tag v2026.6.11 contains the same all-agent Promise.all(agentIds.map(...loadCostUsageSummaryFromCache...)) shape. (src/gateway/server-methods/usage.ts:811, e085fa1a3ffd)
  • PR applies the bounded worker-pool pattern: The PR changes the all-agent cost path to lazy per-agent tasks through runTasksWithConcurrency, uses a shared 12-agent limit, and rethrows the first task error before aggregation. (src/gateway/server-methods/usage.ts:864, 062a5ef7ef9f)
  • Sibling usage path supports the fix shape: The existing sessions.usage handler already uses runTasksWithConcurrency with a 12-agent limit and errorMode: "stop" for per-agent usage-cache loads in the same module. (src/gateway/server-methods/usage.ts:1271, b88f80940add)
  • Concurrency helper contract checked: runTasksWithConcurrency starts task factories lazily, clamps the worker count to the limit, preserves result indexes, and reports hasError plus firstError for callers that need fail-fast behavior. (src/utils/run-with-concurrency.ts:27, b88f80940add)

Likely related people:

  • Tak Hoffman: Authored the merged token usage dashboard work and a later multi-agent sessions.usage discovery fix in the same gateway usage surface. (role: feature owner; confidence: high; commits: 8a352c8f9dfd, 9271fcb3d49f; files: src/gateway/server-methods/usage.ts, src/infra/session-cost-usage.ts)
  • steipete: Authored early usage-cost summary/cache work and later refactors touching the same gateway and session-cost usage files. (role: adjacent usage-cost contributor; confidence: high; commits: 3ce1ee84ace4, 0e17e55be902, 990413534ae4; files: src/gateway/server-methods/usage.ts, src/infra/session-cost-usage.ts)
  • NianJiu: Authored the merged sibling fix that reads usage-cost cache once per agent in sessions.usage, which is the closest existing pattern for this PR. (role: adjacent fix contributor; confidence: medium; commits: efe4a59ceb75; files: src/gateway/server-methods/usage.ts, src/gateway/server-methods/usage.sessions-usage.test.ts)
  • vincentkoc: Assigned to the PR and authored the current head commit that consolidates the cost and sessions usage paths onto one shared concurrency cap. (role: likely follow-up owner; confidence: medium; commits: 062a5ef7ef9f; files: src/gateway/server-methods/usage.ts, src/gateway/server-methods/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 (1 earlier review cycle)
  • reviewed 2026-07-07T11:25:41.246Z sha 0dace0fa35f7cf8f76f19bebd0be62c373bf7670 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P2 Normal backlog priority with limited blast radius. labels Jul 7, 2026
zw-xysk and others added 2 commits July 7, 2026 10:21
…e starvation

Replace raw Promise.all in loadAllAgentCostUsageSummary with
runTasksWithConcurrency (limit=12), matching the sibling sessions.usage
pattern. Unbounded concurrent usage-cost cache reads saturated the SQLite
connection pool for deployments with 100+ agents, causing SQLITE_BUSY
timeouts or gateway memory crashes.

Fixes openclaw#101552
@vincentkoc
vincentkoc force-pushed the fix/usage-all-agent-concurrency-101552 branch from 0dace0f to 062a5ef Compare July 7, 2026 17:22
@vincentkoc vincentkoc changed the title fix(gateway): bound all-agent usage.cost concurrency to prevent SQLite starvation fix(gateway): bound all-agent usage cache concurrency Jul 7, 2026
@vincentkoc vincentkoc self-assigned this Jul 7, 2026
@vincentkoc

Copy link
Copy Markdown
Member

Land-ready proof for exact head 062a5ef7ef9f11b5c89d27fb640686bbfcb00116:

  • The all-agent usage.cost path now shares the existing 12-load concurrency policy with sibling sessions.usage.
  • errorMode: "stop" plus firstError rethrow preserves the prior all-or-nothing request behavior.
  • The deterministic 13-agent regression proves only 12 cache loads start before release, then verifies all 13 totals are aggregated.
  • node scripts/run-vitest.mjs src/gateway/server-methods/usage.test.ts: 2 files, 62 tests passed.
  • node scripts/run-oxlint.mjs src/gateway/server-methods/usage.ts src/gateway/server-methods/usage.test.ts: passed.
  • ./node_modules/.bin/oxfmt --check src/gateway/server-methods/usage.ts src/gateway/server-methods/usage.test.ts: passed.
  • git diff --check: passed.
  • Blacksmith Testbox tbx_01kwyrv80bmm6hxj5xxyyatsdb: pnpm check:changed passed.
  • Hosted exact-head CI: https://github.com/openclaw/openclaw/actions/runs/28885384161
  • Fresh branch autoreview: no actionable findings.

Source inspection corrected the issue's mechanism: loadCostUsageSummaryFromCache performs usage-cache reads, transcript enumeration, stale-file detection, and background refresh scheduling. This bounds that real filesystem/cache fan-out; it does not claim SQLite connection-pool starvation.

@vincentkoc
vincentkoc merged commit e5c2247 into openclaw:main Jul 7, 2026
213 of 223 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 8, 2026
* fix(gateway): bound all-agent usage.cost concurrency to prevent SQLite starvation

Replace raw Promise.all in loadAllAgentCostUsageSummary with
runTasksWithConcurrency (limit=12), matching the sibling sessions.usage
pattern. Unbounded concurrent usage-cost cache reads saturated the SQLite
connection pool for deployments with 100+ agents, causing SQLITE_BUSY
timeouts or gateway memory crashes.

Fixes openclaw#101552

* fix(gateway): share usage cache concurrency cap

---------

Co-authored-by: Vincent Koc <[email protected]>
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: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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.

Unbounded concurrency in usage DB queries causes SQLite starvation

2 participants