Repository navigation
perf: reuse background projection and usage reads - #170399
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis PR reuses committed previews, terminal-model facts, plugin namespace lists, and usage snapshots to reduce background database reads. Example: A session showing “Original preview” receives two duplicate transcript notifications.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this owner-directed optimization removes redundant reads still present on main, preserves the existing ownership contracts, and has passing exact-head CI with no actionable findings. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherGateway projections and plugin-state caches consume committed receipts, while database workers prepare session previews, fallback-model facts, and usage totals for session and usage responses. flowchart TD
A[Committed writes] --> B[Receipt publishers]
B --> C[Projection and namespace caches]
C --> D[Background workers]
D --> E[SQLite snapshots]
E --> D
C --> F[Session and usage responses]
D --> F
Technical reviewBest possible solution: Land the bounded read-reuse optimization with the existing receipt publishers, database workers, and cache lifecycle owners. Do we have a high-confidence way to reproduce the issue? Current-main source establishes the redundant invalidation, database-wide namespace-cache veto, and separate usage reads; supplied paired Gateway measurements corroborate the usage-read cost, and this review executed no target code. Is this the best way to solve the issue? The approach is proportionate: it retains canonical invalidation, same-namespace ordering, exact checkpoint matching, and the larger terminal probe when the newest message exceeds the preview budget. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 1a4e4e56caeb. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +68, Tests +322, Docs +7. Total +397 across 12 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
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 HistoryReview history (3 earlier review cycles)Reviewed October 12, 2026, 9:06 PM ET / October 13, 2026, 01:06 UTC (Revision 4). |
Preserve the admission and background-read ownership documentation.
Reuse receipt-backed preview and plugin namespace state, and combine the usage checkpoint body and partition read. Preserve bounded transcript reads and committed-write freshness. Three alternating measurement pairs keep warmed Gateway MAIN SQL at zero. Usage refresh saves one statement per turn without adding a request. Background throughput is essentially flat under the loaded host; full attribution and accepted edges are recorded in the PR. Validated with focused regressions and final-head CI. Required static checks have no PR-caused findings; the sole full-tree Knip finding was an inherited helper already removed on main.
What Problem This Solves
Turn-triggered background work rereads transcript tails and usage checkpoints, and discards reusable plugin namespace lists during unrelated writes. This change keeps each existing owner and removes redundant work.
User Impact
There is no intended user-visible behavior change; session previews, fallback model facts, plugin state and usage totals remain current after committed writes, with less background database work.
Why This Change Was Made
Reuse facts already read or published by the existing owner:
No schema, durability, retention, public SDK, update, or memory-indexing scheduling/publication change. Memory indexing is measured separately and owned by the dedicated lane.
Removed checks and accepted edges
T1 and operation cost
Touched production area T1: 0 → 0. Preview/status synchronous extraction is called only by the history worker or incognito side-data worker; host status callers use the asynchronous reader or prepared facts. Existing mixed native session/usage kernels are unchanged. In particular, the shared usage-cache kernel retains its six native sites for incognito/maintenance; cutting those over needs its writer owner redesigned and is stopped under the escape hatch. This PR does not reclassify that debt. The retained native sites are
readSessionCostUsageRollupValuesInDatabase(1),writeSessionCostUsageRollupInDatabase(1),readSessionCostUsageRollupBodyInDatabase(1), andpruneSessionCostUsageRollupsInDatabase(3).Live measurement
Three alternating pairs (M,C,M,C,M,C), ten warmed turns per run, using the frozen shared harness v2.0.0 against isolated synthetic state. Base
5cf2615e65ec2e8344c836a5572c523783981e60; measured source9b434ae598b6019c9a3f3138ef62496baa9a015d. The PR implementation is unchanged at final merge head; the merge incorporates main’s unrelated commits, with documentation as the only conflict resolution. Measurements apply to this pinned base/candidate pair, not to a remeasurement of incoming main commits.All runs passed the complete foreground/child/cron/compaction workload. The first aborted baseline setup is excluded. Both sides use the same harness copy; its only adaptation sets the synthetic Gateway handshake timeout to 90 seconds after the original 15-second setup timed out under load. The shared harness was not edited. Every run used the local CPU semaphore.
Values are median [min–max]. “Turn” counts preserve the harness causal scope; raw window counts also include detached work.
Start load averages (32 CPUs): base 135.3, 98.5, 61.1; candidate 97.8, 94.7, 64.2.
Attributed saving: usage background work is exactly 100→90 statements and 20→20 requests in each ten-turn run. Completed bounded previews and cached namespace reads add no requests. Raw warmed requests rise 55.4→56.7 and whole-workload requests 1264→1291; the third candidate overlaps 64 maintenance requests versus 4 in the third baseline, while the changed usage work stays at 20 and projection preparation stays at 20 (first pair 20→21). The shared read families below do not rise. Under the campaign attribution rule, the raw increase is reported as scheduling noise, not hidden or attributed to a saving.
Background activity below uses pooled exposure time across the three runs so category rates add to the pooled total. These are stack-supported activities, not invented originating turn IDs. Memory includes indexing, preparation, publication and retrieval; all memory work remains outside this PR.
Background owner and SQL family census
Statement owners are SQL executors. Request owners are scheduling producers; generic queue-only memory requests are joined to successful execution by request ID and explicitly labeled executor. An owner appearing in one table does not imply one request per statement.
src/infra/sqlite-busy-timeout.ts:setSqliteBusyTimeoutextensions/memory-core/src/memory/manager-chunk-writer.ts:writeMemoryChunkssrc/state/openclaw-agent-execution-operations.ts:usageCache.writeRollupextensions/memory-core/src/memory/manager-source-index-kernel.ts:MemorySourceIndexKernel.deleteVectorsextensions/memory-core/src/memory/manager-retrieval-read.ts:readMemoryDatabaseFactsextensions/memory-core/src/memory/manager-embedding-cache.ts:upsertMemoryEmbeddingCacheextensions/memory-core/src/memory/manager-vector-write.ts:writeMemoryVectorsextensions/memory-core/src/memory/manager-publication.worker.ts:transactextensions/memory-core/src/memory/manager-publication.worker.ts:Object.withCommitextensions/memory-core/src/memory/manager-embedding-cache.ts:countMemoryEmbeddingCachesrc/infra/sqlite-wal-checkpoint.ts:checkpointsrc/config/sessions/session-accessor.sqlite-read.ts:readTranscriptExportSnapshotReadOnlySyncsrc/infra/session-cost-usage-cache.kernel.ts:writeSessionCostUsageRollupInDatabasesrc/config/sessions/session-accessor.sqlite-transcript-watermark-read.ts:readSessionTranscriptHotWatermarksrc/config/sessions/session-accessor.sqlite-transcript-stats.ts:readTranscriptStatsBatchFromDatabasesrc/gateway/session-row-projection-shared-facts.ts:prepareSessionRowSharedFactssrc/trajectory/runtime-retention.ts:<anonymous>src/config/sessions/session-transcript-worker-runtime.ts:runRequest<multiple memory-core executors>src/infra/session-cost-usage-cache.sqlite.ts:<anonymous>src/infra/session-cost-usage-worker-scope.ts:Object.runextensions/memory-core/src/memory/manager-retrieval-read.ts:readMemoryDatabaseFactsextensions/memory-core/src/memory/manager-embedding-cache.ts:loadMemoryEmbeddingCacheextensions/memory-core/src/memory/manager-source-index-kernel.ts:readMemorySourceChunksextensions/memory-core/src/memory/manager-embedding-cache.ts:countMemoryEmbeddingCacheextensions/memory-core/src/memory/manager-source-state.ts:loadMemorySourceFileStatesrc/config/sessions/session-transcript-read-worker-runtime.ts:readSessionEntryInWorkerSELECTINSERTPRAGMACOMMITDELETEBEGIN IMMEDIATEBEGINRELEASE SAVEPOINT openclaw_tx_nestedSAVEPOINT openclaw_tx_nestedCREATEDROPno-turn-contextwal-maintenanceNamed background targets, raw statements over all thirty warmed turns:
readParticipantRowsreadSelectedSessionEntryRowsreadSessionTranscriptWatermarkInDatabasereadSessionTranscriptHotWatermarkreadTranscriptStatsBatchFromDatabasereadSessionCostUsageRollupBodyInDatabasereadSessionCostUsagePartitionsInDatabasereadSessionCostUsageRollupWithPartitionsInDatabasereadProjectionSnapshot,iterateVisibleMessageMetadata,readSnapshotEventRowsandlistPluginStateEntriesare absent as background SQL owners in this current-base trace; they were targets in the earlier census. The owner census above identifies the current execution names instead.Envelope attribution below counts BEGIN/BEGIN IMMEDIATE/COMMIT statements, including both ends, over all thirty warmed turns. The sampled envelopes contain multi-statement writes or consistent read snapshots; none is removed as a single-statement transaction.
src/state/openclaw-agent-execution-operations.ts:usageCache.writeRollupextensions/memory-core/src/memory/manager-publication.worker.ts:transactextensions/memory-core/src/memory/manager-publication.worker.ts:Object.withCommitsrc/config/sessions/session-accessor.sqlite-read.ts:readTranscriptExportSnapshotReadOnlySyncsrc/gateway/worker-environments/placement-read-projection.ts:readWorkerPlacementRecoveryCandidatesInDatabasesrc/state/openclaw-agent-execution-operations.ts:trajectory.retention.deletesrc/config/sessions/session-entry-read.worker.ts:readSessionRowDatabaseFactssrc/state/openclaw-state-db-transaction.ts:transactionThe trace records producer stacks and scheduling roots but does not retain SQL bindings/session IDs or the original transcript-append/entry-write notification across every detached queue. Exact per-session duplicate counts and those missing trigger identities are therefore not claimed. The official plugin catalog was one request in the first baseline, not a repeated hotspot. Memory
runRetrievalrequests andreadMemoryDatabaseFactsexecutions are included in the separate memory activity total; that total is not mislabeled as indexing-only.prepareSessionRowSharedFactsremains a repeated request owner: 20 requests in each ten-turn baseline and 21/20/20 in the candidates. The two requests per ordinary window are a follow-up; this trace cannot prove that their SQL inputs identify the same session. Usage stats, hot watermark and each rollup stage run once per warmed turn in all runs.The harness has no isolated idle phase and its SQL events have no timestamps, so this run cannot establish an idle-only SQL/min comparison. No idle timer or maintenance schedule changed; measured maintenance activity is disclosed above. Memory accounts for about 63% of pooled baseline background SQL and idle maintenance another 6%; those owners are outside this patch. The 40% background reduction target is not claimed.
Evidence
server-restart-sentinel.test.ts/ “appends and broadcasts the durable internal update outcome only once” returns{ delivered: false, owned: false }on both PR CI and main run 38322669274, main96db2f6dfa4f47fd579a6d8408011950b8af53e1, at line 1038. The PR does not touch that owner.extensions/qa-lab/src/mantis/run.test-support.ts:timedOutCommandResultexport, independently reproduced on clean main baselinebe49163a5b5fbdf984e0c209f790d5823131f221. Main already removed it in 582b6dd0041c, and a clean merge-tree check confirms it is absent from this PR’s merge result. Two wrapper attempts hit the host-load timeout; the same published Knip version/config completed directly without changing repository gates. No PR-caused static findings remain. SDK diff and published-driver update cell are not applicable.Remaining owner work
Sampled read/write transaction envelopes contain multiple related statements, so they remain intact. Fusing usage rollup/partition writes requires completing the shared incognito writer cutover. Removing the later generation/watermark read requires the stats owner to extend its existing batch result; replacing it with point reads would regress large inventories. Participant reads need the membership owner's complete receipt contract. The remaining two shared-facts requests per ordinary warmed window need attribution through that owner before a cutover. These are follow-ups, not new competing owners in this patch.
LOC: production +86/−18, tests +324/−2, docs +8/−1. Regression coverage accounts for most of the growth; the old duplicate paths are removed.