Skip to content

♻️ refactor(message): prefer dedicated usage column over metadata.usage#15457

Merged
arvinxx merged 2 commits into
canaryfrom
feat/message-usage-field
Jun 4, 2026
Merged

♻️ refactor(message): prefer dedicated usage column over metadata.usage#15457
arvinxx merged 2 commits into
canaryfrom
feat/message-usage-field

Conversation

@arvinxx

@arvinxx arvinxx commented Jun 4, 2026

Copy link
Copy Markdown
Member

💻 Change Type

  • ♻️ refactor
  • ✅ test

🔗 Related Issue

🔀 Description of Change

Token usage was previously promoted out of metadata.usage into a dedicated messages.usage jsonb column — but nothing populated that column, and every read still went through metadata.usage. This PR wires up the dual-write / preferred-read so the column becomes the source of truth while staying backward-compatible.

Write side — centralized in the DB model so all executor callers (Gateway, hetero-agent, client) are covered without touching them:

  • update() / updateMetadata() / buildMessageInsertValue() promote token usage into the usage column, preferring a top-level usage payload and falling back to metadata.usage.
  • metadata.usage stays dual-written during the transition for backward-compatible reads.
  • The topic-usage rollup recompute now gates on the resolved usage value.

Read side — prefer the usage column, fall back to metadata.usage for legacy rows:

  • queryByIds / queryWithWhere select the column and expose it as UIChatMessage.usage.
  • getTokenHeatmaps and recomputeTopicUsage use COALESCE(usage, metadata->'usage') in SQL.
  • UsageRecordService.findByDateRange and context-engine tokenAccounting prefer the top-level usage.

Types:

  • Add top-level usage to UpdateMessageParams and DBMessageItem.
  • Mark metadata.usage and the legacy flat token fields (totalTokens, cost, inputXxxTokens, …) as @deprecated, pointing to the top-level usage field. Performance fields are untouched.

Note: metadata.usage is intentionally still written and still listed in the zod schema, so it's not yet removable — a follow-up can do the full cut-over (stop writing metadata.usage, drop the read fallbacks, backfill legacy rows).

🧪 How to Test

  • Tested locally
  • Added/updated tests
  • No tests needed

Added/extended tests asserting the column wins over metadata.usage (and legacy rows fall back) across: message create / query / update / stats(heatmap), topic usage rollup, usage record service, and token accounting. Full repo type-check passes; all touched suites green.

📸 Screenshots / Videos

No UI changes.

📝 Additional Information

Backward-compatible and additive — no migration required (the usage column already exists on trunk). Dual-write means rollback-safe.

Token usage was promoted out of metadata.usage into a dedicated messages.usage
column, but nothing populated it and all reads still went through metadata.usage.

- Centralize write-side promotion in the DB model (update / updateMetadata /
  create), so all executor callers populate the usage column from a top-level
  usage payload, falling back to metadata.usage. metadata.usage stays dual-written
  for backward-compatible reads.
- Reads prefer the usage column and fall back to metadata.usage: message queries,
  getTokenHeatmaps, recomputeTopicUsage, the usage record service, and context
  token accounting.
- Add top-level usage to UpdateMessageParams + DBMessageItem types.
- Mark metadata.usage and the legacy flat token fields as @deprecated, pointing
  to the top-level usage field.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@vercel

vercel Bot commented Jun 4, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lobehub Ready Ready Preview, Comment Jun 4, 2026 5:56am

Request Review

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 4, 2026

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We've reviewed this pull request using the Sourcery rules engine

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: edb9f7ddbf

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +2023 to +2026
.set({
...message,
...(mergedMetadata && { metadata: mergedMetadata }),
...(usageToWrite && { usage: usageToWrite }),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve metadata.usage for top-level usage updates

When callers use the newly added top-level usage parameter without also sending metadata.usage, this update writes only messages.usage; metadata.usage is left absent or stale because mergedMetadata is only built from the metadata payload. During the stated dual-write transition, older readers/rollback paths that still consume metadata.usage will miss the recorded usage for those messages, so the update path should also merge usageToWrite into metadata when it is present.

Useful? React with 👍 / 👎.

@codecov

codecov Bot commented Jun 4, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.05882% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 70.85%. Comparing base (e8b914f) to head (6e45ca5).
⚠️ Report is 1 commits behind head on canary.

Additional details and impacted files
@@            Coverage Diff            @@
##           canary   #15457     +/-   ##
=========================================
  Coverage   70.84%   70.85%             
=========================================
  Files        3253     3253             
  Lines      320623   320645     +22     
  Branches    34937    28350   -6587     
=========================================
+ Hits       227160   227177     +17     
- Misses      93282    93287      +5     
  Partials      181      181             
Flag Coverage Δ
app 61.50% <100.00%> (-0.01%) ⬇️
database 92.50% <100.00%> (+<0.01%) ⬆️
packages/agent-manager-runtime 49.69% <ø> (ø)
packages/agent-runtime 80.48% <ø> (ø)
packages/builtin-tool-lobe-agent 18.52% <ø> (ø)
packages/context-engine 84.17% <100.00%> (+<0.01%) ⬆️
packages/conversation-flow 91.29% <ø> (ø)
packages/device-gateway-client 89.68% <ø> (ø)
packages/eval-dataset-parser 95.15% <ø> (ø)
packages/eval-rubric 76.11% <ø> (ø)
packages/fetch-sse 85.57% <ø> (ø)
packages/file-loaders 87.89% <ø> (ø)
packages/memory-user-memory 74.99% <ø> (ø)
packages/model-bank 99.99% <ø> (ø)
packages/model-runtime 84.51% <ø> (ø)
packages/prompts 72.51% <ø> (ø)
packages/python-interpreter 92.90% <ø> (ø)
packages/ssrf-safe-fetch 0.00% <ø> (ø)
packages/types 35.34% <0.00%> (-0.02%) ⬇️
packages/utils 88.77% <ø> (ø)
packages/web-crawler 88.08% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Components Coverage Δ
Store 68.48% <ø> (ø)
Services 54.57% <ø> (ø)
Server 71.84% <100.00%> (-0.01%) ⬇️
Libs 57.01% <ø> (ø)
Utils 81.44% <ø> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

When a caller passed the new top-level `usage` param without also sending
`metadata.usage`, the update wrote only `messages.usage` and left
`metadata.usage` stale/absent — legacy readers and rollback paths still consume
it during the dual-write transition. Fold the resolved usage into the metadata
patch so `metadata.usage` stays in sync regardless of how usage was passed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@arvinxx arvinxx merged commit 475f391 into canary Jun 4, 2026
34 of 35 checks passed
@arvinxx arvinxx deleted the feat/message-usage-field branch June 4, 2026 06:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant