Skip to content

fix(ui): use precise hourly message counts for Peak Error Hours - #49396

Merged
hxy91819 merged 3 commits into
openclaw:mainfrom
konanok:fix/peak-error-hours-inaccurate-rates
Apr 29, 2026
Merged

hxy91819 merged 3 commits into
openclaw:mainfrom
konanok:fix/peak-error-hours-inaccurate-rates

Conversation

@konanok

@konanok konanok commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: The "Peak Error Hours" widget in the Usage Metrics view shows identical error rates for every hour (e.g. 9.89% across all hours), making it useless for identifying when errors actually concentrate.
  • Why it matters: Users rely on this widget to diagnose problematic time windows; uniform rates provide zero insight and can delay incident response.
  • What changed: Added UTC quarter-hour message counting in the backend (session-cost-usage.ts) and precise hour-level aggregation with proper timezone conversion in the frontend (usage-metrics.ts). The legacy proportional-allocation algorithm is preserved as a fallback for sessions without granular data.
  • What did NOT change (scope boundary): Session file format, cache structure, RPC protocol, gateway startup flow, or any other Usage Metrics widget. No migration is required — existing .jsonl session files are re-scanned on each load.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor
  • 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

  • Closes #
  • Related #

User-visible / Behavior Changes

  • Peak Error Hours now displays distinct, accurate error rates per hour instead of a single uniform rate across all hours.
  • Both Local and UTC timezone views render correct hour labels and rates.
  • Sessions scanned before this change will automatically show precise rates on next load (no migration needed).

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No

Repro + Verification

Environment

  • OS: macOS (Darwin)
  • Runtime/container: Node 24.12.0
  • Model/provider: N/A (UI-only change)
  • Integration/channel (if any): N/A
  • Relevant config (redacted): default ~/.openclaw/openclaw.json

Steps

  1. Run the gateway: openclaw gateway run --allow-unconfigured
  2. Open Control UI → Usage tab → scroll to Peak Error Hours widget.
  3. Toggle between Local and UTC time views.

Expected

  • Each hour shows a different error rate reflecting actual message/error distribution.
  • UTC and Local views show correctly offset hours.

Actual (before fix)

  • Every hour displayed the same error rate (e.g. 9.89%), which equals the session-wide average.
before

After fix

Local timezone

after

UTC timezone

after_2

Evidence

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

Tests added (20 total, all pass):

Backend (src/infra/session-cost-usage.test.ts — 11 tests):

  • Validates UTC quarter-hour bucket index calculation (e.g. 00:14Z → index 0, 00:15Z → index 1, 06:30Z → index 26, 23:59Z → index 95)
  • Verifies per-role counting (user, assistant, tool, toolResult, errors)
  • Confirms integration with the existing loadSessionCostSummary pipeline

Frontend (ui/src/ui/views/usage-metrics.test.ts — 9 tests):

  • Empty sessions → empty result
  • Sessions without hourlyMessageCounts → falls back to legacy proportional algorithm
  • Precise aggregation produces distinct per-hour rates
  • UTC mode maps quarter-hour buckets to correct UTC hours
  • Local mode applies timezone offset correctly
  • Top-5 limit and descending sort by error rate
  • Hours with zero messages are excluded
  • Multi-session aggregation across different hours
  • Cross-timezone boundary wrapping (negative offsets wrap to 0-23)

Human Verification (required)

  • Verified scenarios: Started the full gateway (openclaw gateway run), opened Control UI, navigated to Usage → Peak Error Hours. Confirmed that different hours now show different error rates. Toggled Local / UTC and verified hour labels shift correctly.
  • Edge cases checked: Sessions with no messages (skipped), sessions with only one hour of activity (single entry displayed), timezone offset causing hour wrap-around past midnight.
  • What I did not verify: Behavior with sessions spanning multiple days in the same widget view; behavior on Windows (only verified on macOS).

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.

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No — loadSessionCostSummary re-scans raw .jsonl transcript files on every call (not cached), so all existing sessions produce precise hourly data immediately.

Failure Recovery (if this breaks)

  • How to disable/revert this change quickly: Revert this commit. The frontend fallback path (legacy proportional algorithm) activates automatically when hourlyMessageCounts is absent or empty, so reverting the backend change alone is also safe.
  • Files/config to restore: None — no config or data format changes.
  • Known bad symptoms reviewers should watch for: All hours showing the same error rate again (regression to old behavior); hours appearing in the wrong position when switching Local/UTC.

Risks and Mitigations

  • Risk: Quarter-hour bucket granularity (96 buckets) increases the size of SessionCostSummary objects in memory.
    • Mitigation: Buckets are sparse (only hours with actual messages are stored), and typical sessions span a small number of distinct quarter-hours. Memory impact is negligible.
  • Risk: new Date().getTimezoneOffset() is called once per buildPeakErrorHours invocation; DST transitions mid-session could shift some hours by ±1.
    • Mitigation: The offset is precomputed per call (consistent within a single render). DST edge cases affect at most 1 hour boundary, which is acceptable for a diagnostic widget.

@greptile-apps

greptile-apps Bot commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes the Peak Error Hours widget which previously showed an identical error rate (the session-wide average) for every hour. The backend (session-cost-usage.ts) now accumulates UTC quarter-hour bucket counts (quarterIndex 0–95) during session parsing, and the frontend (usage-metrics.ts) converts those buckets to the correct local or UTC hour slot using getTimezoneOffset(), falling back to the legacy proportional-allocation algorithm when the precise data is absent. The previously flagged timezone-handling bug (UTC mode silently showing local-hour data) is correctly resolved in the current commit: UTC mode reads Math.floor(quarterIndex * 15 / 60) directly, while local mode shifts by localOffsetMin. The type chain from SessionCostSummary → SessionUsageEntry → UsageSessionEntry is correct, and the 20 new tests cover UTC mapping, local-timezone conversion, non-integer offsets, day-boundary wrapping, multi-session aggregation, top-5 limiting, and the fallback path.

Confidence Score: 5/5

Safe to merge — the timezone math is correct, the fallback path is preserved and tested, and no pre-existing behavior is regressed.

All findings are P2 or lower. The core fix is sound: UTC quarter-hour indices are computed with getUTCHours()/getUTCMinutes() on the backend and converted correctly to local or UTC hour buckets on the frontend. The previously flagged timezone bug is verifiably resolved in the current commit. Tests cover the important edge cases.

No files require special attention.

Reviews (2): Last reviewed commit: "fix: use precise hourly message counts f..." | Re-trigger Greptile

Comment thread ui/src/ui/views/usage-metrics.ts Resolved
@konanok konanok changed the title fix: use precise hourly message counts for Peak Error Hours fix(ui): use precise hourly message counts for Peak Error Hours Mar 18, 2026
@konanok
konanok force-pushed the fix/peak-error-hours-inaccurate-rates branch from e216c6d to 12df2fe Compare March 18, 2026 10:14
@konanok
konanok force-pushed the fix/peak-error-hours-inaccurate-rates branch from 12df2fe to c64700f Compare April 14, 2026 13:30
@konanok

konanok commented Apr 17, 2026

Copy link
Copy Markdown
Contributor Author

@hxy91819 Just a gentle bump — would appreciate any directional feedback on this when you have a moment. Happy to adjust the approach.

@hxy91819

Copy link
Copy Markdown
Member

@greptile-apps review

@hxy91819

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c64700f121

ℹ️ 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 thread ui/src/ui/views/usage-metrics.ts Resolved
@hxy91819

Copy link
Copy Markdown
Member

Nice catch on the proportional-allocation math — that's a subtle one and the 96-bucket quarter-hour UTC encoding is the right shape for a widget that has both Local and UTC toggles.

Two small things before merge:

  1. SessionHourlyMessageCounts.date is commented as UTC but is currently set via formatDayKey, which uses the gateway's local timezone. Harmless today (the UI only reads quarterIndex), but the comment will mislead future consumers — either switch date to a UTC day key or relax the comment to match dailyMessageCounts.date.
  2. Please add a ## Unreleased → ### Fixes entry in CHANGELOG.md; other recent fix PRs follow the ... (#<PR>). Thanks @<author>. pattern.

Optional: the quarter-hour aggregation block in loadSessionCostSummary duplicates the daily aggregation logic just above it — worth extracting a small accumulateMessageCounts(counts, entry) helper to keep the two from drifting.

@konanok
konanok force-pushed the fix/peak-error-hours-inaccurate-rates branch from c64700f to 39f4076 Compare April 28, 2026 10:07
@konanok

konanok commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Nice catch on the proportional-allocation math — that's a subtle one and the 96-bucket quarter-hour UTC encoding is the right shape for a widget that has both Local and UTC toggles.

Two small things before merge:

  1. SessionHourlyMessageCounts.date is commented as UTC but is currently set via formatDayKey, which uses the gateway's local timezone. Harmless today (the UI only reads quarterIndex), but the comment will mislead future consumers — either switch date to a UTC day key or relax the comment to match dailyMessageCounts.date.
  2. Please add a ## Unreleased → ### Fixes entry in CHANGELOG.md; other recent fix PRs follow the ... (#<PR>). Thanks @<author>. pattern.

Optional: the quarter-hour aggregation block in loadSessionCostSummary duplicates the daily aggregation logic just above it — worth extracting a small accumulateMessageCounts(counts, entry) helper to keep the two from drifting.

@hxy91819 Thanks for catching these! All three points addressed (amended into the original commit):

  1. date comment inconsistency — The root cause was that hourlyMessageCounts stored mixed timezone semantics: date was local (via formatDayKey/toLocaleDateString) while quarterIndex was UTC. This also caused the DST bug on the frontend side. The fix unifies both fields to UTC:

    • Added formatUtcDayKey (using getUTCFullYear/getUTCMonth/getUTCDate) for hourlyMessageMap, so SessionHourlyMessageCounts.date is now genuinely UTC and the // YYYY-MM-DD (UTC) comment is accurate.
    • Frontend reconstructs the full UTC timestamp from date + quarterIndex, then uses new Date(Date.UTC(...)).getHours() for DST-aware local hour conversion.
    • formatDayKey is left unchanged — it's shared by 5 consumers (dailyMessageCounts, dailyBreakdown, etc.) where local timezone is the correct semantics.
  2. CHANGELOG.md — Added.

  3. accumulateMessageCounts helper — Extracted. Both daily and hourly aggregation now call accumulateMessageCounts(bucket, entry, errorStopReasons), eliminating the duplicated counting logic. errorStopReasons is passed as a parameter since it's a local variable inside loadSessionCostSummary.

@konanok
konanok force-pushed the fix/peak-error-hours-inaccurate-rates branch 2 times, most recently from a2b8763 to 1978829 Compare April 28, 2026 10:25
@clawsweeper

clawsweeper Bot commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve.

Keep open. Current main still computes Peak Error Hours by proportionally allocating session-wide messageCounts over hour slices, and the backend SessionCostSummary still has no hourlyMessageCounts, quarterIndex, or SessionHourlyMessageCounts contract for the UI to consume. The PR remains a focused implementation candidate with active maintainer review context and a limited, relevant patch.

Best possible solution:

Keep this PR open for maintainer review. The best path is to land this PR or an equivalent fix that adds backend per-bucket message/error counts, uses them in buildPeakErrorHours for Local and UTC views, preserves the legacy fallback for older payloads, and keeps the backend/frontend regression tests plus changelog entry aligned.

What I checked:

  • Current main still uses proportional allocation: buildPeakErrorHours reads session.usage?.messageCounts and applies the same slice share to both errors and total messages, which preserves a session-wide error rate across populated hours instead of using per-hour message/error counts. (ui/src/ui/views/usage-metrics.ts:77, b85edb3f0cf6)
  • Backend summary type has no precise hourly contract: SessionCostSummary exposes dailyMessageCounts and messageCounts, but no SessionHourlyMessageCounts, hourlyMessageCounts, or quarterIndex field on current main. (src/infra/session-cost-usage.types.ts:124, b85edb3f0cf6)
  • Session scanner returns daily/message totals only: loadSessionCostSummary builds dailyMessageMap, converts it to dailyMessageCounts, and returns dailyMessageCounts plus aggregate messageCounts; there is no hourly/quarter-hour aggregation map in the current return payload. (src/infra/session-cost-usage.ts:571, b85edb3f0cf6)
  • No current-main symbol evidence for proposed implementation: Repository search found the proposed symbols only absent on current main; the only Peak Error Hours hit is the UI label. (b85edb3f0cf6)
  • PR patch is scoped to the reported behavior: The live patch for commit 5a104e6f3b6a changes only CHANGELOG.md, session usage source/types/tests, and Usage Metrics UI/tests; it adds UTC quarter-hour buckets, UI aggregation, fallback tests, and a changelog entry. (5a104e6f3b6a)
  • Security/supply-chain review pass: The inspected PR patch does not touch CI workflows, action refs, dependency sources, lockfiles, install/build/release scripts, package publishing metadata, secrets handling, permissions, downloaded artifacts, generated/vendor/minified files, or other unrelated code-execution surfaces. (5a104e6f3b6a)

Likely related people:

  • steipete: The provided prior ClawSweeper review for this PR identified Peter Steinberger from current-main blame/log on the central Usage Metrics and session cost usage files. The same code paths remain the relevant current-main surface for this review. (role: current-main feature-history owner; confidence: medium; commits: 6249c32826d8; files: ui/src/ui/views/usage-metrics.ts, src/infra/session-cost-usage.ts, src/infra/session-cost-usage.types.ts)
  • hxy91819: hxy91819 reviewed this exact approach, requested the UTC date-key/comment and changelog follow-ups, and later assigned the PR, making them the clearest current maintainer routing contact from the PR discussion. (role: recent maintainer reviewer and assignee; confidence: medium; files: ui/src/ui/views/usage-metrics.ts, src/infra/session-cost-usage.ts, src/infra/session-cost-usage.types.ts)

Remaining risk / open question:

  • Closing this PR now would leave the current proportional-allocation Peak Error Hours behavior in place on main.
  • The PR expands the SessionCostSummary payload with sparse quarter-hour message buckets; maintainers should review payload size/contract compatibility before merge.
  • This was a read-only review, so I did not run the PR's tests or changed gate.

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

@konanok
konanok force-pushed the fix/peak-error-hours-inaccurate-rates branch from 1978829 to 5a104e6 Compare April 29, 2026 02:58
@hxy91819 hxy91819 self-assigned this Apr 29, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Apr 29, 2026
konanok and others added 2 commits April 29, 2026 15:09
The Peak Error Hours widget displayed identical error rates for all hours
because the legacy algorithm distributed errors proportionally across
session time spans. This produced misleading data (e.g., every hour
showing 9.89%) instead of highlighting actual error-heavy periods.

Changes:
- Add SessionHourlyMessageCounts type with quarterIndex field (0-95)
  representing UTC-based 15-minute buckets for timezone-accurate
  hour conversion — covers all global UTC offsets (±15/30/45 min)
- Collect per-quarter-hour message/error counts in loadSessionCostSummary
  using getUTCHours()/getUTCMinutes() with UTC day keys (formatUtcDayKey)
- Prefer precise quarterly data in buildPeakErrorHours for both local
  and UTC views, falling back to proportional allocation for sessions
  without quarterly data
- Fix DST bug: replace single getTimezoneOffset() with
  new Date(Date.UTC(...)).getHours() for DST-aware local hour mapping
- Extract accumulateMessageCounts helper to deduplicate daily/hourly
  message count aggregation logic
- Guard hourlyMessageCounts with .length check before including in
  summary (consistent with dailyLatency/dailyModelUsage pattern)
@hxy91819
hxy91819 self-requested a review April 29, 2026 07:09
@hxy91819
hxy91819 force-pushed the fix/peak-error-hours-inaccurate-rates branch from 5a104e6 to fbbf43b Compare April 29, 2026 07:19
@hxy91819
hxy91819 merged commit bd5afad into openclaw:main Apr 29, 2026
67 of 69 checks passed
@hxy91819

Copy link
Copy Markdown
Member

Merged via squash.

Thanks @konanok!

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
…claw#49396)

Merged via squash.

Prepared head SHA: fbbf43b
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
…claw#49396)

Merged via squash.

Prepared head SHA: fbbf43b
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
…claw#49396)

Merged via squash.

Prepared head SHA: fbbf43b
Co-authored-by: konanok <[email protected]>
Co-authored-by: hxy91819 <[email protected]>
Reviewed-by: @hxy91819
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
…claw#49396)

Merged via squash.

Prepared head SHA: fbbf43b
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

app: web-ui App: web-ui size: M stale Marked as stale due to inactivity

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants