fix(dashboard): count live usage_history rows in Free Tier 'used this month' (#10381) (#10509)

* fix(dashboard): count live usage_history rows in Free Tier 'used this month' (#10381)

* fix(dashboard): use an indexable UTC month-range predicate for used-this-month (#10381)

sumUsageTokensThisMonth() filtered usage_history with
substr(timestamp, 1, 7) = strftime('%Y-%m', 'now') — a substr() expression
SQLite cannot use a range index on, and fragile against any timestamp
that isn't exactly ISO-shaped. Replace with an indexable inclusive-start/
exclusive-end UTC range: timestamp >= <month start> AND timestamp <
<next month start>, matching the ISO 8601 format saveRequestUsage()
already writes.

Adds a boundary regression test: the first instant of the current month
is included, the last instant of the previous month is excluded, and a
next-month row is excluded too (covers the upper bound substr() could
never express).

---------

Co-authored-by: adevwithpurpose <adevwithpurpose@users.noreply.github.com>
This commit is contained in:
Diego Rodrigues de Sa e Souza
2026-08-18 10:51:25 -03:00
committed by GitHub
parent 9500adb013
commit 83c1d3c659
3 changed files with 107 additions and 4 deletions

View File

@@ -1,14 +1,38 @@
import { getDbInstance } from "./core.ts";
import type { SqliteAdapter } from "./adapters/types.ts";
/** Total input+output tokens rolled up in daily_usage_summary for the current calendar month. */
/**
* Total input+output tokens for the current calendar month, across BOTH storage legs:
*
* 1. `daily_usage_summary` — the rolled-up aggregate (filled only by the retention
* cleanup path rolling up rows OLDER than `retention.usageHistory`, default 365 days),
* so the current month's rows never appear here until ~a year later (or the operator
* lowers retention).
* 2. `usage_history` — the live per-request rows (written by `saveRequestUsage` with
* `tokens_input`/`tokens_output` and an ISO `timestamp`), which hold the current month's
* actual usage.
*
* #10381: reading only leg 1 always returned ~0 for the current month. No double-count:
* a row is rolled into `daily_usage_summary` only immediately before being deleted from
* `usage_history` by the same cleanup step. The analytics layer uses the same
* reconciliation in `buildUnifiedSource`.
*/
export function sumUsageTokensThisMonth(db: SqliteAdapter = getDbInstance()): number {
try {
const row = db
.prepare(
`SELECT COALESCE(SUM(total_input_tokens + total_output_tokens), 0) AS used
FROM daily_usage_summary
WHERE date >= strftime('%Y-%m-01','now')`
`SELECT
COALESCE((
SELECT SUM(tokens_input + tokens_output)
FROM usage_history
WHERE timestamp >= strftime('%Y-%m-01T00:00:00.000Z','now')
AND timestamp < strftime('%Y-%m-01T00:00:00.000Z','now','+1 month')
), 0) +
COALESCE((
SELECT SUM(total_input_tokens + total_output_tokens)
FROM daily_usage_summary
WHERE date >= strftime('%Y-%m-01', 'now')
), 0) AS used`
)
.get() as { used: number } | undefined;
return row?.used ?? 0;