Skip to content

perf: Claude Code catalog refresh no longer re-scans the projects tree on every poll - #136222

Merged
steipete merged 2 commits into
mainfrom
steipete/silly-neumann-962688
Sep 2, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/silly-neumann-962688

Conversation

@steipete

@steipete steipete commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where operators with large Claude Code histories would see the sessions sidebar's catalog refresh stall for seconds when the Gateway host's disk was busy. On a production Gateway the sessions.catalog.list RPC exceeded 1s in 518 requests over one day with a 60s maximum, far more than any other method, while the Control UI polls it every 30s (5s while anything changes) and again on every reconnect and tab focus.

Why This Change Was Made

The Claude Code catalog provider re-read the whole ~/.claude/projects tree on every poll to decide whether its cache was still valid (a readdir per project directory and a stat of every direct child), and any active Claude session changed that whole-tree stamp, so every poll also reran the assembled scan with a realpath and stat per transcript plus a stat per Claude Desktop metadata file. The provider now owns freshness with a directory watch (recursive on macOS/Windows, root plus per-project-directory on Linux) and keeps an incrementally maintained snapshot whose lstat signatures replace the per-candidate filesystem work; CLI records and the Desktop overlay are cached independently so one does not invalidate the other. A watch vouches for coverage only after a short arming interval because libuv starts the macOS FSEvents stream asynchronously; watcher failure degrades to today's per-poll full read. Gateway enumeration retains its caller partition because external plugin node policies can observe connection identity; the plugin filesystem snapshot is still reusable across those enumerations. Desktop metadata retains its 60-second backstop because custom groups live outside the watched session directory. Non-goals: the separate sessions.github.options latency (two uncached GitHub identity probes per call) is tracked as a follow-up.

User Impact

The Claude Code group in the sessions sidebar refreshes without touching the disk when nothing changed, and a change re-reads only the affected project directory. Dashboards that reconnect reuse the plugin filesystem snapshot without merging caller-bound provider work. Sessions created or renamed outside OpenClaw still appear on the next refresh; the whole tree is re-read at most every five minutes as a backstop.

Evidence

Warm listClaudeSessions on a 1.2k-project tree (unsaturated NVMe; production wall time is disk-bound):

stats readdirs realpaths opens ms
before 7,180 1,229 1,517 1 170–2,400
after (unchanged tree) 0 0 0 0 0–1

Regression tests that fail on pre-fix code: extensions/anthropic/session-catalog.test.ts ("serves an unchanged assembled scan without reparsing transcript files" now asserts zero home I/O; "re-stats only the changed project directory on the next poll"; "keeps the CLI records when only the Desktop store changes"). New session-catalog-tree-watch.test.ts covers dirty reporting, Linux child-watch lifecycle, and creation-failure fallback.

Local proof:

node scripts/run-vitest.mjs extensions/anthropic            # 25 files, 429 tests passed
node scripts/run-vitest.mjs src/gateway/server-methods/session-catalog.test.ts   # 27 passed
node scripts/check-changed.mjs                              # all lanes ok

Codex autoreview (two passes on the final diff): scoped-clean, no accepted findings.

Production LOC: +694/-385 (net +309); tests: +476/-75 (net +401); docs: +10. The production growth adds bounded watcher/snapshot lifecycle ownership and separates Desktop invalidation from CLI records; the moved Desktop parsing code is not new capability. A net-neutral TTL-only change would retain whole-tree disk reads or delay freshness for all CLI records.

Original-head live real-flow proof on an isolated dev gateway (OPENCLAW_STATE_DIR under a temp dir, CLAUDE_CONFIG_DIR pointing at the real ~/.claude, port 18901, OPENCLAW_SKIP_CHANNELS=1), calling openclaw gateway call sessions.catalog.list --params '{"limitPerHost":40}' from fresh CLI connections; the gateway's own RPC timing lines:

[ws] ⇄ res ✓ sessions.catalog.list 1060ms   # first poll: watch attaches, full tree read
[ws] ⇄ res ✓ sessions.catalog.list 69ms     # next poll from a new connection on the original head

The Claude Code group listed the local CLI sessions on every call (Desktop rows are excluded under HOME isolation, as before).

CI and review corrections

The first exact-head CI run (33615118618, head e3bd513) exposed a caller-isolation regression. The generic gateway cache-key optimization is removed: external plugin node policies may observe connection identity, and the existing shipped privacy contract is retained. The unchanged privacy regression failed locally before this correction; both gateway catalog suites then passed (41 tests).

ClawSweeper's rank-up move is accepted: Desktop metadata retains the 60-second refresh because Local Storage groups are outside the session-directory watcher. The existing group test now verifies an ordinary poll after an independent group update, and failed before the correction. CLI records remain independently cached.

No persistent store or schema change: the group map is a bounded process-local cache; the existing external LevelDB format is only read. No changelog or new config option.

Corrected-candidate local proof: gateway catalog + unchanged privacy suites passed 41/41 tests; Anthropic catalog + tree-watch suites passed 74/74 tests. The initial Linux failure in keeps the CLI records when only the Desktop store changes was the same overextended Desktop TTL and is addressed by restoring the 60-second bound.

Corrections are committed in 6da97ea. Fresh autoreview of the complete corrected candidate: scoped-clean at P0. Local node scripts/check-changed.mjs passed ratchets, formatting, core and core-test typechecks, then stopped in untouched extensions/browser/src/browser/chrome-mcp-options.ts because this worktree lacks the already-declared @types/yargs-parser installation. No dependency or lockfile workaround was applied; exact-head hosted CI is the remaining gate. The original security-fast failure happened during Git history fetch (exit 128, no credentials available to that fetch), before scanning.

Related: #127743 tracks the separate stale-while-revalidate product decision for slow external catalogs after cache expiry; this PR reduces Claude provider scan cost and does not claim to close that issue.

…it per poll

`sessions.catalog.list` took >1s in hundreds of requests per day (max 60s)
on an IOPS-saturated Gateway host. The Claude provider re-read the whole
`~/.claude/projects` tree on every poll to compute a freshness stamp
(readdir + stat of every direct child), and any active Claude session
changed that stamp so every poll also reran the assembled scan with a
realpath + stat per candidate; the Desktop 60s TTL forced CLI rescans too.
Measured warm poll on a 1.2k-project tree: ~7.2k stats, 1.2k readdirs,
1.5k realpaths with zero file parsing.

The provider now owns freshness with a directory watch
(`session-catalog-tree-watch.ts`): one recursive fs.watch on macOS and
Windows, root plus per-project-directory watches on Linux (Node's Linux
recursive watch watches every file), nonpersistent, degrading to a full
read on watcher failure with a 5s reattach. A watch vouches for coverage
only once it has been attached for 250ms and polled, because libuv starts
the FSEvents stream asynchronously and drops writes in that window. The
projects tree snapshot is kept per root and re-stats only dirty
directories; its lstat signatures (mtime/size/ino) replace the
per-candidate realpath + stat during discovery; CLI records are keyed by
tree stamp; the Desktop overlay refreshes on its own watch or backstop
without invalidating CLI records; Desktop custom groups cache on the
LevelDB listing signature; merged results are memoized on identity.

Gateway side, the list cache key no longer carries a per-connection
caller id. node.list and node.invoke read only scopes, role, and device
id from the caller and the key already carried those plus the profile
visibility facts, so a reconnected dashboard (a new client object) now
shares the settled enumeration instead of queueing another provider scan
behind the admission cap.

Warm unchanged poll after: 0 stats, 0 readdirs, 0 realpaths, 0 opens.

Docs: docs/providers/anthropic.md describes the watched freshness model.
@steipete
steipete marked this pull request as ready for review September 2, 2026 09:37
@clawsweeper

clawsweeper Bot commented Sep 2, 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 docs Improvements or additions to documentation gateway Gateway runtime extensions: anthropic size: XL maintainer Maintainer-authored PR labels Sep 2, 2026
@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 2, 2026, 6:03 AM ET / 10:03 UTC.

ClawSweeper review

What this changes

The PR makes Anthropic’s Claude Code session catalog retain bounded watched filesystem snapshots so unchanged Gateway polls avoid rescanning local project and Desktop session data.

Merge readiness

✅ Ready for maintainer review

No introduced correctness defect was found on the corrected head. The earlier Desktop-refresh and caller-isolation concerns are addressed; this maintainer-authored, protected PR should remain open for normal exact-head CI and maintainer handling.

Priority: P2
Reviewed head: 6da97eada75d094c2ac4782b7b40e6a2245b4804

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The corrected patch has a coherent owner boundary and targeted regression coverage, with no remaining actionable correctness finding.
Proof confidence 🌊 off-meta tidepool Not applicable: The provided repository state identifies this as a MEMBER-authored PR, so the external-contributor proof gate does not apply. Its body nevertheless includes a real isolated-Gateway timing trace for the changed catalog path.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The provided repository state identifies this as a MEMBER-authored PR, so the external-contributor proof gate does not apply. Its body nevertheless includes a real isolated-Gateway timing trace for the changed catalog path.
Evidence reviewed 7 items Plugin cache owner: The watched snapshot is owned by the Anthropic plugin: it reuses a clean snapshot, rescans only dirty project directories, and retains a five-minute full-read backstop.
Caller isolation retained: Gateway list keys include a per-connection caller id and caller scope/role/device facts, while results are projected with current caller visibility at delivery time.
Introduction boundary: Host-verified PR introduction evidence lists ten Anthropic/docs/config paths and no Gateway handler path, so the final branch does not introduce a cross-caller Gateway cache change.
Findings None None.
Security None None.

How this fits together

The Anthropic plugin reads local Claude Code and Claude Desktop session metadata into the Gateway session catalog. Gateway handlers then apply each caller’s current visibility rules before returning rows to the Control UI or another catalog client.

flowchart LR
  A[Claude project files] --> B[Watched plugin snapshot]
  F[Desktop session metadata] --> C[Desktop overlay]
  B --> D[Combined session records]
  C --> D
  D --> E[Gateway caller visibility]
  E --> G[Catalog response]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +309, Tests +401, Docs +10, Other 0. Total +720 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 6 694 385 +309
Tests 2 476 75 +401
Docs 1 10 0 +10
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 10 1181 461 +720

Review metrics

Metric Value Why it matters
Production vs test delta production +694/-385; tests +476/-75; docs +10 The net production growth is tied to bounded watcher and snapshot lifecycle ownership; the test growth covers cache, Desktop-refresh, and watcher-failure behavior.

Stored data model

Persistent data-model change detected: serialized state: extensions/anthropic/claude-desktop-groups.ts, unknown-data-model-change: extensions/anthropic/claude-desktop-groups.ts. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best possible solution:

Keep filesystem freshness in the Anthropic plugin, preserve the 60-second Desktop overlay refresh for unwatched Local Storage groups, and retain Gateway’s per-caller response partition.

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

Not applicable as an issue reproduction. The PR supplies an observed Gateway cold-to-warm timing trace and focused source-visible cache regressions, though this read-only review did not execute them.

Is this the best way to solve the issue?

Yes. The snapshot belongs in the Anthropic plugin, while Gateway continues to derive the response from current caller facts; this avoids both repeated filesystem work and unsafe cross-caller sharing.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: This improves repeated session-catalog latency for operators with large local Claude histories without evidence of an availability, data-loss, or security incident.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The provided repository state identifies this as a MEMBER-authored PR, so the external-contributor proof gate does not apply. Its body nevertheless includes a real isolated-Gateway timing trace for the changed catalog path.

Label justifications:

  • P2: This improves repeated session-catalog latency for operators with large local Claude histories without evidence of an availability, data-loss, or security incident.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The provided repository state identifies this as a MEMBER-authored PR, so the external-contributor proof gate does not apply. Its body nevertheless includes a real isolated-Gateway timing trace for the changed catalog path.

Evidence

What I checked:

  • Plugin cache owner: The watched snapshot is owned by the Anthropic plugin: it reuses a clean snapshot, rescans only dirty project directories, and retains a five-minute full-read backstop. (extensions/anthropic/session-catalog-scan.ts:271, 6da97eada75d)
  • Caller isolation retained: Gateway list keys include a per-connection caller id and caller scope/role/device facts, while results are projected with current caller visibility at delivery time. (src/gateway/server-methods/session-catalog.ts:190, 6da97eada75d)
  • Introduction boundary: Host-verified PR introduction evidence lists ten Anthropic/docs/config paths and no Gateway handler path, so the final branch does not introduce a cross-caller Gateway cache change. (6da97eada75d)
  • Prior finding covered: The custom-group regression advances the 60-second Desktop refresh and verifies a normal poll sees the Local Storage group update; this is the earlier review’s required behavior. (extensions/anthropic/session-catalog.test.ts:1399, 6da97eada75d)
  • Cache behavior tests: Focused tests exercise zero-I/O unchanged scans, targeted dirty-directory refresh, and watcher fallback/lifecycle instead of relying only on timing claims. (extensions/anthropic/session-catalog.test.ts:1952, 6da97eada75d)
  • Current-main drift check: Current main descends from the pinned base, and the checked cache implementation paths have no later main-branch drift; the PR remains a distinct unmerged change. (fc8a452938a0)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-02T09:44:52.266Z sha e3bd513 :: needs changes before merge. :: [P2] Preserve the Desktop fallback for unwatched group storage

@steipete

steipete commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the rank-up move in 6da97ea: Desktop overlays retain the 60-second refresh, and the existing custom-group test now verifies a normal poll after changing Local Storage. That assertion failed before the correction and passes afterward. The Linux CI Desktop-refresh failure shares this invalidation gap.

CI also exposed the gateway caller-partition regression. The generic cross-connection cache change is removed, preserving the unchanged shipped privacy test and external plugin node-policy contract. The Anthropic watched snapshot remains reusable across enumerations. Gateway catalog/privacy tests: 41 passed; Anthropic catalog/watch tests: 74 passed. Fresh autoreview is scoped-clean at P0. No persistent schema or data format changed; the group cache is process-local only. The PR body now records the corrected scope and the local missing-dependency check limitation.

@clawsweeper re-review

This push changes behavior beyond the Desktop finding by restoring gateway caller isolation.

@clawsweeper

clawsweeper Bot commented Sep 2, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. labels Sep 2, 2026
@steipete
steipete merged commit 1e08882 into main Sep 2, 2026
358 of 362 checks passed
@steipete
steipete deleted the steipete/silly-neumann-962688 branch September 2, 2026 10:27
@steipete

steipete commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 3, 2026
…e on every poll (openclaw#136222)

* perf(catalog): watch the Claude projects tree instead of re-statting it per poll

`sessions.catalog.list` took >1s in hundreds of requests per day (max 60s)
on an IOPS-saturated Gateway host. The Claude provider re-read the whole
`~/.claude/projects` tree on every poll to compute a freshness stamp
(readdir + stat of every direct child), and any active Claude session
changed that stamp so every poll also reran the assembled scan with a
realpath + stat per candidate; the Desktop 60s TTL forced CLI rescans too.
Measured warm poll on a 1.2k-project tree: ~7.2k stats, 1.2k readdirs,
1.5k realpaths with zero file parsing.

The provider now owns freshness with a directory watch
(`session-catalog-tree-watch.ts`): one recursive fs.watch on macOS and
Windows, root plus per-project-directory watches on Linux (Node's Linux
recursive watch watches every file), nonpersistent, degrading to a full
read on watcher failure with a 5s reattach. A watch vouches for coverage
only once it has been attached for 250ms and polled, because libuv starts
the FSEvents stream asynchronously and drops writes in that window. The
projects tree snapshot is kept per root and re-stats only dirty
directories; its lstat signatures (mtime/size/ino) replace the
per-candidate realpath + stat during discovery; CLI records are keyed by
tree stamp; the Desktop overlay refreshes on its own watch or backstop
without invalidating CLI records; Desktop custom groups cache on the
LevelDB listing signature; merged results are memoized on identity.

Gateway side, the list cache key no longer carries a per-connection
caller id. node.list and node.invoke read only scopes, role, and device
id from the caller and the key already carried those plus the profile
visibility facts, so a reconnected dashboard (a new client object) now
shares the settled enumeration instead of queueing another provider scan
behind the admission cap.

Warm unchanged poll after: 0 stats, 0 readdirs, 0 realpaths, 0 opens.

Docs: docs/providers/anthropic.md describes the watched freshness model.

* fix(catalog): preserve caller isolation and Desktop refresh bounds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation extensions: anthropic gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL 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