Skip to content

perf(usage): stale-while-revalidate caches for usage.status and sessions.usage - #115369

Merged
steipete merged 1 commit into
mainfrom
perf/usage-result-caches
Jul 28, 2026
Merged

steipete merged 1 commit into
mainfrom
perf/usage-result-caches

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Opening the Usage page on team.openclaw.ai pays usage.status ~1294ms and sessions.usage ~1209ms every time. usage.status issued one authenticated HTTP fetch per configured provider on every call with no cache — while models.authStatus already had a purpose-built 60s credential-fingerprinted stale-while-revalidate cache for exactly this data. sessions.usage re-ran synchronous per-session transcript aggregates (a SUM over every event row per session, no covering index) on every call, with no result cache — unlike usage.cost, which already had the 30s TTL + coalescing pattern.

Why This Change Was Made

Both RPCs re-derived results that are stable for tens of seconds. Reusing the two existing cache disciplines (shared SWR module; the usage.cost wrapper shape) avoids new frameworks and keeps invalidation semantics consistent.

User Impact

Repeat Usage-page opens drop from ~1.2s per RPC to sub-10ms; provider HTTP fan-out happens at most once per 60s per credential set; the synchronous transcript aggregation no longer runs per open.

Evidence

  • usage.status shares the 60s credential-aware SWR cache with models.authStatus (single module, no duplication); credential change invalidates (test).
  • sessions.usage: bounded 256-entry 30s SWR cache keyed on config identity, scope/agent, dates, bucket, limit, grouping, key, and context-weight mode; in-flight coalescing; complete stale results preferred over partial refreshes (documented + tested).
  • Clone audit: the usage scan reads sessionId/timestamps only → listSessionTranscriptInstances(clone:false), removing a structuredClone of ~800 entries per call. No schema/index change; a (session_id, byte-size) rollup/index is noted as follow-up needing operator approval only if cold scans remain material.
  • 223 focused tests; response-shape parity; core tsgo, full lint, both deadcode lanes on Testbox (run https://github.com/openclaw/openclaw/actions/runs/30384451488); format, git diff --check; autoreview clean (three cache findings fixed, one rejected with fan-out proof).

@steipete
steipete marked this pull request as ready for review July 28, 2026 18:25
@steipete
steipete requested a review from a team as a code owner July 28, 2026 18:25
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: XL maintainer Maintainer-authored PR labels Jul 28, 2026
@steipete
steipete merged commit a21f235 into main Jul 28, 2026
176 of 182 checks passed
@steipete
steipete deleted the perf/usage-result-caches branch July 28, 2026 18:42
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit to christian-lallo/openclaw that referenced this pull request Jul 28, 2026
* origin/main: (61 commits)
  perf(ui): debounce event-driven session list refreshes and right-size child paging (openclaw#115374)
  feat(talk): support GPT-Live realtime voice over ChatGPT OAuth (openclaw#115226)
  feat(system-agent): guide gateway configuration in Ask OpenClaw (openclaw#115363)
  fix(agents): make overflow recovery append-only via branch-and-reappend (openclaw#115271) (openclaw#115310)
  fix(macos): bound websocket ping so a dropped pong cannot orphan its continuation (openclaw#115362)
  fix(codex): isolate native hook relay startup (openclaw#115078)
  fix(ci): stop reviving superseded pull request workflows (openclaw#115378)
  feat(openshell): add workspace selection (openclaw#114952)
  fix(skills): persist workshop apply reason; correct Skill Workshop docs (openclaw#114471)
  fix: agent stops replying when a session transcript has no header row (openclaw#115080)
  perf(usage): stale-while-revalidate caches for usage.status and sessions.usage (openclaw#115369)
  fix(discord): reject invalid UTF-8 probe responses (openclaw#111734)
  feat(gateway): add memory.search operator method (openclaw#115346)
  fix(android): keep welcome action reachable with large text (openclaw#111747)
  fix(gateway): validate doctor memory agent ids (openclaw#115365)
  refactor: harden shell completion and shard Control UI E2E (openclaw#115332)
  fix(ui): anchor the thread branches menu to its trigger button (openclaw#115352)
  perf(sessions): incremental snapshot revalidation and shallow list projections (openclaw#115359)
  refactor(sessions): consolidate entry state (openclaw#115299)
  feat(ui): swap three plain Lobsterdex palettes for balloon, ascii, and portal (openclaw#115308)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 29, 2026
obviyus added a commit that referenced this pull request Oct 16, 2026
…oviders on every load (#174741)

## What Problem This Solves

Fixes: the Models page never shows provider usage, and every page load re-runs provider usage probes, when `models.authStatus` and `usage.status` are requested together (as the page does).

## User Impact

User impact: provider usage appears on the Models page on load. Provider usage endpoints are polled once per 60 s cache window per provider set instead of on every page load.

## Why This Change Was Made

Both RPCs share one provider-usage cache entry and one in-flight refresh per agent. They ask for different provider sets: `models.authStatus` asks for providers with refreshable credentials, and `usage.status` asks for every usage-capable provider. When they ran together, each read missed the other's entry and started a refresh that superseded the other's in-flight refresh, so the earlier result was discarded. The result:
- `usage.status` answered `{ providers: [], refreshing: true }` on every load.
- `models.authStatus` carried no `usage`.
- Each load re-resolved auth and plugin runtime for every usage provider, and probed provider endpoints.

The cache now keeps one entry and one in-flight refresh per provider set within each agent. Nothing else changes: TTL, credential-bound invalidation, cold-read markers and stale-while-revalidate stay as they were.

`a21f235` (#115369) intended the two readers to share this cache. A later change gave them different provider sets.

## Evidence

Isolated Gateway on a copy of a real state directory: outbound network denied, base and fix run ABAB on the same restored state.

- **Work count** (alternating `usage.status` / `models.authStatus`, 8 calls): outbound usage probes on 7 of 8 calls (base) vs only on the first refresh of each provider set (fix).
- **Responses after identical warm-up:** `agents.list`, `config.get`, `models.list` and `sessions.usage` are identical. `usage.status` now returns the provider snapshots instead of `refreshing: true`. `models.authStatus` providers now carry `usage`.
- **Serial p50 over 20 calls, two rounds:** `usage.status` 4.9/4.3 ms → 0.8/1.0 ms. `models.list` 30.5/27.2 ms → 2.2/2.5 ms; the per-call refresh was also blocking it on the main thread. The host was heavily loaded, so treat wall times as indicative only.
- **CPU profile:** the per-load `resolveProviderRuntimePlugin` → `applyPluginAutoEnable` frames (~100 ms main thread per page load) are gone from steady-state page loads.
- **Tests:** new regression `refreshes each provider set once per TTL when page reads interleave` fails on base (4 refreshes in 3 loads) and passes with the fix (2). `usage.status-cache`, `usage-cache` and `models-auth-status` suites pass (66 tests).

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
…oviders on every load (openclaw#174741)

## What Problem This Solves

Fixes: the Models page never shows provider usage, and every page load re-runs provider usage probes, when `models.authStatus` and `usage.status` are requested together (as the page does).

## User Impact

User impact: provider usage appears on the Models page on load. Provider usage endpoints are polled once per 60 s cache window per provider set instead of on every page load.

## Why This Change Was Made

Both RPCs share one provider-usage cache entry and one in-flight refresh per agent. They ask for different provider sets: `models.authStatus` asks for providers with refreshable credentials, and `usage.status` asks for every usage-capable provider. When they ran together, each read missed the other's entry and started a refresh that superseded the other's in-flight refresh, so the earlier result was discarded. The result:
- `usage.status` answered `{ providers: [], refreshing: true }` on every load.
- `models.authStatus` carried no `usage`.
- Each load re-resolved auth and plugin runtime for every usage provider, and probed provider endpoints.

The cache now keeps one entry and one in-flight refresh per provider set within each agent. Nothing else changes: TTL, credential-bound invalidation, cold-read markers and stale-while-revalidate stay as they were.

`d24100c` (openclaw#115369) intended the two readers to share this cache. A later change gave them different provider sets.

## Evidence

Isolated Gateway on a copy of a real state directory: outbound network denied, base and fix run ABAB on the same restored state.

- **Work count** (alternating `usage.status` / `models.authStatus`, 8 calls): outbound usage probes on 7 of 8 calls (base) vs only on the first refresh of each provider set (fix).
- **Responses after identical warm-up:** `agents.list`, `config.get`, `models.list` and `sessions.usage` are identical. `usage.status` now returns the provider snapshots instead of `refreshing: true`. `models.authStatus` providers now carry `usage`.
- **Serial p50 over 20 calls, two rounds:** `usage.status` 4.9/4.3 ms → 0.8/1.0 ms. `models.list` 30.5/27.2 ms → 2.2/2.5 ms; the per-call refresh was also blocking it on the main thread. The host was heavily loaded, so treat wall times as indicative only.
- **CPU profile:** the per-load `resolveProviderRuntimePlugin` → `applyPluginAutoEnable` frames (~100 ms main thread per page load) are gone from steady-state page loads.
- **Tests:** new regression `refreshes each provider set once per TTL when page reads interleave` fails on base (4 refreshes in 3 loads) and passes with the fix (2). `usage.status-cache`, `usage-cache` and `models-auth-status` suites pass (66 tests).

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 19, 2026
…ession tests (#176630)

## What Problem This Solves

Performance work in OpenClaw keeps fixing the same waste twice: caches that stop hitting, batches that get reverted, and PRs that land with a regression their own numbers already show. Agents had no repository guide for this work, and three flows where the same waste keeps returning had no test that counts it.

## User Impact

No user-visible change. Agents doing performance work now have one OpenClaw skill: measure the real flow with a committed workload, count operations first, delete waste before batching or caching, and land only when every user-facing metric holds or improves. Three work-count tests fail CI if known waste comes back.

## Why This Change Was Made

A corpus of 103 performance cases from the last 90 days on `main` (70 randomly sampled, 33 seeded with every perf revert; each judged from its diff and PR text):

- **Deleting waste lasts:** 3 of 31 random-sample deletes were later re-fixed, and those failed deletes broke a guard, not because the waste returned.
- **Caches, batches and worker moves come back:** 4 of 5, 6 of 7 and 5 of 8 were later re-fixed (biased set, a signal not a rate). In 3 of the 4 cache re-fixes the cache silently stopped hitting, e.g. #115369 → #174741 and #149773 → #149879.
- **Own regressions predict reverts:** 21 PRs landed while their own numbers showed a large regression; 11 of them were later reverted or re-fixed, against 25 of the other 82. Five of the six reverts had shown the regression in their own body.
- **Same waste, again and again:** SQLite schema/admission re-checks (14 PRs, one revert), session list rows (two reverts in two days), model catalog rebuilds.

Changes:

- `.agents/skills/openclaw-performance/SKILL.md`: measure (committed bench per flow, counts first, acceptance rule before the first run, interleaved samples), find waste (10 recurring OpenClaw patterns with real cases), fix order (delete → once at the owner → carry the prepared fact → batch → cache with a written reason, cache-identity rules and an interleaved work-count test), land (no user-facing metric worse unless the owner accepts it).
- Root `AGENTS.md`: the "Do less work" line keeps its core rule and points to the skill.
- Work-count tests (counts, never wall time):
  - `src/state/openclaw-agent-execution.schema-admission.test.ts`: warm chat turns make only their own write requests; no re-open, schema prepare or integrity validation.
  - `src/gateway/session-row-projection.list-page.test.ts`: after an unrelated subagent renewal, repeating the same pages renders 0 rows, materializes 0 more and does 0 worker reads or SQL.
  - `src/gateway/server-methods/models-auth-status.work-count.test.ts` (own file, to keep the existing test under its line cap): interleaved `models.authStatus` and `usage.status` page loads add no provider probes, auth-health builds or catalog loads after warm-up.

## Evidence

| Test | Back-test (parent of the historical fix) |
|---|---|
| Schema admission | fails at `8b7917c79b8^` (#166253): each warm turn adds `open` and `prepare` again |
| Session list | fails at `1b896e6327f^` (#162280): 80 rows materialized instead of 10, plus 1 worker read |
| Models page | fails at `c3f0b6abc01^` (#174741): 3 provider probes in 2 loads; the readers evict each other |

- All three pass on head (each file about 0.3–1.7 s); `models-auth-status.test.ts` still passes 52/52. The Models page test still fails at `c3f0b6abc01^` with real-module mocks (one extra provider probe).
- The pre-commit hook (line-cap ratchet, `AGENTS.md` size) passed; root `AGENTS.md` is 18,917 characters.
- Every PR cited by the skill is merged; every named bench script exists on `main`.

Blind replay of 8 held-out performance tasks (none cited by the skill; each from the parent of its known-good fix), Codex agent with and without the skill, 2 seeds; stopped early after 12 judged pairs to free the host:

| | Without skill | With skill |
|---|---|---|
| Pair wins (blind Codex judge) | 3 | 8 (1 tie) |
| Removed the same waste as the reference fix | 11/14 runs | 11/13 runs |
| Proof includes a work-count test | 5/14 | 11/13 |
| Added a cache | 1 | 1 |
| Judge: proof / waste found / fix order (1-5) | 3.08 / 4.50 / 4.83 | 4.33 / 4.42 / 4.50 |

The skill does not change whether agents find the waste; it changes how they prove it, which is what keeps the waste from returning. One judge and 12 pairs: the win split is not significant (p ≈ 0.23).

**Merge danger:** two-way door; a revert removes the skill and the tests. No runtime change. Blast radius: agent instructions for performance work, and three test files.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 19, 2026
…ession tests (openclaw#176630)

## What Problem This Solves

Performance work in OpenClaw keeps fixing the same waste twice: caches that stop hitting, batches that get reverted, and PRs that land with a regression their own numbers already show. Agents had no repository guide for this work, and three flows where the same waste keeps returning had no test that counts it.

## User Impact

No user-visible change. Agents doing performance work now have one OpenClaw skill: measure the real flow with a committed workload, count operations first, delete waste before batching or caching, and land only when every user-facing metric holds or improves. Three work-count tests fail CI if known waste comes back.

## Why This Change Was Made

A corpus of 103 performance cases from the last 90 days on `main` (70 randomly sampled, 33 seeded with every perf revert; each judged from its diff and PR text):

- **Deleting waste lasts:** 3 of 31 random-sample deletes were later re-fixed, and those failed deletes broke a guard, not because the waste returned.
- **Caches, batches and worker moves come back:** 4 of 5, 6 of 7 and 5 of 8 were later re-fixed (biased set, a signal not a rate). In 3 of the 4 cache re-fixes the cache silently stopped hitting, e.g. openclaw#115369 → openclaw#174741 and openclaw#149773 → openclaw#149879.
- **Own regressions predict reverts:** 21 PRs landed while their own numbers showed a large regression; 11 of them were later reverted or re-fixed, against 25 of the other 82. Five of the six reverts had shown the regression in their own body.
- **Same waste, again and again:** SQLite schema/admission re-checks (14 PRs, one revert), session list rows (two reverts in two days), model catalog rebuilds.

Changes:

- `.agents/skills/openclaw-performance/SKILL.md`: measure (committed bench per flow, counts first, acceptance rule before the first run, interleaved samples), find waste (10 recurring OpenClaw patterns with real cases), fix order (delete → once at the owner → carry the prepared fact → batch → cache with a written reason, cache-identity rules and an interleaved work-count test), land (no user-facing metric worse unless the owner accepts it).
- Root `AGENTS.md`: the "Do less work" line keeps its core rule and points to the skill.
- Work-count tests (counts, never wall time):
  - `src/state/openclaw-agent-execution.schema-admission.test.ts`: warm chat turns make only their own write requests; no re-open, schema prepare or integrity validation.
  - `src/gateway/session-row-projection.list-page.test.ts`: after an unrelated subagent renewal, repeating the same pages renders 0 rows, materializes 0 more and does 0 worker reads or SQL.
  - `src/gateway/server-methods/models-auth-status.work-count.test.ts` (own file, to keep the existing test under its line cap): interleaved `models.authStatus` and `usage.status` page loads add no provider probes, auth-health builds or catalog loads after warm-up.

## Evidence

| Test | Back-test (parent of the historical fix) |
|---|---|
| Schema admission | fails at `04c36511d39^` (openclaw#166253): each warm turn adds `open` and `prepare` again |
| Session list | fails at `d13db6a6cc8^` (openclaw#162280): 80 rows materialized instead of 10, plus 1 worker read |
| Models page | fails at `c373547bbbd^` (openclaw#174741): 3 provider probes in 2 loads; the readers evict each other |

- All three pass on head (each file about 0.3–1.7 s); `models-auth-status.test.ts` still passes 52/52. The Models page test still fails at `c373547bbbd^` with real-module mocks (one extra provider probe).
- The pre-commit hook (line-cap ratchet, `AGENTS.md` size) passed; root `AGENTS.md` is 18,917 characters.
- Every PR cited by the skill is merged; every named bench script exists on `main`.

Blind replay of 8 held-out performance tasks (none cited by the skill; each from the parent of its known-good fix), Codex agent with and without the skill, 2 seeds; stopped early after 12 judged pairs to free the host:

| | Without skill | With skill |
|---|---|---|
| Pair wins (blind Codex judge) | 3 | 8 (1 tie) |
| Removed the same waste as the reference fix | 11/14 runs | 11/13 runs |
| Proof includes a work-count test | 5/14 | 11/13 |
| Added a cache | 1 | 1 |
| Judge: proof / waste found / fix order (1-5) | 3.08 / 4.50 / 4.83 | 4.33 / 4.42 / 4.50 |

The skill does not change whether agents find the waste; it changes how they prove it, which is what keeps the waste from returning. One judge and 12 pairs: the win split is not significant (p ≈ 0.23).

**Merge danger:** two-way door; a revert removes the skill and the tests. No runtime change. Blast radius: agent instructions for performance work, and three test files.

Co-authored-by: Ayaan Zaidi <[email protected]>
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 size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant