Skip to content

refactor: keep usage pricing SQLite reads off the Gateway thread - #148709

Merged
steipete merged 6 commits into
mainfrom
codex/usage-pricing-publication-main
Sep 15, 2026
Merged

steipete merged 6 commits into
mainfrom
codex/usage-pricing-publication-main

Conversation

@steipete

@steipete steipete commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Related: #144592
Builds on the metadata preparation merged in #148305.

What Problem This Solves

Cold usage reports, session logs, and usage charts can block the Gateway thread while loading SQLite-backed metadata and remote prices for cost estimation.

User Impact

Usage pricing prepares its database inputs asynchronously while preserving recorded costs, configured prices, scoped metadata, and startup catalog selection. No configuration changes or data migration are required.

Why This Change Was Made

Usage fingerprints await the existing metadata and shared-state worker owners. Logs and charts prepare pricing only when a record needs an estimate; billed-only reads and disabled remote catalogs retain their existing laziness. Per-record calculation keeps using the cached synchronous resolver.

The metadata resolver preserves current, workspace-scoped, and explicitly fresh selections. Remote preparation preserves the first published startup catalog and optional read/parse fallback. Original-owner checks and typed cancellation prevent retired or invalidated reads from publishing fallback absence into the existing startup or pricing caches. Log decoding remains best-effort, while failed asynchronous pricing preparation rejects the log request instead of silently omitting a valid record.

Evidence

  • Six compiled synthetic comparisons using JSONL diagnostic inputs on the qualified pricing source preserved costs, chart order/cumulative values, and fingerprints. Cold logs and charts went from 65 to zero parent-thread SQLite calls on Node and from 60 to zero on Bun, including cleanup. Billed-only reads stayed at zero; later estimation went from 41 to zero after a recorded catalog update.

  • All seven native SQLite methods were counted without throwing. Explicit fixture writes and their cleanup remain separately counted. Bun's five runtime-validation calls precede the counters; no fixture access is exempted.

  • 140 affected-owner tests and the complete changed-file gate passed before the additive main composition. Controlled JavaScript cancellation regressions failed before repair and passed afterward. The composition preserves the backup-record worker commands; 43 focused backup/metadata tests, core types, scoped lint, import-cycle checks, and fresh independent review passed. One existing Windows-only test was skipped on macOS.

  • Both the qualified pricing source (70c8cddc63b6) and runtime composition (f59f310a8eb6) passed normal builds and isolated CLI checks. Runtime-artifact Node/Bun cold-log controls also passed with all seven parent SQLite counters at zero across 16 windows, including series reads, repeats, and cleanup. The six-case comparisons remain attributed to 70c8cddc63b6.

  • CI preflight exposed duplicate scheduling when an infra test also belonged to the canonical database-worker list. The planner now defers to that owner once; the identical hybrid planner call passes locally, all 76 planner tests pass, and filesystem coverage plus the separate uniqueness assertion remain intact. This follow-up changes no pricing runtime source.

  • The actual log-entrypoint cancellation regression failed on 60b2cbebbf3a and passed after narrowing the malformed-record catch. Both database-admission and plugin-cache retirement reject the request; fresh reads preserve malformed-record skips, billed-zero costs, and estimates. Twenty-five focused log/reporting/stream tests, the full changed-file gate, and independent review passed for this caller repair. Earlier compiled evidence remains pinned to its named runtime commits.

  • A subsequent CI run encountered the memory-wiki fixture cleanup failure family addressed by merged fix(tests): drain shared database workers before fixture cleanup #148734. This branch now includes that canonical awaited cleanup, with both landed fixture files preserved exactly; 14 selected ordinary Wiki, Teams, pricing and maintenance cases, static checks and fresh review passed on the combined source. The exact inode/generation cause is not claimed, and admission checks remain unchanged.

  • CI also reported an invalid-config reply in the existing runtime-inspection fixture. Its snapshot matched the written fixture, but the original exception was unavailable. This branch now inherits the exact diagnostic merged in chore(plugins): expose hidden CI inspection errors #148736, which records the existing config-read phase and allowlisted error identity only on failure. The redundant branch-local observer was removed. Production behavior and assertions remain unchanged; the cause is unproven pending new-head CI. Static checks and independent review cover the composition; no held scenario was replayed.

Timings were mixed and do not establish a general speedup. These counts cover the named pricing reads; other SQLite transcript, usage-cache and catalog-write owners remain tracked separately in the campaign.

@clawsweeper

clawsweeper Bot commented Sep 15, 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.

@steipete
steipete marked this pull request as ready for review September 15, 2026 02:42
@openclaw-barnacle openclaw-barnacle Bot added size: L maintainer Maintainer-authored PR labels Sep 15, 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 Sep 15, 2026
@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 15, 2026, 1:24 AM ET / 05:24 UTC (Revision 6).

ClawSweeper review

What this changes

Moves usage-pricing metadata and catalog reads into existing SQLite workers while preserving cost calculations, propagating cancellation, and scheduling database-owned tests once.

Merge readiness

✅ Ready for maintainer review

This remains useful, maintainer-sponsored work that current main does not implement. The earlier cancellation defect is fixed, GitHub now reports the branch mergeable, and no new blocking defect was found.

Priority: P2
Reviewed head: 6180041e43f2c85a645ad1714878867a34fb21c4

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch reuses existing owners, preserves pricing semantics, and addresses the prior defect with meaningful regression coverage.
Proof confidence 🌊 off-meta tidepool Not applicable: The external-contributor gate does not apply to this MEMBER-authored PR. Its body records Node/Bun production pricing-entrypoint measurements and cancellation results at named revisions; no new authority boundary requires additional final-effect proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The external-contributor gate does not apply to this MEMBER-authored PR. Its body records Node/Bun production pricing-entrypoint measurements and cancellation results at named revisions; no new authority boundary requires additional final-effect proof.
Evidence reviewed 10 items Current main still needs the change: Fetched main builds cold pricing contexts through synchronous metadata resolution and remote catalog access; it has no prepareModelPricingContext implementation.
Latest release comparison: The supplied latest release, v2026.9.4, also uses synchronous cold pricing preparation. No shipped replacement was established.
Existing owners and publication semantics: Pricing preparation retains its plugin-cache owner, rejects invalidated facts, checks retirement before publication, and preserves an already-published context. Remote preparation uses the existing shared-state worker and retains first-publication catalog selection.
Findings None None.
Security None None.

How this fits together

Usage reporting combines session records with configured and catalog prices to produce costs, logs, and charts. This change prepares pricing metadata through the shared database worker before synchronous calculations consume it.

flowchart TD
  A[Usage report request] --> B[Session records]
  B --> C{Estimate needed?}
  C -->|No| F[Preserve recorded cost]
  C -->|Yes| D[Prepare pricing metadata]
  D --> E[Shared SQLite worker]
  E --> G[Cached pricing calculation]
  F --> H[Costs logs and charts]
  G --> H
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +331, Tests +296, Other +6. Total +633 across 21 files.

View PR surface stats
Area Files Added Removed Net
Source 14 448 117 +331
Tests 6 304 8 +296
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 7 1 +6
Total 21 759 126 +633

Review metrics

Metric Value Why it matters
Production versus regression coverage Production net +331 lines; tests/support net +296; tooling net +6 Production growth implements asynchronous preparation and cancellation handling within existing owners, with regression coverage for publication and selection semantics.

Root-cause cluster

Relationship: partial_overlap
Canonical: #144592
Summary: This PR implements the usage-pricing portion of the broader asynchronous-storage campaign.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Keep pricing calculations synchronous over prepared facts, with SQLite reads and cancellation owned by the existing cache and database lifecycles.

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

Yes, at source level: cold usage pricing on main reaches synchronous metadata and catalog reads. The reported Node/Bun measurements support that mechanism; this review did not execute it.

Is this the best way to solve the issue?

Yes. The patch prepares existing owners before calculation, preserves pricing precedence and stored formats, and fixes cancellation at the actual log entrypoint without adding configuration or a competing store.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This is a bounded Gateway responsiveness improvement for cold usage-pricing reads, without evidence of an urgent user-facing outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The external-contributor gate does not apply to this MEMBER-authored PR. Its body records Node/Bun production pricing-entrypoint measurements and cancellation results at named revisions; no new authority boundary requires additional final-effect proof.

Evidence

What I checked:

  • Current main still needs the change: Fetched main builds cold pricing contexts through synchronous metadata resolution and remote catalog access; it has no prepareModelPricingContext implementation. (src/model-catalog/pricing.ts:64, d47f299c681a)
  • Latest release comparison: The supplied latest release, v2026.9.4, also uses synchronous cold pricing preparation. No shipped replacement was established. (src/model-catalog/pricing.ts:64, 3a9d69db306c)
  • Existing owners and publication semantics: Pricing preparation retains its plugin-cache owner, rejects invalidated facts, checks retirement before publication, and preserves an already-published context. Remote preparation uses the existing shared-state worker and retains first-publication catalog selection. (src/model-catalog/pricing.ts:153, 6180041e43f2)
  • Previous cancellation finding resolved: The asynchronous pricing call is outside the malformed-record catch. The added log-entrypoint regression covers database-admission invalidation and plugin-cache retirement, followed by successful fresh reads preserving billed-zero and estimated costs. (src/infra/session-cost-usage-reporting.ts:377, 6180041e43f2)
  • Re-review continuity: The inspected pricing, metadata, cache, worker, and cancellation-regression files are unchanged from the previous reviewed head. Its empty findings remain consistent with this review. (6180041e43f2)
  • Current integration state: The REST response confirms the pinned head remains open and unmerged, with mergeable=true and mergeable_state=blocked. The previous conflict warning is no longer current. The supplied stale test merge is not evidence of the final merged tree. (6180041e43f2)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Fabio Ribeiro: 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 (5 earlier review cycles)
  • reviewed 2026-09-15T02:49:43.019Z sha f59f310 :: needs changes before merge. :: [P2] Propagate pricing cancellation outside the malformed-record catch
  • reviewed 2026-09-15T03:11:05.754Z sha 60b2cbe :: needs changes before merge. :: [P2] Propagate pricing cancellation outside the malformed-record catch
  • reviewed 2026-09-15T03:47:36.331Z sha 6968733 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-15T04:29:08.104Z sha 30406a9 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-15T05:07:58.527Z sha 503e834 :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added 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. and removed 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 Sep 15, 2026
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Sep 15, 2026
@steipete
steipete merged commit a4c8466 into main Sep 15, 2026
196 checks passed
@steipete
steipete deleted the codex/usage-pricing-publication-main branch September 15, 2026 06:03
@steipete

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

maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts 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