Repository navigation
refactor(usage): move cache writes off the Gateway thread - #163287
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. Reviewed October 2, 2026, 1:52 AM ET / 05:52 UTC (Revision 2). ClawSweeper reviewWhat this changesMoves durable usage-cache writes, pruning, and refresh-lock transactions into the existing database worker while preserving incognito and maintenance behavior. Merge readiness✅ Ready for maintainer review This PR remains useful: current main still executes usage-cache transactions on the calling thread, and neither related PR supersedes it. No actionable correctness or security finding remains; the captured body records approval for the reviewed head, resolving the previous next step. Priority: P2 Review scores
Verification
How this fits togetherUsage reporting aggregates session transcripts into per-agent SQLite cache rows. The Gateway retains refresh authority and publishes results while database workers execute durable transactions. flowchart TD
A[Session transcripts] --> B[Usage computation worker]
B --> C[Gateway refresh owner]
C --> D[Writer queue and live admission]
D --> E[Agent database worker]
E --> F[SQLite usage cache]
F --> G[Usage reports]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +150, Tests +153. Total +303 across 8 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Keep durable cache mutations under the canonical worker owner with exact-byte comparisons, live admission, and joined cleanup. Do we have a high-confidence way to reproduce the issue? Yes, current-main source establishes caller-thread cache transactions, and the production refresh regression has a reported baseline failure for that SQL. This review did not execute tests. Is this the best way to solve the issue? Yes, extending the existing database executor reuses the authoritative kernels and preserves the supported native exceptions. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against a272cf0cd56e. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
|
Merged via squash.
|
…63287) * refactor(usage): move cache writes to agent database workers * test(usage): await Doctor cache worker cleanup
What Problem This Solves
Usage reports aggregate in a worker, but their host effect handler still executed rollup writes, pruning, and refresh-lock transactions on the Gateway thread. This left the cache writer outside the existing asynchronous agent-database port.
Why This Change Was Made
Register typed rollup-write, prune, acquire-lock, and release-lock operations with the existing agent execution owner. Durable refreshes await those operations; the existing connection-bound kernels still own exact-byte CAS, prune snapshots, and PID/nonce lock matching. The usage computation worker and host authority owner remain in place.
Retain acquisition and cleanup custody before yielding. Transaction and commit admission recheck live authority, and exact-lock cleanup uses the admitted physical identity even if an acquisition reply is lost. Cold creation permits the temporary missing-file transition only after shared-owner admission and adopts only the accepted worker identity. No data write is replayed after an uncertain result.
User Impact
cache_entriesSQL after this change.cache-read1, cache kernel 10, cache facade 1); T2 migration 3 → 3 and agent executor W 1 → 1. The same kernels and native transaction remain reachable for incognito/maintenance, so reclassifying the mixed files would be incorrect. Nine previously host-exposed primitive sites in the durable write flow now execute in the worker; already-worker reads are not counted as new savings.Evidence
Baseline:
212a6b81d58d01624e787b097db01bb6bb5ef58c. Final head:496767dbf0ed3c734386635b9300e6c401df2bbf.Integrated main
db20d752394fed8a02e8fa97b1169f5f294fb45bwithout conflicts. All final tests below usedOPENCLAW_VITEST_NO_OUTPUT_TIMEOUT_MS=1800000and/usr/bin/time -pon the loaded local host.pnpm test src/infra/session-cost-usage-cache.admission.test.ts --maxWorkers=1pnpm test src/infra/session-cost-usage-cache.sqlite.test.ts --maxWorkers=1pnpm test src/infra/session-cost-usage-cache.worker.test.ts --maxWorkers=1pnpm test src/commands/doctor-usage-cost-cache.test.ts --maxWorkers=1The first final run included a 62.4-second compiled-worker build. The admission and refresh-worker files exceed the 30-second test-time guideline because they exercise existing real worker/database lifecycle, cancellation, contention, and recovery contracts. The three new delayed/revoked admission cases totaled 2.7 seconds of test time; the new foreign-file case took 4.3 seconds. No sleeps, polling, serial configuration, or production test seams were added.
node scripts/check-changed.mjs --base 212a6b81d58d01624e787b097db01bb6bb5ef58c: passed, including core production types, all 27 core test type graphs, changed-file lint, formatting, and guards.node scripts/run-tsgo.mjs -p tsconfig.core.json --incremental --tsBuildInfoFile .artifacts/tsgo-cache/core.tsbuildinfoandnode scripts/run-tsgo-core-test-shards.mjs --ci-graphs-json '["core-test-infra","core-test-state-logging"]': passed.node scripts/run-tsgo-core-test-shards.mjs --ci-graphs-json '["core-test-commands-doctor"]',node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json src/commands/doctor-usage-cost-cache.test.ts, and targetedoxfmt --check: passed.pnpm check:database-worker-ratchet --base 212a6b81d58d01624e787b097db01bb6bb5ef58c: passed before and after integration.pnpm check:madge-import-cycles: passed before and after integration, 0 cycles.node scripts/database-worker-inventory.mjs --json: captured on the pinned base and final production tree, filtered to the owner files above.git diff --numstat 212a6b81d58d01624e787b097db01bb6bb5ef58c...4d4f08b529dceand the final PR diff against integrated main: production +234/−84/net +150.git diff --check: passed.scoped-cleanat P0–P2. The final review covered the complete eight-file PR diff.Coverage includes writer FIFO, canceled and delayed acquisition, lost acquisition reply, authority revocation during a queued rollup, exact-lock cleanup and retry, stale prune snapshots, transactional rollback, cold creation, foreign-file refusal, incognito, and the existing Doctor flow. Native worker and SQLite boundary tests require actual private databases/workers; a mocked kernel cannot prove thread placement or native admission ordering. CI timing is unavailable at PR creation.
Two tooling-only attempts stopped before tests: the baseline compiler overlapped setup-generated artifacts, and the Doctor compiler observed removal of lint’s temporary configuration file. Checks and tests were then serialized. After setup finished, the baseline regression failed for the intended caller-thread SQL. The first implementation run exposed the cold-creation handoff and two fixture assumptions (a broad file-read mock and a trigger installed before worker admission); those were repaired and the affected suites passed. The later Doctor run exposed synchronous fixture teardown that deleted state before worker drainage; that fixture now awaits cleanup and injects rejection at its async storage boundary, while the cache-owner tests retain native rollback proof.
Compatibility retained
Facade signatures are unchanged: status and prune are asynchronous; the synchronous preparation function returns an owner with awaited acquire/write/prune/release methods. The private host transaction path is retained only for scopes excluded by the canonical execution owner: process-held incognito storage and authorized native maintenance/deletion recovery. Connection-bound kernel exports remain shared by workers and those native owners. The superseded general
runCacheWriteTransactionhelper is removed; no public SDK export changes.Update behavior
No schema, state format, retention, durability, permission, or configuration change. Doctor keeps the same old-scope cleanup behavior under its existing owner. No migration or operator action is required.
Overlapping open PRs
session-cost-usage-cache.sqlite.ts; it addresses same-process lock recovery. This change preserves the current PID/nonce policy.Maintainer-requested async-database campaign, wave 11, usagecache lane. Coordinator approved head
496767dbf0ed3c734386635b9300e6c401df2bbffor landing through the native maintainer workflow. ClawSweeper completed its exact-head review with no correctness or security findings; its coordinator-approval item is satisfied.