Skip to content

refactor(usage): add precise token buckets for Usage Mosaic - #74337

Merged
hxy91819 merged 1 commit into
openclaw:mainfrom
konanok:refactor/usage-token-mosaic-buckets
Apr 30, 2026
Merged

hxy91819 merged 1 commit into
openclaw:mainfrom
konanok:refactor/usage-token-mosaic-buckets

Conversation

@konanok

@konanok konanok commented Apr 29, 2026

Copy link
Copy Markdown
Contributor

Summary

Describe the problem and fix in 2–5 bullets:

  • Problem: Usage Mosaic currently spreads session-level totalTokens across every hour touched by the session duration, so long or cross-hour sessions can make hourly token distribution look flatter than the actual model usage timeline.
  • Why it matters: Peak Error Hours already moved to precise UTC quarter-hour buckets in fix(ui): use precise hourly message counts for Peak Error Hours #49396, and maintainers identified token mosaic as the same follow-up area; token mosaic should follow the same data-modeling pattern so the hourly heatmap and hour filter are based on actual usage timestamps when available.
  • What changed: add per-session utcQuarterHourTokenUsage buckets, aggregate them from transcript usage entries, and make Usage Mosaic/hour filtering prefer these buckets before falling back to the legacy session-span behavior.
  • What did NOT change (scope boundary): this does not rewrite dailyBreakdown, daily chart timezone semantics, provider/channel aggregates, or introduce a global UsageTimeBucket model.
  • AI-assisted: yes; implementation, tests, and local verification were prepared with an AI coding assistant and manually reviewed.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

Root Cause (if applicable)

For bug fixes or regressions, explain why this happened, not just what changed. Otherwise write N/A. If the cause is unclear, write Unknown.

  • Root cause: N/A — this is a focused follow-up refactor to give token mosaic the same precise bucket-based data source that fix(ui): use precise hourly message counts for Peak Error Hours #49396 introduced for peak error hours.
  • Missing detection / guardrail: existing tests covered message/error quarter-hour buckets but did not cover token mosaic distribution or hour filtering from token buckets.
  • Contributing context (if known): token mosaic previously only had session-level total token usage, so the UI estimated hourly token distribution by spreading tokens across the session time span.

Regression Test Plan (if applicable)

For bug fixes or regressions, name the smallest reliable test coverage that should catch this. Otherwise write N/A.

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file:
    • src/infra/session-cost-usage.test.ts
    • ui/src/ui/views/usage-metrics.test.ts
  • Scenario the test should lock in:
    • backend aggregates multiple usage entries into UTC quarter-hour token buckets without proportional allocation;
    • Usage Mosaic places token totals in the bucket hour instead of spreading the session total across the whole session span;
    • hour filtering uses precise token buckets when present;
    • old summaries without valid token buckets keep the legacy session-span fallback.
  • Why this is the smallest reliable guardrail: the behavior is fully determined by session summary aggregation and pure UI helper functions, so unit tests cover the data contract and rendering inputs without needing a browser e2e flow.
  • Existing test that already covers this (if any): buildPeakErrorHours tests cover message/error bucket mapping, but not token buckets.
  • If no new test is added, why not: N/A — new tests were added.

User-visible / Behavior Changes

Usage Mosaic now uses precise per-turn token timestamps when the new utcQuarterHourTokenUsage data is available. The visible heatmap should better reflect when token usage actually happened.

Clicking an hour remains a session-level filter: it selects sessions that have token usage in that hour, then displays those sessions' total usage. It does not yet change page totals to hour-bucket-only totals.

Older summaries without the new token bucket field remain backward compatible through the legacy session-span fallback.

Diagram (if applicable)

Before:
JSONL usage entries
  -> SessionCostSummary(totalTokens, firstActivity, lastActivity)
  -> Usage Mosaic spreads totalTokens across the whole session span
  -> hour filter checks whether the session span touches the selected hour

After:
JSONL usage entries
  -> SessionCostSummary(utcQuarterHourTokenUsage)
  -> Usage Mosaic maps UTC quarter-hour buckets to local/UTC display hours
  -> hour filter checks whether token buckets touch the selected hour
  -> legacy summaries fall back to the old session-span path

Security Impact (required)

  • New permissions/capabilities? (Yes/No): No
  • Secrets/tokens handling changed? (Yes/No): No
  • New/changed network calls? (Yes/No): No
  • Command/tool execution surface changed? (Yes/No): No
  • Data access scope changed? (Yes/No): No
  • If any Yes, explain risk + mitigation: N/A

Repro + Verification

Environment

  • OS: macOS / Darwin
  • Runtime/container: local Node/pnpm workspace
  • Model/provider: N/A
  • Integration/channel (if any): Control UI / Usage Metrics
  • Relevant config (redacted): N/A

Steps

  1. Open Control UI Usage Metrics for sessions with assistant usage entries spanning multiple hours.
  2. Compare a session where token usage occurs in one UTC quarter-hour but the session span crosses later hours.
  3. Inspect Usage Mosaic hour totals and click the involved hours.

Expected

  • Token mosaic hour totals use utcQuarterHourTokenUsage when available.
  • Tokens are attributed to the actual usage bucket hour, not spread across all hours touched by the session span.
  • Selecting an hour includes sessions with token buckets in that hour and excludes sessions with token buckets only in other hours.
  • Older summaries without valid token buckets still use the legacy session-span fallback.

Actual

  • Implemented as expected in unit tests and targeted local verification.

Evidence

Attach at least one:

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Relevant local verification:

node scripts/run-vitest.mjs run --config test/vitest/vitest.infra.config.ts src/infra/session-cost-usage.test.ts
# 21 passed

pnpm --dir ui test src/ui/views/usage-metrics.test.ts
# 16 passed

pnpm --dir ui build
# passed

pnpm build
# passed

pnpm check
# passed

pnpm check:changed
# passed

git diff --check origin/main...HEAD
# passed

Known unrelated full-suite result after rebasing onto origin/main@de0f54b54a:

pnpm test
# failed 74 Vitest shards in 605.09s
# failures are outside this PR's touched files, including:
# - src/plugins/contracts/plugin-sdk-index.bundle.test.ts
# - src/plugins/contracts/plugin-sdk-runtime-api-guardrails.test.ts
# - src/gateway/server-startup-config.recovery.test.ts
# - extensions/active-memory/index.test.ts
# - test/scripts/parallels-smoke-model.test.ts
# - extensions/github-copilot/provider-discovery.contract.test.ts
# - src/agents/auth-profiles.ensureauthprofilestore.test.ts
# - src/entry.respawn.test.ts

Codex local review:

codex review --base origin/main
# completed; findings reviewed
# addressed: token bucket total basis documentation, invalid bucket validation,
# UTC day-boundary coverage, local timezone mapping coverage,
# empty token-bucket contract coverage, and float-safe cost assertions

Human Verification (required)

What you personally verified (not just CI), and how:

  • Verified scenarios:
    • backend loadSessionCostSummary emits sorted utcQuarterHourTokenUsage entries;
    • multiple usage entries in the same UTC quarter-hour are accumulated;
    • token buckets split correctly across UTC day boundaries;
    • token mosaic uses precise token buckets instead of session-span proportional allocation;
    • hour filtering uses token buckets when available;
    • fallback keeps legacy session-span hour matching when token buckets are missing or invalid;
    • build, typecheck, lint, and changed-lane checks pass locally.
  • Edge cases checked:
    • same quarter-hour aggregation;
    • usage.total preferred over component sum for token bucket total;
    • invalid/zero token buckets do not block fallback;
    • invalid YYYY-MM-DD / quarterIndex values are ignored instead of being silently rolled over by Date.UTC;
    • local timezone bucket mapping path is covered;
    • old summaries without utcQuarterHourTokenUsage remain compatible.
  • What you did not verify:
    • manual browser screenshot/recording;
    • production data migration, because the new field is optional and computed from existing transcript data;
    • full pnpm test green, because latest origin/main currently has unrelated failures outside this PR's touched files. Full log: .artifacts/pnpm-test-after-rebase.log.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

If a bot review conversation is addressed by this PR, resolve that conversation yourself. Do not leave bot review conversation cleanup for maintainers.

Note: no GitHub bot review conversations exist yet for this PR at the time this content was prepared. A local Codex review was run before PR creation; actionable findings were addressed in the implementation.

Compatibility / Migration

  • Backward compatible? (Yes/No): Yes
  • Config/env changes? (Yes/No): No
  • Migration needed? (Yes/No): No
  • If yes, exact upgrade steps: N/A

Compatibility details:

  • utcQuarterHourTokenUsage is optional on SessionCostSummary.
  • UI falls back to the previous session-span path when the new field is absent or has no valid positive token buckets.
  • No persisted data migration is required; the bucket is derived while reading existing session JSONL transcripts.

Risks and Mitigations

  • Risk: Response payloads for sessions.usage become slightly larger because each session may include token quarter-hour buckets.
    • Mitigation: buckets are sparse and only emitted for quarter-hours that actually contain token usage.
  • Risk: users may interpret hour-filtered totals as hour-bucket-only totals.
    • Mitigation: this PR keeps the existing session-level filtering semantics; the PR description calls out that scope boundary explicitly.
  • Risk: malformed bucket data could map to an unexpected hour.
    • Mitigation: frontend validates date format, real UTC date, and quarterIndex range before using a bucket.

@greptile-apps

greptile-apps Bot commented Apr 29, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds utcQuarterHourTokenUsage buckets to SessionCostSummary, aggregated from per-entry timestamps while loading session JSONL files, and updates the Usage Mosaic and hour-filter logic to prefer these precise UTC quarter-hour buckets over the legacy session-span proportional allocation. Older summaries without the field fall back transparently to the existing session-span behavior. The refactor also extracts computeUsageTokenTotals and getUtcQuarterHourBucketKey helpers to deduplicate token-total logic, and moves the session-span filtering function from usage.ts into the usage-metrics.ts module alongside the new bucket-aware path.

Confidence Score: 5/5

This PR is safe to merge — no bugs, no security issues, and backward compatibility is preserved through the documented fallback path.

The implementation is well-structured: new type fields are optional, the bucket validation in getUtcQuarterHourBucketDate rejects malformed dates and out-of-range quarterIndex values, the fallback to session-span behavior is exercised by tests, and utcQuarterHourTokenUsage propagates correctly through the entire type chain from SessionCostSummary to the UI's UsageSessionEntry. All token-total basis differences between the new buckets and legacy dailyBreakdown are explicitly documented.

No files require special attention.

Reviews (1): Last reviewed commit: "refactor(usage): add precise token mosai..." | Re-trigger Greptile

@clawsweeper

clawsweeper Bot commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes:

This PR adds optional UTC quarter-hour token usage buckets to session cost summaries, aggregates them from transcript usage entries, updates Control UI Usage Mosaic/hour filtering to prefer those buckets with legacy fallback, and adds backend/UI tests plus a changelog entry.

Maintainer follow-up before merge:

This is an existing focused implementation PR with no discrete blocking bug found; the remaining work is maintainer review, conflict/rebase handling, and validation rather than a separate ClawSweeper repair job.

Security review:

Security review cleared: The diff touches usage aggregation, UI helpers, tests, and changelog only; it does not add dependencies, workflows, network calls, permissions, secret handling, install scripts, or command execution paths.

Review details

Best possible solution:

Land a reviewed version that keeps the token-bucket field optional, derives sparse UTC quarter-hour token buckets from existing transcript usage, validates bucket coordinates in the UI, preserves legacy span fallback for older summaries, and keeps the focused backend/UI coverage for aggregation, timezone mapping, invalid data, and fallback behavior.

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

Yes. On current main, a session with token usage in one quarter-hour but an activity span crossing another hour will still have Usage Mosaic tokens proportionally spread across the span and selected-hour filtering matched by first/last activity; the current files show that path directly.

Is this the best way to solve the issue?

Yes, with maintainer review. The proposed direction is the narrowest maintainable extension of the already-merged #49396 pattern: add an optional sparse bucket contract, consume it in the token mosaic/hour filter, and leave dailyBreakdown and broader UsageTimeBucket work out of scope.

Acceptance criteria:

  • node scripts/run-vitest.mjs run --config test/vitest/vitest.infra.config.ts src/infra/session-cost-usage.test.ts
  • pnpm --dir ui test src/ui/views/usage-metrics.test.ts
  • pnpm --dir ui build
  • pnpm check:changed in Testbox before merge

What I checked:

  • Current main type contract has message buckets only: SessionCostSummary exposes utcQuarterHourMessageCounts but no utcQuarterHourTokenUsage field on current main. (src/infra/session-cost-usage.types.ts:144, de1ac12f1c04)
  • Current main backend does not emit token buckets: loadSessionCostSummary builds utcQuarterHourMessageMap and returns utcQuarterHourMessageCounts, while token usage is still accumulated into totals and daily breakdowns only. (src/infra/session-cost-usage.ts:610, de1ac12f1c04)
  • Current main Usage Mosaic spreads tokens across the activity span: buildUsageMosaicStats calls forEachSessionHourSlice and adds usage.totalTokens multiplied by share to each hour and weekday. (ui/src/ui/views/usage-metrics.ts:159, de1ac12f1c04)
  • Current main hour filtering is still span-based: renderUsage defines sessionTouchesHours from firstActivity/lastActivity and filters selected hours through that helper instead of token usage buckets. (ui/src/ui/views/usage.ts:174, de1ac12f1c04)
  • Proposed diff adds the missing token-bucket path: The PR diff adds SessionUtcQuarterHourTokenUsage, fills utcQuarterHourTokenMap from usage entries, maps valid buckets in Usage Mosaic, switches selected-hour matching to buckets when present, and adds backend/UI tests for aggregation, day boundaries, invalid buckets, and fallback. (src/infra/session-cost-usage.ts:776, 6d949364b732)
  • Related merged work covers message counts, not token buckets: The current changelog records fix(ui): use precise hourly message counts for Peak Error Hours #49396 as a Peak Error Hours/message-count fix; the current search found no token-bucket implementation on main. (CHANGELOG.md:35, de1ac12f1c04)

Likely related people:

  • konanok: The current-main squash commit for fix(ui): use precise hourly message counts for Peak Error Hours #49396 introduced the UTC quarter-hour message-count pattern this PR extends to token usage, and its commit metadata credits konanok for that merged behavior beyond this PR proposal. (role: introduced related behavior / likely follow-up owner; confidence: high; commits: bd5afadc5c7a, fbbf43b84a25; files: src/infra/session-cost-usage.ts, src/infra/session-cost-usage.types.ts, ui/src/ui/views/usage-metrics.ts)
  • hxy91819: The fix(ui): use precise hourly message counts for Peak Error Hours #49396 squash metadata records Reviewed-by @hxy91819, and this PR's author explicitly tagged hxy91819 as the prior Usage Metrics token mosaic discussion contact; the live PR is also assigned to hxy91819. (role: reviewer / discussion context; confidence: medium; commits: bd5afadc5c7a, fbbf43b84a25; files: src/infra/session-cost-usage.ts, src/infra/session-cost-usage.types.ts, ui/src/ui/views/usage-metrics.ts)
  • steipete: GitHub path history shows repeated current-main maintenance and refactors around Usage UI helpers and session cost usage infrastructure, including the usage timeslice walker and session usage type extraction. (role: adjacent owner / recent maintainer; confidence: medium; commits: 8df6134a1b40, 68dbbc7c5ff1, c256503ea129; files: ui/src/ui/views/usage-metrics.ts, ui/src/ui/views/usage.ts, src/infra/session-cost-usage.ts)

Remaining risk / open question:

  • The live PR API reports mergeable_state dirty, so the branch needs rebase or conflict resolution before merge validation.
  • The patch changes the exported sessions.usage/SessionCostSummary payload shape; reviewers should explicitly accept the optional sparse bucket contract and payload-size tradeoff.
  • The PR intentionally keeps clicked-hour totals at session level while using token buckets only to decide whether a session touches an hour, so that UX semantic needs maintainer acceptance.
  • This read-only review did not rerun the PR's tests; final merge should re-run the targeted backend/UI checks and changed gate after any rebase.

Codex review notes: model gpt-5.5, reasoning high; reviewed against de1ac12f1c04.

@konanok

konanok commented Apr 29, 2026

Copy link
Copy Markdown
Contributor Author

@hxy91819 This is the follow-up PR for the Usage Metrics token mosaic issue we discussed after #49396.

Main changes:

  • added per-session UTC quarter-hour token usage buckets;
  • switched Usage Mosaic from session-span proportional allocation to precise token buckets when available;
  • updated hour filtering to use the same buckets, with the old session-span fallback preserved;
  • kept dailyBreakdown, daily chart timezone behavior, and broader UsageTimeBucket refactor out of scope;
  • added backend/UI coverage for bucket aggregation, UTC day boundaries, local timezone mapping, invalid buckets, and fallback behavior.

Targeted checks and local Codex review are done; actionable findings have been addressed.

@hxy91819 hxy91819 self-assigned this Apr 29, 2026
@clawsweeper

clawsweeper Bot commented Apr 29, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes:

This PR adds optional UTC quarter-hour token usage buckets to session cost summaries, aggregates them from transcript usage entries, updates Control UI Usage Mosaic/hour filtering to prefer those buckets with legacy fallback, and adds backend/UI tests plus a changelog entry.

Maintainer follow-up before merge:

The remaining action is normal maintainer PR review and validation of an existing implementation branch; there is no separate narrow repair task for ClawSweeper to queue.

Review details

Best possible solution:

Land a reviewed version that adds the optional token-bucket contract, derives sparse buckets from transcript usage, uses them in Usage Mosaic and hour selection with validated legacy fallback, and keeps focused backend/UI coverage for bucket aggregation, invalid data, timezone mapping, and fallback behavior.

Acceptance criteria:

  • node scripts/run-vitest.mjs run --config test/vitest/vitest.infra.config.ts src/infra/session-cost-usage.test.ts
  • pnpm --dir ui test src/ui/views/usage-metrics.test.ts
  • pnpm --dir ui build
  • pnpm check:changed in Testbox before merge

What I checked:

Likely related people:

  • konanok: The merged related PR fix(ui): use precise hourly message counts for Peak Error Hours #49396 introduced the current UTC quarter-hour message-count pattern that this PR extends to token usage, and the current changelog credits that shipped behavior to konanok; this is not based solely on authorship of this PR. (role: introduced related behavior / likely follow-up owner; confidence: high; commits: fbbf43b84a25; files: src/infra/session-cost-usage.ts, src/infra/session-cost-usage.types.ts, ui/src/ui/views/usage-metrics.ts)
  • hxy91819: The PR author explicitly tagged hxy91819 as part of the follow-up Usage Metrics token mosaic discussion after fix(ui): use precise hourly message counts for Peak Error Hours #49396; local current-main history did not tie this handle to the central files, so this is a routing clue rather than code ownership proof. (role: discussion context / likely maintainer reviewer; confidence: low; files: src/infra/session-cost-usage.ts, src/infra/session-cost-usage.types.ts, ui/src/ui/views/usage-metrics.ts)

Remaining risk / open question:

  • The PR changes the exported sessions.usage/SessionCostSummary payload shape, so reviewers should confirm the optional field contract, payload size, and backward compatibility before merge.
  • The PR intentionally keeps hour-click totals session-level while using token buckets only to decide whether a session touches an hour; that UX semantic should be explicitly accepted.
  • The PR body reports unrelated full-suite failures on its rebased branch, so targeted usage tests plus the changed gate should be rechecked on the final merge candidate.

Codex review notes: model gpt-5.5, reasoning high; reviewed against 1390eadd9289.

@hxy91819
hxy91819 force-pushed the refactor/usage-token-mosaic-buckets branch from 6d94936 to 1518535 Compare April 30, 2026 15:31
@hxy91819
hxy91819 merged commit 0eb8f34 into openclaw:main Apr 30, 2026
72 of 73 checks passed
@hxy91819

Copy link
Copy Markdown
Member

Merged via squash.

Thanks @konanok!

@clawsweeper clawsweeper Bot mentioned this pull request Apr 30, 2026
2 tasks done
lxe pushed a commit to lxe/openclaw that referenced this pull request May 6, 2026
…#74337)

Merged via squash.

Prepared head SHA: 1518535
Co-authored-by: konanok <[email protected]>
Co-authored-by: hxy91819 <[email protected]>
Reviewed-by: @hxy91819
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
…#74337)

Merged via squash.

Prepared head SHA: 1518535
Co-authored-by: konanok <[email protected]>
Co-authored-by: hxy91819 <[email protected]>
Reviewed-by: @hxy91819
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
…#74337)

Merged via squash.

Prepared head SHA: 1518535
Co-authored-by: konanok <[email protected]>
Co-authored-by: hxy91819 <[email protected]>
Reviewed-by: @hxy91819
sablehead pushed a commit to sablehead/openclaw that referenced this pull request Jun 10, 2026
…#74337)

Merged via squash.

Prepared head SHA: 1518535
Co-authored-by: konanok <[email protected]>
Co-authored-by: hxy91819 <[email protected]>
Reviewed-by: @hxy91819
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants