Repository navigation
fix(usage): coalesce incremental projection refreshes - #169974
Conversation
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.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review in progressClawSweeper is reviewing this revision. This supersedes any previous blocked status. |
|
Codex review: needs changes before merge. What this changesThis 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.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete 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 Before merge
FindingsNone. Tests
Agent review detailsHow this fits togetherCommitted 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
Technical reviewBest 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
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource -118, Tests -255, Docs +7. Total -366 across 26 files. Added test files: 0. View PR surface stats
LabelsLabel changes:
Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 12, 2026, 11:27 AM ET / 15:27 UTC. |
|
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. |
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.
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:
Evidence
git diff --checkpass.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.Per-family values are ten-turn means.
usage-costusage-cacheusageCache.acquireLockusageCache.pruneusageCache.releaseLockusageCache.writeRollupLive 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
openadmission moving from boot; combined boot+connect falls 3,225→2,983 SQL. The larger compaction/shutdown windows contain deferred Memory admission and synchronization:schema.admitcontributes 135 direct + 133 domain-publication statements, followed by source/vector/cache work. Their source stacks are the unchangedextensions/memory-core/src/memory/manager-publication.worker.ts,manager-source-index-kernel.ts, andmanager-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
580dd4173031passed 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. Commitf4d43500106achanges 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 blobc1c09082fa2438b05c6ae522290d013b035cc143; 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 lockedatBEGIN IMMEDIATE. Exact test/error reproduced on current mainf6dd2d3d(1/29 failed, 308.52s command / 284.08s Vitest); candidate580dd417passed 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
adfdc968aabbpasses 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-15andbuild-artifactsalso 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.