Skip to content

fix(gateway): prevent idle CPU spikes on multi-agent hosts - #124334

Merged
steipete merged 1 commit into
mainfrom
steipete/fix-gateway-configured-session-discovery-hot-loop
Aug 16, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/fix-gateway-configured-session-discovery-hot-loop

Conversation

@steipete

@steipete steipete commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where operators with several configured agents could see a freshly started Gateway consume 100–140% idle CPU and 1.8–2.7 GB RSS, with intermittent HTTP, RPC, and WebSocket handshake timeouts.

On Molty's 11-agent installation, strace recorded about 27,684 failed readlink calls in 12 seconds and 8,735 path calls in 3 seconds. Gateway dashboard prewarm resolves session stores once per configured agent, while each resolution was unnecessarily enumerating every agent root and retired sessions.json path.

Why This Change Was Made

Configured agents already own deterministic canonical session-store paths. After those direct targets are validated, the resolver now returns their deduplicated paths before broad filesystem discovery. Retired and manually created agents still use the existing broad discovery path unchanged.

This repairs the discovery owner directly and avoids adding a cache or downstream Gateway workaround. It does not change config schema, storage format, API, generated baselines, or canonical session ownership.

User Impact

Multi-agent Gateways avoid quadratic session-store discovery during startup prewarm, reducing idle filesystem churn and the CPU/RSS pressure that could delay dashboard and protocol handshakes. Retired/manual agent discovery is preserved.

Evidence

  • Live Molty evidence: 11 agent databases; 100–140% idle CPU; 1.8–2.7 GB RSS; approximately 27,684 failed readlink calls in 12 seconds and 8,735 path calls in 3 seconds.
  • Pre-fix regression: src/config/sessions/targets.test.ts failed 1/40 because resolveAgentSessionDirsFromAgentsDirSync was called twice (configured custom root plus default state root).
  • Post-fix: node scripts/run-vitest.mjs src/config/sessions/targets.test.ts — 40/40 passed.
  • Post-fix siblings: node scripts/run-vitest.mjs src/gateway/server-startup-handler-prewarm.test.ts src/gateway/server.sessions.list-store-materialization.test.ts — 12/12 passed.
  • Targeted type-aware Oxlint, Oxfmt, and git diff --check passed.
  • node scripts/check-changed.mjs --dry-run -- src/config/sessions/targets.ts src/config/sessions/targets.test.ts selected core, coreTests. The remote router's installed Crabbox binary failed its version/help sanity check before execution, so the documented trusted-source local fallback ran the identical changed gate; all guards, production/test typechecks, lint, and architecture checks passed.
  • .agents/skills/autoreview/scripts/autoreview --mode branch --base origin/main passed cleanly with no accepted/actionable findings on the final rebased head.
  • Exact-head CI: https://github.com/openclaw/openclaw/actions/runs/31919883652 — passed for cd7a9d2dfe139e43a142a9e3df8d6b23ba917fec.
  • Production LOC: +6/−0. Tests: +18/−9.
  • Screenshots: not applicable; this has no visual change.

ClawSweeper review disposition

The P1 finding and both optional rank-up moves are intentionally skipped. The proposed Retired Agent → configured retired-agent case mixes two ownership modes: once an ID is configured, its runtime-owned store path is canonical and deterministic; broad normalized-directory discovery remains available for unconfigured retired/manual owners. No public config/data contract or observed installation was identified for treating a noncanonical directory as an additional store for an actively configured owner. Preserving that speculative runtime compatibility would retain the reported hot-path scan or require a broader prewarm target-planning redesign outside this focused repair. This boundary follows the repository's canonical-runtime/no-unowned-fallback doctrine and the task's explicit configured-versus-retired/manual ownership split.

AI-assisted: yes. The implementation and evidence were reviewed; no agent transcript is included.

Configured agents now use their canonical direct store paths while retired and manual owners retain broad discovery. This prevents Gateway startup prewarm from rescanning every agent root once per configured agent.
@clawsweeper

clawsweeper Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@steipete
steipete marked this pull request as ready for review August 16, 2026 01:34
@openclaw-barnacle openclaw-barnacle Bot added size: XS maintainer Maintainer-authored PR labels Aug 16, 2026
@steipete steipete self-assigned this Aug 16, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 16, 2026
@clawsweeper

clawsweeper Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 15, 2026, 9:39 PM ET / August 16, 2026, 01:39 UTC.

ClawSweeper review

What this changes

The branch returns configured agents’ validated canonical session-store paths before broad directory discovery to avoid repeated scans during Gateway startup prewarm.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

The performance target is valid, but the early return drops an existing compatibility path for manually named session directories that normalize to a configured agent ID, so this PR is not ready to merge.

Priority: P1
Reviewed head: cd7a9d2dfe139e43a142a9e3df8d6b23ba917fec

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch has a well-scoped performance diagnosis but needs a compatibility-preserving implementation before it is merge-ready.
Proof confidence 🌊 off-meta tidepool Not applicable: The repository state identifies this as a maintainer-authored PR, so the external-contributor real-behavior-proof gate does not apply; the PR body nevertheless records live pre-fix measurements and focused post-fix checks.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The repository state identifies this as a maintainer-authored PR, so the external-contributor real-behavior-proof gate does not apply; the PR body nevertheless records live pre-fix measurements and focused post-fix checks.
Evidence reviewed 6 items Current resolver preserves normalized discovered directories: Current main scans configured and default agent roots, then keeps a discovered target when its normalized directory name matches the requested agent; this is the behavior the new early return bypasses.
Manual-directory behavior is intentional: The discovered-target helper explicitly retains the on-disk path when a directory name does not round-trip through normalization, supporting retired or manual stores.
Patch removes discovery for every configured ID: The added guard returns immediately for any configured agent, including one whose only existing store is under a manually named directory that normalizes to that configured ID.
Findings 1 actionable finding [P1] Preserve noncanonical stores for configured agent IDs
Security None None.

How this fits together

Gateway startup prewarms each configured agent’s session data for dashboard and protocol access. The session-target resolver supplies canonical configured paths plus discovered legacy or manually created stores to the combined Gateway store.

flowchart LR
  A[Configured agents] --> B[Session target resolver]
  C[Manual or legacy agent directories] --> B
  B --> D{Target ownership}
  D --> E[Canonical direct paths]
  D --> F[Validated directory discovery]
  E --> G[Combined Gateway store]
  F --> G
  G --> H[Startup prewarm and session views]
Loading

Before merge

  • Preserve noncanonical stores for configured agent IDs (P1) - This return bypasses the existing scan that intentionally accepts validated directories whose names normalize to the requested ID. A configured retired-agent with an existing Retired Agent store now gets no target when its canonical directory is absent, hiding its sessions from requested-agent Gateway views. Preserve that discovery behavior while eliminating repeated scans, and cover this configured-plus-noncanonical case.
  • Resolve merge risk (P1) - Merging the early return can omit persisted sessions stored under a manually named or legacy directory that normalizes to a now-configured agent ID, changing Gateway session visibility for existing installations.
  • Complete next step (P2) - The session-state regression is source-proven, but preserving complete legacy discovery while removing repeated scans needs an owner-level resolver/prewarm redesign on this maintainer-owned PR.

Findings

  • [P1] Preserve noncanonical stores for configured agent IDs — src/config/sessions/targets.ts:580-582
Agent review details

Security

None.

PR surface

Source +6, Tests +9. Total +15 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 6 0 +6
Tests 1 18 9 +9
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 24 9 +15

Review metrics

Metric Value Why it matters
Production versus test LOC production +6, tests +9 net The small production addition changes session-target selection, so its performance benefit must retain existing store-discovery compatibility.

Stored data model

Persistent data-model change detected: serialized state: src/config/sessions/targets.test.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Preserve normalized manual-store discovery (recommended)
    Refactor the resolver or prewarm flow so configured IDs retain validated noncanonical stores that normalize to them while filesystem scans are not repeated per agent.

Technical review

Best possible solution:

Have Gateway prewarm project configured agents from one complete validated target map, preserving normalized legacy/manual stores without rescanning every root for every configured agent.

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

Yes, from source: configure retired-agent while placing its only store under a valid Retired Agent directory; current main normalizes and finds it, whereas the new configured-agent return yields no discovered target.

Is this the best way to solve the issue?

No. The early return removes the repeated scan but also removes intentional normalized-directory compatibility; the optimization should preserve the complete target set and avoid repetition at the Gateway prewarm boundary.

Full review comments:

  • [P1] Preserve noncanonical stores for configured agent IDs — src/config/sessions/targets.ts:580-582
    This return bypasses the existing scan that intentionally accepts validated directories whose names normalize to the requested ID. A configured retired-agent with an existing Retired Agent store now gets no target when its canonical directory is absent, hiding its sessions from requested-agent Gateway views. Preserve that discovery behavior while eliminating repeated scans, and cover this configured-plus-noncanonical case.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P1: The patch can cause Gateway session views to omit existing agent state on affected multi-agent installations.
  • add merge-risk: 🚨 session-state: The changed target-selection path can hide previously discoverable persisted session stores for configured agents.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: The repository state identifies this as a maintainer-authored PR, so the external-contributor real-behavior-proof gate does not apply; the PR body nevertheless records live pre-fix measurements and focused post-fix checks.

Label justifications:

  • P1: The patch can cause Gateway session views to omit existing agent state on affected multi-agent installations.
  • merge-risk: 🚨 session-state: The changed target-selection path can hide previously discoverable persisted session stores for configured agents.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: The repository state identifies this as a maintainer-authored PR, so the external-contributor real-behavior-proof gate does not apply; the PR body nevertheless records live pre-fix measurements and focused post-fix checks.

Evidence

What I checked:

  • Current resolver preserves normalized discovered directories: Current main scans configured and default agent roots, then keeps a discovered target when its normalized directory name matches the requested agent; this is the behavior the new early return bypasses. (src/config/sessions/targets.ts:578, 1fda8835300f)
  • Manual-directory behavior is intentional: The discovered-target helper explicitly retains the on-disk path when a directory name does not round-trip through normalization, supporting retired or manual stores. (src/config/sessions/targets.ts:270, 1fda8835300f)
  • Patch removes discovery for every configured ID: The added guard returns immediately for any configured agent, including one whose only existing store is under a manually named directory that normalizes to that configured ID. (src/config/sessions/targets.ts:580, cd7a9d2dfe13)
  • Gateway prewarm reaches the changed resolver: Requested-agent Gateway store resolution calls this function, and startup prewarm invokes the requested-agent path once per configured agent. (src/config/sessions/combined-store-gateway.ts:231, cd7a9d2dfe13)
  • Regression coverage omits the compatibility combination: The new test proves that a configured canonical path does not enumerate directories, while the retained discovered-directory test covers only an unconfigured agent; neither covers a configured ID with a noncanonical on-disk directory that normalizes to it. (src/config/sessions/targets.test.ts:614, cd7a9d2dfe13)
  • Feature provenance: The current resolver behavior appears to have been introduced with the session-target extraction, and blame attributes the scanned fallback section to that commit. (src/config/sessions/targets.ts:527, eeabc2cf69a0)

Likely related people:

  • steipete: Current-main blame attributes the resolver’s direct and discovery paths to this author, who also has the largest observed history share across the resolver, combined Gateway store, and prewarm files. (role: introduced current resolver behavior and recent area contributor; confidence: high; commits: eeabc2cf69a0; files: src/config/sessions/targets.ts, src/config/sessions/combined-store-gateway.ts, src/gateway/server-startup-handler-prewarm.ts)

Rank-up moves

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

  • Retain normalized manual and legacy directory discovery for configured agent IDs.
  • Add a regression covering a configured ID whose on-disk directory normalizes to that ID but is not canonical.

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

Copy link
Copy Markdown
Contributor Author

Land-ready verification for exact head cd7a9d2dfe139e43a142a9e3df8d6b23ba917fec:

  • Pre-fix owner regression: src/config/sessions/targets.test.ts failed 1/40 because configured resolution enumerated both the configured and default agent roots.
  • Post-fix owner proof: node scripts/run-vitest.mjs src/config/sessions/targets.test.ts — 40/40 passed.
  • Gateway siblings: node scripts/run-vitest.mjs src/gateway/server-startup-handler-prewarm.test.ts src/gateway/server.sessions.list-store-materialization.test.ts — 12/12 passed.
  • Targeted type-aware Oxlint, Oxfmt, and git diff --check passed.
  • core, coreTests changed gate passed all guards, production/test typechecks, lint, and architecture checks. The installed Crabbox binary failed its version/help sanity check before remote execution, so repository policy's trusted-source local fallback ran the identical gate.
  • Fresh autoreview on the final rebased head: clean, no accepted/actionable findings.
  • Exact-head CI: https://github.com/openclaw/openclaw/actions/runs/31919883652 — success.
  • Native review artifacts: validated READY FOR /prepare-pr, zero findings, issueValidation=valid.
  • OPENCLAW_TESTBOX=1 scripts/pr prepare-run 124334: passed at 2026-08-16T01:44:28Z in hosted_exact_or_recent_parent mode, reusing the exact-head hosted CI result; no separate Testbox lease/run was needed. The remote PR tree matches the prepared head.
  • ClawSweeper's P1 and both rank-up moves have an explicit justified skip in the PR body; no re-review is required because the reviewed head is unchanged and the review is current.
  • Production LOC: +6/−0. Tests: +18/−9.

Known proof gap: this publication lane did not rerun the full Molty process after the fix; the live CPU/RSS/strace evidence is pre-fix, while the owner regression, Gateway siblings, changed gate, autoreview, and exact-head CI are post-fix.

@steipete
steipete merged commit d58e378 into main Aug 16, 2026
260 checks passed
@steipete
steipete deleted the steipete/fix-gateway-configured-session-discovery-hot-loop branch August 16, 2026 01:45
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 16, 2026
Configured agents now use their canonical direct store paths while retired and manual owners retain broad discovery. This prevents Gateway startup prewarm from rescanning every agent root once per configured agent.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XS status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant