Skip to content

refactor(usage): move cache writes off the Gateway thread - #163287

Merged
steipete merged 3 commits into
mainfrom
dbasync/usagecache
Oct 2, 2026
Merged

steipete merged 3 commits into
mainfrom
dbasync/usagecache

Conversation

@steipete

@steipete steipete commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Durable usage-cache SQL moves off the calling thread. The real refresh regression fails on the pinned baseline and passes with no caller-thread cache_entries SQL after this change.
  • Raw owner inventory: T1 12 → 12 (cache-read 1, 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.
  • Lane production LOC: +234 / −84 / net +150, excluding tests/support/docs. No inventory classification or generated inventory document changed.
  • No user configuration or stored format change; no performance benchmark claim.

Evidence

Baseline: 212a6b81d58d01624e787b097db01bb6bb5ef58c. Final head: 496767dbf0ed3c734386635b9300e6c401df2bbf.

Integrated main db20d752394fed8a02e8fa97b1169f5f294fb45b without conflicts. All final tests below used OPENCLAW_VITEST_NO_OUTPUT_TIMEOUT_MS=1800000 and /usr/bin/time -p on the loaded local host.

Exact test command Result Wall time
pnpm test src/infra/session-cost-usage-cache.admission.test.ts --maxWorkers=1 16 passed 174.30 s
pnpm test src/infra/session-cost-usage-cache.sqlite.test.ts --maxWorkers=1 12 passed 47.84 s
pnpm test src/infra/session-cost-usage-cache.worker.test.ts --maxWorkers=1 10 passed 91.73 s
pnpm test src/commands/doctor-usage-cost-cache.test.ts --maxWorkers=1 9 passed 58.03 s

The 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.
  • After merging main: node scripts/run-tsgo.mjs -p tsconfig.core.json --incremental --tsBuildInfoFile .artifacts/tsgo-cache/core.tsbuildinfo and node scripts/run-tsgo-core-test-shards.mjs --ci-graphs-json '["core-test-infra","core-test-state-logging"]': passed.
  • Final Doctor fixture: 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 targeted oxfmt --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...4d4f08b529dce and the final PR diff against integrated main: production +234/−84/net +150.
  • git diff --check: passed.
  • Codex autoreview: branch review against integrated main and final local review including the Doctor fixture both returned scoped-clean at 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 runCacheWriteTransaction helper 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

Maintainer-requested async-database campaign, wave 11, usagecache lane. Coordinator approved head 496767dbf0ed3c734386635b9300e6c401df2bbf for landing through the native maintainer workflow. ClawSweeper completed its exact-head review with no correctness or security findings; its coordinator-approval item is satisfied.

@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations size: L labels Oct 2, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 2, 2026
@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 2, 2026, 1:52 AM ET / 05:52 UTC (Revision 2).

ClawSweeper review

What this changes

Moves 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
Reviewed head: 496767dbf0ed3c734386635b9300e6c401df2bbf

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent worker cutover with focused native boundary coverage and no actionable review finding.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: Repository State identifies a MEMBER author, exempting ordinary contributor proof. The captured body reports native worker/SQLite execution through the production refresh owner, including queued revocation, lost replies, rollback, and cleanup; inspected source supports those boundaries, with no unresolved authority violation or stored-format change.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Repository State identifies a MEMBER author, exempting ordinary contributor proof. The captured body reports native worker/SQLite execution through the production refresh owner, including queued revocation, lost replies, rollback, and cleanup; inspected source supports those boundaries, with no unresolved authority violation or stored-format change.
Evidence reviewed 9 items Pinned introduction and merge result: Inspected the merge-base-to-head introduced diff. The test merge's raw parents are the pinned base followed by the exact head, and its base-relative result contains only the eight introduced paths.
Current main still needs this work: Current main retains runCacheWriteTransaction, which invokes synchronous native transactions and usage-cache kernels on the caller. The proposed worker dispatch is absent.
Live admission and cleanup custody: Inputs are cloned before queueing; the existing execution binding validates source authority and physical identity at admission. Cleanup captures the admitted file identity and deletes only the exact lock value, without replaying a data write after an uncertain result.
Findings None None.
Security None None.

How this fits together

Usage 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]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +150, Tests +153. Total +303 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 4 234 84 +150
Tests 4 176 23 +153
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 410 107 +303

Review metrics

Metric Value Why it matters
Worker operation surface 4 internal operations added; 0 public API or configuration additions The added dispatch extends the existing database owner without introducing another user-facing contract.

Technical review

Best 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.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded runtime responsiveness improvement without evidence of an urgent user-facing outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Repository State identifies a MEMBER author, exempting ordinary contributor proof. The captured body reports native worker/SQLite execution through the production refresh owner, including queued revocation, lost replies, rollback, and cleanup; inspected source supports those boundaries, with no unresolved authority violation or stored-format change.

Evidence

What I checked:

  • Pinned introduction and merge result: Inspected the merge-base-to-head introduced diff. The test merge's raw parents are the pinned base followed by the exact head, and its base-relative result contains only the eight introduced paths. (8348d0350731)
  • Current main still needs this work: Current main retains runCacheWriteTransaction, which invokes synchronous native transactions and usage-cache kernels on the caller. The proposed worker dispatch is absent. (src/infra/session-cost-usage-cache.sqlite.ts:43, a272cf0cd56e)
  • Live admission and cleanup custody: Inputs are cloned before queueing; the existing execution binding validates source authority and physical identity at admission. Cleanup captures the admitted file identity and deletes only the exact lock value, without replaying a data write after an uncertain result. (src/infra/session-cost-usage-cache.sqlite.ts:102, 496767dbf0ed)
  • Existing kernels and storage contracts retained: Four internal worker operations reuse the unchanged SQL kernels and request commit admission inside the transaction. The introduced diff changes no schema, stored encoding, retention, configuration, or public SDK contract. (src/state/openclaw-agent-execution-operations.ts:275, 496767dbf0ed)
  • Production-boundary coverage: The refresh regression uses the production refresh entry point and observes zero caller-thread cache SQL. Native worker/database cases cover revoked queued authority with no persisted rollup, delayed and lost acquisition replies, foreign-file refusal, rollback, and exact-lock cleanup. The captured body reports 47 passing tests and the intended baseline failure; this read-only review did not rerun them. (src/infra/session-cost-usage-cache.worker.test.ts:215, 496767dbf0ed)
  • Previous approval item resolved: The previous completed review had no findings and requested campaign coordinator approval. The captured body now explicitly records coordinator approval for this exact head. Internal scheduling and admission changes preserve existing contracts, so no additional product or storage-design approval is required by this review. (496767dbf0ed)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • obviyus: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-02T05:35:29.786Z sha 496767d :: needs changes before merge. :: none

@steipete
steipete merged commit 4a66195 into main Oct 2, 2026
136 of 137 checks passed
@steipete
steipete deleted the dbasync/usagecache branch October 2, 2026 07:47
@steipete

steipete commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant