Skip to content

perf(anthropic): cache Claude session-catalog transcript metadata by mtime - #109309

Merged
steipete merged 1 commit into
mainfrom
perf/anthropic-catalog-mtime-cache
Jul 16, 2026
Merged

steipete merged 1 commit into
mainfrom
perf/anthropic-catalog-mtime-cache

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

sessions.catalog.list stalls the gateway event loop (observed ~9s per call on a large catalog, tens-of-seconds event-loop delay). Root cause: the Claude provider's transcript discovery (extensions/anthropic/session-catalog.ts discoverCliRecords) re-scans every ~/.claude/projects/*/*.jsonl file on every call — opening each, reading up to a 1 MiB prefix, and running a synchronous JSON.parse per line to derive the session's title / first prompt / cwd / gitBranch. There was no caching, so unchanged, long-ended transcripts were re-opened and re-parsed on each call. The Control UI polls this every 30s per browser tab, so the cost compounds and monopolizes the main thread (it's a plausible trigger for the client-side "terminal liveness timeout" reconnect seen under load).

Why This Change Was Made

A .jsonl transcript's derived catalog metadata is a pure function of its content prefix, and Claude CLI transcripts are append-only while active then static. So an unchanged file (same mtimeMs + size) yields identical metadata and never needs re-reading.

This adds a module-level per-file cache keyed by resolved path, validated on (mtimeMs, size):

  • Hit (mtime+size match): restore the cached CatalogRecord/sidechain flag and skip the open/read/parse entirely; cache hits read no bytes so they don't consume the scan byte budget.
  • Miss (changed/new file): scan as before, then cache the outcome — including negative/sidechain-only results so those aren't re-parsed either.
  • Correctness guard: a file whose read was cut short by the 64 MiB scan-byte budget is not cached (its derived record could be incomplete).
  • Eviction: after a complete scan (not one truncated by the file-count/byte budget), entries for files no longer present are dropped; a 20,000-entry cap bounds growth. Zero staleness — any content change flips mtime/size and re-scans.

User Impact

Session catalog loads are dramatically cheaper after the first scan: unchanged transcripts become a Map lookup instead of a re-parse, so repeated polls / multiple browser tabs no longer each re-parse the whole catalog. Same results, same ordering — just faster and far less event-loop pressure. No config, no behavior change.

Evidence

  • New tests in session-catalog.test.ts cover: cached reuse for unchanged transcripts (measured 2 → 0 transcript opens/parses on the unchanged second call), rescan of a changed transcript + negative-result refresh, discovery of a new transcript without re-reading siblings, eviction of a deleted transcript after a complete scan, and the test reset hook.
  • node scripts/run-vitest.mjs extensions/anthropic/session-catalog.test.ts — all green.
  • pnpm check:madge-import-cycles — 0 cycles.
  • Structured autoreview — clean, no actionable findings.
  • Contained entirely to extensions/anthropic/; no core src/** imports, no SDK/protocol changes.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5cc207c69d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if (!fileStat?.isFile()) {
continue;
}
const cached = catalogDiscoveryCache.get(filePath);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include session id in discovery cache keys

When an in-root symlink under ~/.claude/projects resolves to another transcript, this path-only cache can reuse a result parsed for the symlink's basename when the real basename is scanned later. inspectLine filters on the current sessionId, so a negative cache produced for alias.jsonl -> real-session.jsonl will be accepted for real-session.jsonl when mtime/size/ctime match, causing the real session to be omitted; before this change the second path was parsed with its own session id and could be discovered. Key the cache by both resolved path and session id, or reject/normalize such aliases before caching.

Useful? React with 👍 / 👎.

@steipete
steipete force-pushed the perf/anthropic-catalog-mtime-cache branch 2 times, most recently from 6f835dc to d94c6a2 Compare July 16, 2026 21:04
@steipete
steipete force-pushed the perf/anthropic-catalog-mtime-cache branch from d94c6a2 to 6154f10 Compare July 16, 2026 21:14
@steipete
steipete merged commit 7bc2b96 into main Jul 16, 2026
85 checks passed
@steipete
steipete deleted the perf/anthropic-catalog-mtime-cache branch July 16, 2026 21:41
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 17, 2026
zooqueen pushed a commit to zooqueen/openclaw that referenced this pull request Sep 11, 2026
steipete added a commit that referenced this pull request Oct 14, 2026
…le B) (#171920)

* fix(google): report the operation that supplied fallback video

An empty SDK video result can fall back to a distinct REST operation. Capture
its name after that fallback so returned metadata identifies the delivered video.
Keep the SDK error check before fallback and preserve requests and media limits.

Parameterize the existing fallback regression for SDK 404 and SDK empty results.
The real provider entry probe fails on the original empty-result metadata and
passes both scenarios with this fix, using synthetic SDK and HTTP responses.

* refactor(providers): consolidate old provider and protocol helpers

Share exact Gateway schema fields without changing public shapes. Consolidate
tool-payload classification, catalog responses, device polling, media formatting,
and speech format selection. Remove the Mantle factory's test-only injection seam.

Best-effort tradeoffs accepted:
- OpenRouter equivalent nested request policies reordered during configuration
  edits may cause another bounded catalog GET. #102062 supplies synthetic key
  equivalence, not a human incident; full auth/network policy stays in the key.
- Warm Anthropic scans may discover more history than cold scans. #109309/#115259
  establish synthetic frontier equality, not a human pagination incident. Charge
  actual I/O only, retaining the 64MiB read and bounded file/cache limits.
- A complete Anthropic read exactly at the I/O cap can now be cached. The former
  fence supported synthetic cold/warm cost equality; incomplete reads stay out.
- Deleted transcript metadata can remain in the bounded cache until eviction.
  #109309's eager sweeps duplicate current-candidate visibility and bounded
  retention; no current file means no visible cached row.
- A manually sparse single-audio-item array yields empty text rather than an
  invariant error. #104577/#104558 introduced the throw for a compiler ratchet;
  the real caller supplies a dense filter result, not a reported runtime failure.

Standalone session-memory backend and its registry/factory/tests are untouched.

* refactor(qa-lab): consolidate older harness paths

Share manifest discovery/linking, bus parser construction, Matrix device
verification, registration-local fault history, FIFO starts and mock answers.
Remove type-laundering and duplicate work on trusted internal facts.

Best-effort tradeoffs accepted

- Heap-capture PID fences came from synthetic replacement tests in #137860,
  not a human actual-use report. A coincident restart may fail or omit this
  optional diagnostic; the snapshot-writer health barrier remains.
- Failed-realpath lexical guessing came from synthetic execution validation
  in #116912. A disappearing/inaccessible test now fails existing evidence
  verification instead of guessing its identity; real symlink paths still work.
- #143976 introduced duplicate taxonomy parsing alongside both production
  callers' canonical identity guarantees. Untyped invalid internal build calls
  omitting required identity are unsupported; external artifact validation stays.
- Manifest discovery is invocation-local. A source catalog changed during
  staging is best-effort and is rescanned on the next invocation, rather than
  repeatedly scanning the same catalog for each selected plugin.
- The search fixture's fixed hostname (8288b4d) needs no URL-parser fallback.
  No runtime hostname input exists; a future fixture URL rewrite must update
  its hostname field too. Current output is unchanged.
- db4ad84 projected hit objects to hide registration IDs. Those IDs are now
  gone, and all private callers only read hit facts. Unexpected future internal
  object mutation may alter QA diagnostics; stable array snapshots remain.

Focused owner tests, canonical QA production/test typechecks, syntax lint,
formatting, suppression tests, zero runtime/madge cycles and independent
P0-P2 review cover the retained cut. No SDK/config/protocol/schema changes.

Local broad-proof gaps are recorded in .local/q04-ledger.md: SDK boundary
declaration preparation exceeded its existing 300000ms deadline before typed
lint ran; the repo-wide SQLite worker scanner was interrupted after more than
25 minutes on an overloaded host. Neither is attributed as inherited CI red.
The production, full-tree and script Knip scans also exceeded their existing
600-605s deadlines without a code verdict. Bundled exact-head CI must provide
the missing broad proof; no timeout/skip/retry policy was changed.

* refactor(android): simplify legacy native owners

Use platform accessibility nodes and canonical coroutine cancellation. Remove duplicate sheet validation and unreachable mascot clamps while retaining security, resource bounds and normal lifecycle behavior.

Fix DNS-SD display names by preserving advertised UTF-8 text and decoding instance names once. Both Android APK variants, 260 focused native test cases, lint, cycle checks and independent review validate the candidate.

* refactor: keep round-3 bundle within old-code scope

Drop all hunks in files touched on main within seven days, plus dependent Mantle, Anthropic cache, and QA assertion cuts. Preserve current main tests and baseline without allowances or shims. Keep Google SDK errors in the typed SDK owner and REST errors in its existing helper, without adding assertions. Retain one full mock ask-user roundtrip contract and the two distinct precedence cases.

* refactor(anthropic): preserve fresh hosts without map spread

* refactor(qa-lab): drop Gateway startup cleanup from bundle

Restore the q04 startup import closure and direct tests to main for Telegram menu E2E attribution. Keep Matrix/profile-evidence, provider, and Android changes unchanged.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 15, 2026
…le B) (openclaw#171920)

* fix(google): report the operation that supplied fallback video

An empty SDK video result can fall back to a distinct REST operation. Capture
its name after that fallback so returned metadata identifies the delivered video.
Keep the SDK error check before fallback and preserve requests and media limits.

Parameterize the existing fallback regression for SDK 404 and SDK empty results.
The real provider entry probe fails on the original empty-result metadata and
passes both scenarios with this fix, using synthetic SDK and HTTP responses.

* refactor(providers): consolidate old provider and protocol helpers

Share exact Gateway schema fields without changing public shapes. Consolidate
tool-payload classification, catalog responses, device polling, media formatting,
and speech format selection. Remove the Mantle factory's test-only injection seam.

Best-effort tradeoffs accepted:
- OpenRouter equivalent nested request policies reordered during configuration
  edits may cause another bounded catalog GET. openclaw#102062 supplies synthetic key
  equivalence, not a human incident; full auth/network policy stays in the key.
- Warm Anthropic scans may discover more history than cold scans. openclaw#109309/openclaw#115259
  establish synthetic frontier equality, not a human pagination incident. Charge
  actual I/O only, retaining the 64MiB read and bounded file/cache limits.
- A complete Anthropic read exactly at the I/O cap can now be cached. The former
  fence supported synthetic cold/warm cost equality; incomplete reads stay out.
- Deleted transcript metadata can remain in the bounded cache until eviction.
  openclaw#109309's eager sweeps duplicate current-candidate visibility and bounded
  retention; no current file means no visible cached row.
- A manually sparse single-audio-item array yields empty text rather than an
  invariant error. openclaw#104577/openclaw#104558 introduced the throw for a compiler ratchet;
  the real caller supplies a dense filter result, not a reported runtime failure.

Standalone session-memory backend and its registry/factory/tests are untouched.

* refactor(qa-lab): consolidate older harness paths

Share manifest discovery/linking, bus parser construction, Matrix device
verification, registration-local fault history, FIFO starts and mock answers.
Remove type-laundering and duplicate work on trusted internal facts.

Best-effort tradeoffs accepted

- Heap-capture PID fences came from synthetic replacement tests in openclaw#137860,
  not a human actual-use report. A coincident restart may fail or omit this
  optional diagnostic; the snapshot-writer health barrier remains.
- Failed-realpath lexical guessing came from synthetic execution validation
  in openclaw#116912. A disappearing/inaccessible test now fails existing evidence
  verification instead of guessing its identity; real symlink paths still work.
- openclaw#143976 introduced duplicate taxonomy parsing alongside both production
  callers' canonical identity guarantees. Untyped invalid internal build calls
  omitting required identity are unsupported; external artifact validation stays.
- Manifest discovery is invocation-local. A source catalog changed during
  staging is best-effort and is rescanned on the next invocation, rather than
  repeatedly scanning the same catalog for each selected plugin.
- The search fixture's fixed hostname (34f2850) needs no URL-parser fallback.
  No runtime hostname input exists; a future fixture URL rewrite must update
  its hostname field too. Current output is unchanged.
- 2f4f28f projected hit objects to hide registration IDs. Those IDs are now
  gone, and all private callers only read hit facts. Unexpected future internal
  object mutation may alter QA diagnostics; stable array snapshots remain.

Focused owner tests, canonical QA production/test typechecks, syntax lint,
formatting, suppression tests, zero runtime/madge cycles and independent
P0-P2 review cover the retained cut. No SDK/config/protocol/schema changes.

Local broad-proof gaps are recorded in .local/q04-ledger.md: SDK boundary
declaration preparation exceeded its existing 300000ms deadline before typed
lint ran; the repo-wide SQLite worker scanner was interrupted after more than
25 minutes on an overloaded host. Neither is attributed as inherited CI red.
The production, full-tree and script Knip scans also exceeded their existing
600-605s deadlines without a code verdict. Bundled exact-head CI must provide
the missing broad proof; no timeout/skip/retry policy was changed.

* refactor(android): simplify legacy native owners

Use platform accessibility nodes and canonical coroutine cancellation. Remove duplicate sheet validation and unreachable mascot clamps while retaining security, resource bounds and normal lifecycle behavior.

Fix DNS-SD display names by preserving advertised UTF-8 text and decoding instance names once. Both Android APK variants, 260 focused native test cases, lint, cycle checks and independent review validate the candidate.

* refactor: keep round-3 bundle within old-code scope

Drop all hunks in files touched on main within seven days, plus dependent Mantle, Anthropic cache, and QA assertion cuts. Preserve current main tests and baseline without allowances or shims. Keep Google SDK errors in the typed SDK owner and REST errors in its existing helper, without adding assertions. Retain one full mock ask-user roundtrip contract and the two distinct precedence cases.

* refactor(anthropic): preserve fresh hosts without map spread

* refactor(qa-lab): drop Gateway startup cleanup from bundle

Restore the q04 startup import closure and direct tests to main for Telegram menu E2E attribution. Keep Matrix/profile-evidence, provider, and Android changes unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant