Skip to content

fix(usage): coalesce incremental projection refreshes - #169974

Merged
steipete merged 3 commits into
mainfrom
dbasync/usagerefresh
Oct 12, 2026
Merged

steipete merged 3 commits into
mainfrom
dbasync/usagerefresh

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes excessive SQLite work on ordinary chat turns after proactive Usage projections were introduced in #169660. Every transcript publication could acquire and release a durable refresh lock and rescan transcript pages even when no Usage report was open.

User Impact

Usage projections remain proactive, and an overview read flushes pending publication work so completed turn usage is immediately available. Startup backfills retain their existing nonblocking partial-report behavior. No configuration, schema, retention, or update migration changes.

Why This Change Was Made

The existing usage owner now coalesces publications for 100 ms, skips explicit user/metadata-only publications, and resumes SQLite scans after the previous sequence. It reads the transcript owner's existing rewrite watermark once; rewrites, rewinds, and branch changes rebuild visible ancestry. Each payload page is decoded once and retained only as navigation and small usage contributions.

Cache refresh exclusion belongs to the Gateway process. A process-local reservation replaces lock discovery/acquire/release SQL; the writer atomically upserts the checkpoint and changed month partitions. Incognito keeps its separate compute-owned locking. Usage-only writes continue to publish no session-fact invalidations. The unused lock-status worker API is deleted.

Removed checks and accepted edges:

  • Durable lock PID/nonce discovery and release recovery: unsupported simultaneous foreign cache writers are not coordinated; the Gateway owns the database.
  • Previous-envelope compare-and-swap: one refresh reservation owns these derived writes; explicit deletion still drains the retained writer.
  • Repeated anchor, navigation/payload, post-scan metadata, and tail rereads: a concurrent rewrite may briefly leave a stale derived projection; its next publication rebuilds it using the existing rewrite watermark.
  • Full-cache pruning on an incremental refresh: deletion/topology and full discovery retain pruning ownership.

Evidence

  • Area T1 inventory: 0 → 0; the optimization reduces worker statements and requests.
  • Regression coverage: suffix-only reads, totals against full scans after appends/rewrites/rewinds/compaction, immediate overview freshness, write exclusion, atomic partitions, deletion drainage, and actor residency.
  • Codex autoreview: two rounds; one missing collection-access argument fixed, final review clean through P2. Changed-file oxfmt, type-aware oxlint, and git diff --check pass.
  • PR CI supplies focused tests and type/lint/Madge/T1/dialect checks; the Knip export scan runs separately under the CPU gate.
  • Live baseline/candidate pair passed: all 13 turns, child, cron, control-plane RPCs, compaction, and graceful shutdown. Usage: 122 → 10 SQL / 18 → 2 requests per warmed turn, below the 15/3 target. All five shared read families also decreased.
  • LOC: +531 / −892 (net −361).

Live statement and request measurements

One live baseline/candidate pair at 037aa311e1325ccc148473f03b996bc1ad8201a4 / 580dd4173031577848972251ee04760eef69a6f9, respectively, under the campaign CPU gate. Each run has 10 warmed turn windows. Median [min–max] below is across those 10 turn windows; the mean is the census-compatible per-turn count. This is not a three-run median-of-means. Both runs use the same workload and instrumentation.

Warm metric Baseline median [min–max] Candidate median [min–max] Baseline mean Candidate mean Mean delta
All-thread statements 390 [363–469] 254 [250–261] 395.7 254.2 -141.5
Worker requests 87 [79–96] 62 [61–63] 87.3 61.8 -25.5
Gateway MAIN statements 0 [0–0] 0 [0–0] 0.0 0.0 +0.0

Per-family values are ten-turn means.

Usage request family Baseline SQL Candidate SQL Baseline requests Candidate requests
usage-cost 75.0 6.0 3.0 1.0
usage-cache 3.0 0.0 3.0 0.0
usageCache.acquireLock 12.0 0.0 3.0 0.0
usageCache.prune 12.0 0.0 3.0 0.0
usageCache.releaseLock 9.0 0.0 3.0 0.0
usageCache.writeRollup 11.0 4.0 3.0 1.0
Usage total 122.0 10.0 18.0 2.0
Shared read family Baseline SQL/turn Candidate SQL/turn Delta
exact-entry facts 6.2 5.0 -1.2
actor hydration 4.4 4.1 -0.3
entry-cache snapshot loads 0.5 0.0 -0.5
row facts: primary row SELECT 1.1 1.0 -0.1
watermark reads 2.1 2.0 -0.1
Whole workload, startup–shutdown Baseline Candidate Delta
All-thread statements 10,707 8,543 -2,164
Worker requests 1,759 1,352 -407
Gateway MAIN statements 2,005 2,001 -4
Phase Baseline SQL Candidate SQL Baseline requests Candidate requests Baseline MAIN Candidate MAIN
01.boot 2744 2011 88 71 1861 1852
01.connect 481 972 78 67 16 17
02.first-turn 918 532 165 118 36 42
04.second-session 1587 1112 340 264 11 10
05.control-plane 11 27 2 7 0 0
06.cron 578 486 137 116 2 2
07.compaction 257 545 43 44 32 34
08.shutdown 174 316 33 47 47 44

Live durations were 107.7s / 127.1s (ratio 1.18). Initial host 1-minute loads were 60.86 / 63.51. These are execution counts on a loaded host, not latency benchmarks. Both complete fixtures passed the 13 top-level turns, awaited child, control-plane RPCs, cron, committed compaction, and graceful shutdown. Calibration passed independently on MAIN and worker: 8 calls, 2 prepares, 7 successful statements, zero failures.

Usage work decreases in every exercised phase: connect 49→22 SQL, first turn 117→9, second session 357→38, cron 77→9, and compaction 40→6. The six usage families sum to 1,864→184 SQL and 280→38 requests across the whole workload.

The larger raw connect window reflects an existing 689-statement database open admission moving from boot; combined boot+connect falls 3,225→2,983 SQL. The larger compaction/shutdown windows contain deferred Memory admission and synchronization: schema.admit contributes 135 direct + 133 domain-publication statements, followed by source/vector/cache work. Their source stacks are the unchanged extensions/memory-core/src/memory/manager-publication.worker.ts, manager-source-index-kernel.ts, and manager-embedding-cache.ts. They do not add usage work, and the full workload decreases by 2,164 statements and 407 requests.

CI diagnosis and final proof

Initial CI at 580dd4173031 passed production and test typechecks, source contracts/export collisions, Madge (zero cycles), and database worker/dialect/test-mock ratchets. Two Usage test fixtures depended on the removed lock-write side effects: rollback injection now explicitly admits the writer before adding its trigger; the failure/recovery fixture shuts down a cache-miss worker through the runtime owner. Commit f4d43500106a changes only those tests, so the measured production inputs remain unchanged. The rollback file passes 17/17 locally (pnpm test src/infra/session-cost-usage-cache.sqlite.test.ts --maxWorkers=1, 116.47s command / 106.95s Vitest; 9% test time, dominated by compiler startup). The worker file passes 9/9 (pnpm test src/infra/session-cost-usage-cache.worker.test.ts --maxWorkers=1, 119.55s command / 102.29s Vitest).

Initial-run inherited failures (the final-head lint jobs now pass):

  • check-lint-core-1: users-github.test.ts:679:40, typescript(no-unnecessary-type-arguments). The unchanged main file has blob c1c09082fa2438b05c6ae522290d013b035cc143; exact rule/line reproduced by type-aware oxlint on main. PR job.
  • session-accessor.pending-inputs.test.ts, “stages repeated relocation through savepoints and restores it on rollback”: database is locked at BEGIN IMMEDIATE. Exact test/error reproduced on current main f6dd2d3d (1/29 failed, 308.52s command / 284.08s Vitest); candidate 580dd417 passed 29/29 (284.86s / 268.45s). The test, transaction/admission and transcript-reconcile sources are byte-identical. This fixture mixes synchronous transactions with background projection writes; no repair is claimed. PR job.

The incremental append/rewrite/rewind/compaction regressions passed CI (worker-refresh and projection shard: 0.757s total; individual new cases 0–1ms). Initial cache SQLite and cache worker shards took 91.32s and 68.28s respectively; these include other files and the now-corrected fixture failures. No SDK or update-cell scope.

The final export cleanup (adfdc968aabb) removes the obsolete single-transcript resolver, uses the batched resolver in test support, and makes the existing incognito lock imports explicit so Knip can follow their production consumers. It changes no SQL or refresh scheduling. The live measurement remains applicable.

Final-head Knip export scans pass with zero production, full-tree, and script findings (pnpm deadcode:exports); changed-file type-aware lint, formatting, and diff checks pass.

Final head adfdc968aabb passes all production/test typecheck shards, core and extension lint, source contracts/export collisions, architecture/Madge, and database worker/dialect/test-mock ratchets in CI run 38271965137. The sole failed test shard repeats the independently reproduced main pending-inputs lock failure (final-head job); landing uses the authorized inherited-failure exception. CI has completed: checks-node-changed-compact-small-15 and build-artifacts also passed. The only failed test is the inherited pending-inputs savepoint case above; the aggregate CI gate is red for that same failure. All other scheduled jobs passed or were skipped by their workflow conditions.

Keep proactive Usage reports fresh while scanning each new transcript page once and replacing durable refresh-lock traffic with process-owned exclusion. Reuse transcript rewrite watermarks for rebuilds and preserve atomic projection writes and session-fact invalidation boundaries.
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: XL labels Oct 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR coalesces usage refresh publications, scans appended transcript rows once, and replaces durable refresh locks with process-local exclusion.

Example: Two assistant publications add 20 and 30 tokens to a session already containing 10 tokens.

  • Before: Publications can trigger separate refreshes with durable lock SQL and repeated transcript reads.
  • After: Nearby publications share a refresh, and an immediate overview read flushes the batch and returns 60 tokens.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is focused and source-supported, with meaningful integration coverage but no completed runtime comparison supplied.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored internal optimization is outside the ordinary contributor proof gate; inspected tests exercise persistence and immediate overview totals, while the body describes the live performance pair as still running.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Ordinary chat turns incur unnecessary usage-cache database work even when the Usage view is closed.
Reason: The feature-history owner authored this focused follow-up and explicitly recorded its recoverable concurrency tradeoffs.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep this PR: it is a useful maintainer-owned optimization that current main lacks, and source review found no concrete introduced defect.

Priority: P2
Reviewed head: 580dd4173031577848972251ee04760eef69a6f9

Before merge

Findings

None.

Tests

  • Missing end-to-end proof: The announced Gateway baseline/candidate comparison has no attached result yet, and failing-before execution of the added regression is not supplied.
Agent review details

How this fits together

Committed transcript publications enter the Gateway usage lifetime, which schedules worker scans and atomic derived-cache writes; usage reports consume those cached totals.

flowchart TD
  A[Transcript publications] --> B[Gateway usage lifetime]
  B --> C[Coalesced refresh queue]
  C --> D[Transcript scan worker]
  D --> E[Agent database writer]
  E --> F[Usage projection cache]
  G[Usage report request] --> C
  F --> G
Loading

Technical review

Best possible solution:

Keep coalescing and incremental scanning in the existing usage owner while preserving atomic projection writes and deletion drainage.

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

Current-main source connects transcript publications to durable lock acquisition, refresh scanning, and release even without an open Usage report; no runtime reproduction was executed during this read-only review.

Is this the best way to solve the issue?

The change addresses unnecessary work at its existing owner, removes the superseded lock reader, and preserves transcript authority without adding configuration or another scheduling layer.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 506684822c50.

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source -118, Tests -255, Docs +7. Total -366 across 26 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 15 261 379 -118
Tests 9 229 484 -255
Docs 2 13 6 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 26 503 869 -366

Labels

Label changes:

  • add P2: Reduces ordinary-turn database work without evidence of an urgent outage or broken core workflow.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: Reduces ordinary-turn database work without evidence of an urgent outage or broken core workflow.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rank-up moves

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

  • Attach the announced chat-turn and overview comparison with statement counts and preserved totals.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 12, 2026, 11:27 AM ET / 15:27 UTC.

@steipete

Copy link
Copy Markdown
Contributor Author

Hotguard coordination: this lane caches transcript hot/cold marker facts under existing session-ID write receipts and reuses autocommit participant rows inside an unchanged transaction. It does not change usage refresh scheduling, actor hydration, entry receipts, worker routing, or exported SDK contracts. Archive/restore and session deletion invalidate via their existing write scopes; unknown writes remain conservative misses. Shared-family counts will be reported with the live baseline/candidate pair. This composes with usage refresh coalescing and committed transcript context reuse; exact-entry receipt preservation is already included in the lane base.

@steipete
steipete merged commit 23dee30 into main Oct 12, 2026
145 of 148 checks passed
@steipete
steipete deleted the dbasync/usagerefresh branch October 12, 2026 15:52
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
Proactive Usage projections were rescanning transcript pages and acquiring durable refresh locks on every publication, adding 122 SQL statements and 18 worker requests per warmed turn after openclaw#169660.

Coalesce usage-bearing publications, resume scans from the existing transcript rewrite watermark, decode each page once, and use the Gateway-owned refresh reservation with atomic rollup/partition writes. Overview reads flush pending work for immediate completed-turn freshness. Remove obsolete lock discovery and resolver paths; preserve incognito locking and session-fact residency.

One live baseline/candidate pair reduced Usage work to 10 SQL statements and 2 requests per warmed turn. All-thread warmed medians fell from 390 to 254 statements and 87 to 62 requests; warmed MAIN and area T1 remain zero. All five shared read families decreased.

Regression coverage includes append/rewrite/rewind/compaction totals, immediate overview freshness, write exclusion, deletion drainage, and actor residency. Two Codex review rounds and Knip pass. Full evidence, CI results, and accepted derived-cache concurrency edges are recorded in the PR. No schema, configuration, retention, or update migration changes.

Final-head typechecks, lint, source contracts, Madge, and database ratchets pass. Land with the authorized exception for the unchanged pending-inputs savepoint test: its identical SQLite lock failure was reproduced independently on main.
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 gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL 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