Skip to content

perf(gateway): fix event-loop convoys from per-session hot paths under concurrent sessions - #129135

Merged
steipete merged 4 commits into
mainfrom
steipete/openclaw-performance-debug-6f241a
Aug 25, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/openclaw-performance-debug-6f241a

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

On busy gateways (observed live on the team host, 20+ concurrent Control UI sessions and several active codex runs), the whole gateway degrades: WS methods that normally answer in milliseconds take 8–20s in bursts, and there are ~11s windows where every in-flight method completes at the same instant — a whole-event-loop stall. Live log analysis (43MB gateway log, one day) plus code tracing found four independent per-session hot paths that either block the event loop with synchronous full-transcript work or serially spawn subprocess/network batteries per watched session:

  1. sessions.files.list (536 calls/day, 32% >2s): cold touched-files folds re-parse entire 30–80MB transcripts synchronously; the process-wide LRU held only 16 entries, so >16 viewed sessions thrash it and concurrent cold folds convoy (each request observes the sum of all concurrent folds' CPU). Every call also spawned git rev-parse --show-toplevel just to compute a boolean, and re-opened/realpathed the fs-safe workspace root per touched file.
  2. controlUi.sessionPullRequests.subscribe (2,527 calls/day, p50 1.9s, max 45s): the RPC awaited serial cold loads (~10–18 git spawns + 1–3 serial GitHub fetches with 8s timeouts, per session key, up to 200 keys). Worse, the cache TTLs were inverted: local-git caches lasted 10s against a 60s poll, and the GitHub success cache expired at exactly the poll interval (stamped at load start) — so every poll re-ran the full battery for every watched session, every minute.
  3. Skill loading: full synchronous rescans of every skill root (~94 SKILL.md files on the affected host, readFileSync + frontmatter parse each) ran 4–6× per inbound message on the event loop; the snapshot cache was written but never read for fresh sessions. Symptom: 8,964 "Skill precedence collision resolved" warnings per day for a static configuration fact.
  4. sessions.preview / chat.message.get: preview batches (≤64 keys) synchronously loaded every message event per session to keep the last 12 items, with no yields between keys; message-get loaded the full projected transcript to check one messageId. Together with the folds above this drove repeated memory pressure: level=critical reason=rss_growth events (heap oscillating 0.75→3.1+ GiB).

Why This Change Was Made

The shared invariant violation: request paths answered small questions by synchronously materializing entire transcripts or re-running full discovery batteries, instead of bounded reads and caches sized/invalidated correctly. Fixes stay at the owning boundaries:

  • sessions-files: touched-files cache 16→256 (entries are a cursor + small Map; 256 covers realistic concurrent viewed sessions so warm calls do cursor-delta reads); in-process insideGitCheckout replaces the per-call git spawn; one prepared fs-safe workspace root per request instead of per-file realpath round trips.
  • PR subscriptions: the subscribe RPC now registers the replace-set, pushes cached snapshots, kicks cold loads in the background (replacement-token ordering preserved) and responds immediately; hydration and polling process at most 4 keys concurrently; local-git caches 10s→75s and GitHub success cache 60s→90s so the 60s poll hits warm caches; failure/rate-limit semantics unchanged.
  • skills: loadSkillEntries is memoized (bounded 64-entry cache) keyed on the existing chokidar snapshot-version seam plus config fingerprint/roots; the session snapshot cache now serves fresh sessions read-through; collision warnings fire once per snapshot version.
  • preview/message-get: preview reads a bounded recent tail (64–256 events / 1MiB, one escalation to 2,048 events / 8MiB if filtered messages starve the 12-item preview) and yields between batch keys; message-get uses the existing message-ID-anchored reader (message + predecessor) preserving active-branch filtering, archive fallback, and hidden announce/reply semantics.

User Impact

Control UI stays responsive with many sessions active: sidebar/file-panel/PR-indicator refreshes no longer convoy behind full transcript re-parses or per-session git/GitHub batteries, subscribe RPCs return immediately, and the gateway's background load drops from ~N×15 git spawns + N×2–9 GitHub calls per minute to near-zero for unchanged repos. Heap churn from preview/message-get paths shrinks accordingly. No config surface, schema, or protocol changes; no behavior changes beyond latency/logging (collision warning now deduped per snapshot version).

Evidence

Live diagnosis on team.openclaw.ai (gateway 2026.8.1): per-method latency distribution extracted from the gateway JSONL log — sessions.files.list 536 calls/172 >2s; controlUi.sessionPullRequests.subscribe 2,527 calls, p50 1,873ms; a synchronized ~11.18s completion cluster across 8 unrelated methods at 00:39:12 (event-loop stall); 26 critical rss_growth memory-pressure events; 8,964 skill-collision warnings. Subprocess sampling over 30s showed the PR poller's git diff --shortstat battery cycling across all watched worktrees.

Local verification: targeted Vitest for all touched surfaces green — gateway shard (7 files, 117 tests), skills + workshop suites (57 files, 815 tests incl. new regressions), preview/chat shard. New regression coverage: cursor retention across 24 viewed sessions; subscribe responds without awaiting cold loads; no re-scan within a snapshot version and rescan after version bump; collision warning once per version; 1,024-message transcript preview reads only 64 events; hidden announce messages remain inaccessible via message-get. pnpm check:changed green (assertion-safety baseline shrink included). Production LOC delta: +184/−93 (bounded-parallelism helper, memoization, and bounded-read logic); tests +323/−15.

…folds

Raise the touched-files fold cache from 16 to 256 entries so >16 viewed
sessions no longer thrash it into repeated full-transcript refolds, use
in-process insideGitCheckout instead of spawning git rev-parse per call,
and reuse one prepared fs-safe workspace root per request instead of
re-opening it per touched file.
…ligned caches

controlUi.sessionPullRequests.subscribe now registers the replace-set,
pushes cached snapshots, hydrates cold keys in the background (bounded
concurrency 4) and responds immediately instead of awaiting serial git
and GitHub batteries per session key. Local-git caches grow 10s->75s and
the GitHub success cache 60s->90s so the 60s poll hits warm caches
instead of re-running the full battery for every watched session every
minute; failure and rate-limit semantics are unchanged.
…ot seam

loadSkillEntries now serves repeat loads from a bounded 64-entry cache
keyed on the chokidar snapshot version plus config fingerprint, instead
of synchronously rescanning every skill root 4-6x per inbound message.
The session snapshot cache serves fresh sessions read-through, and the
skill precedence collision warning fires once per snapshot version
instead of ~9k times/day.
… reads

sessions.preview reads a bounded recent tail (64-256 events/1MiB, one
8MiB escalation when filtered messages starve the 12-item preview) and
yields between batch keys instead of synchronously materializing every
transcript in a 64-key loop. chat.message.get resolves visibility via
the message-ID-anchored reader instead of loading the full projected
transcript per request.
@clawsweeper

clawsweeper Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added r: skill Auto-close: skills should be published on ClawHub, not added to core. gateway Gateway runtime size: L maintainer Maintainer-authored PR labels Aug 25, 2026
@steipete
steipete marked this pull request as ready for review August 25, 2026 08:00
@clawsweeper clawsweeper Bot added merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P2 Normal backlog priority with limited blast radius. 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. labels Aug 25, 2026
@clawsweeper

clawsweeper Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 25, 2026, 4:06 AM ET / 08:06 UTC.

ClawSweeper review

What this changes

This PR bounds session transcript reads, caches skill discovery and workspace facts, and moves Control UI pull-request hydration into limited-concurrency background work to avoid Gateway event-loop convoys.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

Keep open for maintainer review. The source-level design follows the owning Gateway and skills boundaries, but the cache TTLs deliberately reduce normal PR-status freshness and the review environment could not retrieve current main or the latest review comment.

Priority: P2
Reviewed head: 3600db95ab3e81859b7b528821bec20f2ef37d95
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch has focused source-level tests and coherent owner boundaries, but exact current-main/merge-head comparison and the cache-freshness decision remain unresolved.
Proof confidence 🌊 off-meta tidepool Not applicable: Not applicable: the target metadata identifies a maintainer-associated PR; the body nevertheless records live host diagnosis and targeted local verification.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Not applicable: the target metadata identifies a maintainer-associated PR; the body nevertheless records live host diagnosis and targeted local verification.
Evidence reviewed 6 items Immediate subscription acknowledgment: The subscription handler starts replacement hydration without awaiting it, then acknowledges the RPC; the subscription owner retains replacement tokens before publishing later snapshots.
Bounded transcript preview path: Preview construction reads a 64–256-event, 1 MiB tail with one bounded 2,048-event/8 MiB recovery read rather than materializing the full transcript.
Regression coverage: Focused tests exercise four-at-a-time subscription hydration, bounded preview reads, sparse-tail recovery, and hidden pre-session announce/reply behavior.
Findings None None.
Security None None.

Live Verification

Command: pnpm test src/gateway/control-ui-session-pr-subscriptions.test.ts src/gateway/server.sessions.preview-resolve.test.ts src/gateway/server.chat.gateway-server-chat-b.test.ts

Result: FAIL (partial) — step 2 expect_output Test Files: expected terminal output was not visible within 30 seconds: "Test Files"

pnpm test src/gateway/control-ui-session-pr-subscriptions.test.ts src/gateway/server.sessions.preview-resolve.test.ts src/gateway/server.chat.gateway-server-cha
t-b.test.ts
runner@runnervm76f27:/tmp/clawsweeper-live-proof-129135-5ApImp/target$ pnpm test src/gateway/control-ui-session-pr-subscriptions.test.ts src/gateway/server.sess
ions.preview-resolve.test.ts src/gateway/server.chat.gateway-server-chat-b.test.ts
$ node --import tsx scripts/test-projects.mts src/gateway/control-ui-session-pr-subscriptions.test.ts src/gateway/server.sessions.preview-resolve.test.ts src/ga
teway/server.chat.gateway-server-chat-b.test.ts
pnpm test src/gateway/control-ui-session-pr-subscriptions.test.ts src/gateway/server.sessions.preview-resolve.test.ts src/gateway/server.chat.gateway-server-cha
t-b.test.ts
[test] starting test/vitest/vitest.gateway.config.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-129135-5ApImp/target

 ✓  gateway-core  ../../src/gateway/control-ui-session-pr-subscriptions.test.ts (13 tests) 504ms






































Assertions:

  • FAIL expect_output: Test Files

How this fits together

Gateway RPC handlers serve Control UI session data and chat messages from SQLite transcript state, workspace files, Git, GitHub, and skill discovery. The changed paths turn those inputs into session previews, file lists, PR indicators, and model skill snapshots.

flowchart LR
  UI[Control UI and chat clients] --> RPC[Gateway RPC handlers]
  RPC --> Sessions[Session transcript reads]
  RPC --> Workspace[Workspace and Git facts]
  RPC --> PRs[GitHub pull-request snapshots]
  RPC --> Skills[Workspace skill discovery]
  Sessions --> Output[Session and chat responses]
  Workspace --> Output
  PRs --> Output
  Skills --> Output
Loading

Decision needed

Question Recommendation
Should normal Control UI pull-request indicators intentionally trade per-minute freshness for the new 75/90-second cache window? Confirm the freshness budget: Accept the 75-second local-Git and 90-second GitHub TTLs, with forced structural refreshes remaining the immediate-update path.

Why: The patch changes observable status-refresh cadence while describing the result as latency/logging-only; the appropriate freshness budget is a maintainer product and operator-experience choice.

Before merge

  • Resolve merge risk (P1) - Normal 60-second polling now commonly refreshes pull-request and local Git facts on the next cycle because the new 75/90-second TTLs outlive one poll; existing Control UI indicators can therefore remain stale for roughly two minutes without an explicit refresh.
  • Resolve merge risk (P1) - Current-main and merge-head behavior could not be compared in this checkout because its missing Git objects attempted an unavailable promisor fetch.
  • Complete next step (P2) - The maintainer label and deliberate indicator-freshness tradeoff require human confirmation; no narrow mechanical repair is established.
Agent review details

Security

None.

PR surface

Source +92, Tests +308, Other -1. Total +399 across 23 files.

View PR surface stats
Area Files Added Removed Net
Source 11 183 91 +92
Tests 11 323 15 +308
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 2 -1
Total 23 507 108 +399

Review metrics

Metric Value Why it matters
Production versus test LOC production +91 net (+184/-93); tests +308 net (+323/-15) The positive production growth implements bounded concurrency, caching, and transcript-read limits, so its freshness and invalidation tradeoffs need explicit review.

Stored data model

Persistent data-model change detected: persistent cache schema: src/skills/runtime/session-snapshot.ts, serialized state: src/gateway/server-methods/sessions-files.touched-files.test.ts, serialized state: src/gateway/server-methods/sessions-files.ts, serialized state: src/gateway/server-methods/sessions-read.ts, serialized state: src/gateway/session-transcript-readers.ts, serialized state: src/skills/runtime/session-snapshot.test.ts, and 3 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Confirm intentional indicator staleness (recommended)
    Accept that unchanged normal subscriptions refresh on the later poll cycle in exchange for substantially lower Git and GitHub load.
  2. Keep the former freshness cadence
    Revise cache expiry or scheduling and add a polling-cadence regression test before merge.

Technical review

Best possible solution:

Retain the bounded owner-path changes, explicitly accept or adjust the normal PR-status freshness budget, then validate the resolved merge head against current main.

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

Do we have a high-confidence way to reproduce the issue? No independent live reproduction was possible here; source and the PR’s reported production measurements identify the hot paths, but the checkout could not run them or read current main.

Is this the best way to solve the issue?

Is this the best way to solve the issue? Unclear: the bounded reads and owner-local caches are coherent, but maintainers must first confirm that the resulting normal PR-status freshness delay is acceptable.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: The PR addresses responsiveness degradation for concurrent Gateway session activity without evidence of an emergency outage.
  • add merge-risk: 🚨 other: The new cache windows intentionally change the normal freshness cadence of Control UI pull-request indicators.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Not applicable: the target metadata identifies a maintainer-associated PR; the body nevertheless records live host diagnosis and targeted local verification.

Label justifications:

  • P2: The PR addresses responsiveness degradation for concurrent Gateway session activity without evidence of an emergency outage.
  • merge-risk: 🚨 other: The new cache windows intentionally change the normal freshness cadence of Control UI pull-request indicators.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Not applicable: the target metadata identifies a maintainer-associated PR; the body nevertheless records live host diagnosis and targeted local verification.

Evidence

What I checked:

  • Immediate subscription acknowledgment: The subscription handler starts replacement hydration without awaiting it, then acknowledges the RPC; the subscription owner retains replacement tokens before publishing later snapshots. (src/gateway/server-methods/control-ui.ts:191, 3600db95ab3e)
  • Bounded transcript preview path: Preview construction reads a 64–256-event, 1 MiB tail with one bounded 2,048-event/8 MiB recovery read rather than materializing the full transcript. (src/gateway/session-transcript-readers.ts:250, 3600db95ab3e)
  • Regression coverage: Focused tests exercise four-at-a-time subscription hydration, bounded preview reads, sparse-tail recovery, and hidden pre-session announce/reply behavior. (src/gateway/server.sessions.preview-resolve.test.ts:135, 3600db95ab3e)
  • Freshness tradeoff: The fixed 60-second poll now reuses 75-second local-Git and 90-second GitHub caches, so an ordinary poll at 60 seconds remains warm and a normal refresh can occur on the following cycle. (src/gateway/control-ui-session-prs.ts:38, 3600db95ab3e)
  • Feature history: The subscription and local-Git cache behavior appears to date to the same area owner’s prior Gateway work, including the original subscription feature and cache introduction. (src/gateway/control-ui-session-pr-subscriptions.ts:230, 662abec75412)
  • Current-main inspection gap: This checkout is a grafted PR head; attempting to resolve the supplied current-main SHA required a promisor fetch that failed because the environment could not resolve github.com. The current-main comparison and latest omitted ClawSweeper comment could therefore not be independently read.

Likely related people:

  • steipete: History attributes the original PR-subscription feature, local Git cache, current performance patch, and most touched Gateway/skills history to Peter Steinberger. (role: feature owner and recent area contributor; confidence: high; commits: 662abec75412, 885121b1f325, 3600db95ab3e; files: src/gateway/control-ui-session-pr-subscriptions.ts, src/gateway/control-ui-session-prs.ts, src/skills/loading/workspace-skill-loader.ts)
  • Ayaan Zaidi: Introduced the execution-directory skill merge behavior that the new versioned skill-discovery cache now serves. (role: adjacent skills-boundary contributor; confidence: medium; commits: a884d19bad90; files: src/skills/loading/workspace-skill-loader.ts)
  • wanyongstar: Recent history shows work on session PR snapshot correctness beyond the display cap. (role: adjacent pull-request snapshot contributor; confidence: medium; commits: 7439cd3faec9; files: src/gateway/control-ui-session-prs.ts)

Rank-up moves

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

  • Confirm the intended 75/90-second normal status-freshness window.
  • Recheck the resolved merge head against current main and its completed exact-head CI.
  • Attach a redacted before/after Gateway latency trace if maintainer review needs confirmation of the production payoff.

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

Maintainer decision on the ClawSweeper items, landing under explicit maintainer authority:

Freshness budget: accepted. The 75s local-git / 90s GitHub success TTLs intentionally trade up to ~2 minutes of background PR-indicator staleness for eliminating the per-minute full git+GitHub battery per watched session (previously ~15 git spawns + 2–9 API calls per session per minute, serialized on a busy gateway). Structural refreshes (refreshSessionKeys) still bypass the cache and update immediately, so user-initiated refresh latency is unchanged. This is the intended product tradeoff for this fix.

Current-main comparison: the review runner's checkout lacked git objects (promisor fetch unavailable) — locally this branch is rebased on origin/main (ebf07e5) with exact-head CI green (81/81 checks on 3600db9).

Live verification timeout: the runner's expect_output timed out waiting 30s for terminal output; the log shows the suites running and the first file passing (13 tests, 504ms). The same suites pass locally in full.

@steipete
steipete merged commit a3d173d into main Aug 25, 2026
312 checks passed
@steipete
steipete deleted the steipete/openclaw-performance-debug-6f241a branch August 25, 2026 08:38
@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 26, 2026
…r concurrent sessions (openclaw#129135)

* perf(gateway): stop sessions.files.list convoying on cold transcript folds

Raise the touched-files fold cache from 16 to 256 entries so >16 viewed
sessions no longer thrash it into repeated full-transcript refolds, use
in-process insideGitCheckout instead of spawning git rev-parse per call,
and reuse one prepared fs-safe workspace root per request instead of
re-opening it per touched file.

* perf(gateway): make session PR subscriptions non-blocking with poll-aligned caches

controlUi.sessionPullRequests.subscribe now registers the replace-set,
pushes cached snapshots, hydrates cold keys in the background (bounded
concurrency 4) and responds immediately instead of awaiting serial git
and GitHub batteries per session key. Local-git caches grow 10s->75s and
the GitHub success cache 60s->90s so the 60s poll hits warm caches
instead of re-running the full battery for every watched session every
minute; failure and rate-limit semantics are unchanged.

* perf(skills): memoize workspace skill discovery on the watcher snapshot seam

loadSkillEntries now serves repeat loads from a bounded 64-entry cache
keyed on the chokidar snapshot version plus config fingerprint, instead
of synchronously rescanning every skill root 4-6x per inbound message.
The session snapshot cache serves fresh sessions read-through, and the
skill precedence collision warning fires once per snapshot version
instead of ~9k times/day.

* perf(gateway): bound sessions.preview and chat.message.get transcript reads

sessions.preview reads a bounded recent tail (64-256 events/1MiB, one
8MiB escalation when filtered messages starve the 12-item preview) and
yields between batch keys instead of synchronously materializing every
transcript in a 64-key loop. chat.message.get resolves visibility via
the message-ID-anchored reader instead of loading the full projected
transcript per request.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P2 Normal backlog priority with limited blast radius. r: skill Auto-close: skills should be published on ClawHub, not added to core. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L 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.

1 participant