Skip to content

[Bug][Performance] Filtered GET /api/usage rescans the whole ledger; 90% of the time is normalizePersistedUsageRow #7846

Closed

Description

@neomaitre

Client or integration

Direct HTTP/API client

Area

Dashboard

Summary

Any filtered usage query (provider, model, apiKeyId, since/until) bypasses the
summary cache and runs scanUsageLedgerCooperatively over the full usage.jsonl
(logs-usage-routes.ts: "Filtered responses have their own full-scan singleflight").
On a ledger of 143k rows (279 MB, ~2.5 months of a shared hub) that takes 25–35 s wall on
one thread, and almost all of it is normalizePersistedUsageRow, not I/O, parsing or
aggregation. Unfiltered queries are served from the warm cache in ~50 ms.

Expected: a filtered usage query should take on the order of the unfiltered one (tens to
hundreds of ms), or at least not spend ~90% of its time re-normalizing rows that this same hub
wrote.

Related: #500 fixed the unfiltered dashboard path with the retained aggregate; #7289 added
the API-key filter, which (like provider/model) takes the uncached full-scan path.

Measurements (calling the hub's own modules from a bun script inside the same container):

Stage over the whole ledger Time
readFileSync (page cache) 0.2 s
createHash("sha256") of the whole file 1.3 s
LF framing + per-line TextDecoder 1.0 s
JSON.parse of every row 1.0 s
normalizePersistedUsageRow on every parsed row 23.1 s
scanUsageLedgerCooperatively with a no-op onEntry 25.0 s
scan + createUsageSummaryAccumulator(...).add (filtered or unfiltered) 32 s

So ~160 µs per row goes into re-normalizing rows that this same hub wrote.

Side effect: while a scan runs, /healthz latency through the proxy goes from ~50 ms to
70–150 ms (the scan yields every 1 MiB / 1000 rows, ~90 ms of work per slice on this CPU),
so in-flight completions see hiccups for the duration.

managementUsageMaxReadBytes is documented as deprecated and does not bound this path.
The only knob that helps is usageLedgerMaxBytes, which deletes history.

Suggestions (each keeps the ledger intact):

  1. A fast path in normalizePersistedUsageRow for rows written by the current writer
    (e.g. a schema-version stamp on write; only unstamped/older rows take the full path).
    This alone would remove ~90% of the cost.
  2. Maintain per-provider / per-model partial aggregates on append, so a first-time filter
    does not start from byte zero (the retained-aggregate + checkpoint machinery already
    exists for the unfiltered path).
  3. A derived index (SQLite, like routing-history.sqlite) holding only the filterable
    columns, rebuilt from usage.jsonl when missing and appended on write.

Happy to run further measurements on this ledger if useful.

Reproduction

  1. Run the hub with a large usage.jsonl (here: 279,011,952 bytes, 143,152 rows, all valid:
    invalid=0, oversized=0; file fully in page cache, reading it takes 0.2 s).
  2. GET /api/usage?range=24h → 50 ms (served from the cache).
  3. GET /api/usage?range=24h&provider=openai → 34.7 s on the first call (37.5 s hub CPU),
    53 ms when repeated.
  4. GET /api/usage?range=7d&provider=anthropic → 28.4 s.
  5. GET /api/usage?range=24h&model=<id> → 27.8 s.
  6. Watch /healthz during step 3: latency rises from ~50 ms to 70–150 ms until the scan ends.

Timings observed through an nginx front on the same host. Profiling the stages in isolation
with a bun script that imports the hub's modules gives the table in the Summary.

Version

2.93.0

Operating system

Linux x86_64 (Docker container, no CPU quota, 0 throttled periods), Bun 1.4.4, Xeon E5-2670 @ 2.6 GHz (one core busy during the scan, the rest idle)

Provider and model

Not provider-specific (reproduced with provider=openai, provider=anthropic and a model= filter)

Logs or error output

GET /api/usage?range=24h                      50 ms   (cached)
GET /api/usage?range=24h&provider=openai      34.7 s  first call, 37.5 s hub CPU; 53 ms repeated
GET /api/usage?range=7d&provider=anthropic    28.4 s
GET /api/usage?range=24h&model=<id>           27.8 s

Screenshots and supporting files

No response

Redacted configuration

{
  "note": "default usage settings; managementUsageMaxReadBytes and usageLedgerMaxBytes not set"
}

Checks

  • I searched existing issues and documentation.
  • I removed secrets, tokens, account details, request credentials, and personal data.

Activity

  1. github-actions commented on Oct 27, 2026

    @github-actions
    Contributor

    Issue reopened

    The report now contains the information required by the automated check. Thanks for updating it.

  2. added
    bug
    gui
    on Oct 27, 2026
  3. Ingwannu commented on Oct 29, 2026

    @Ingwannu
    Owner

    The cold filtered-aggregate path still differs from the retained unfiltered cache on current dev 9b78a16f4fe0c300527e6b183052407269bb941d: src/server/management/logs-usage-routes.ts routes filtered requests to getFilteredUsageAggregate, separate from the unfiltered summary cache. Your repeated same-query ~53ms result should remain distinguished from a cold/different filter; this is not evidence that every filtered request rescans from byte zero.

    #7886 has since landed an ASCII metadata normalization fast path. It does not by itself establish improved end-to-end cold-query latency, so the useful next measurement is the same stage breakdown on a build containing that commit, with ledger size/row count, filter and mutation state held fixed. Please publish timings/counts only, not the ledger or user/account fields.

    For a follow-up patch, reuse the existing aggregate/checkpoint machinery or a bounded derived index rather than an unbounded map of fully normalized historical rows. Cache identity must include file replacement/truncation/rewrite and relevant overlay/time-zone state. A schema-version field in editable JSONL cannot alone authorize bypassing validation/redaction; a fast path must still prove its admitted shape. No destructive history-retention workaround or live ledger probe was run here. Keeping the performance issue open.

  4. lidge-jun commented on Oct 30, 2026

    @lidge-jun
    Owner

    Measurement on current dev (L5 maintenance lane for @lidge-jun), timings and counts only.

    Setup. Source snapshots of dev at d389699c96db (includes #7886) and of d588ca9d22a9 (the commit just before #7886). Each one imports the hub's own modules from a bun script (Bun 1.4.4, Windows, AMD Ryzen 9 9950X3D, one process, file in page cache). The ledger is synthetic: 143,152 rows, 186,663,630 bytes (1,304 bytes per row), written to a temporary OPENCODEX_HOME. Each row carries the usual metadata strings (served, resolved, wire and requested model, effort and reasoning fields, four service-tier fields, logical request id, API key id, conversation id) and two attempts. No user ledger was read. Ranges are over two back-to-back runs per build on an idle host. The scan figures time the scanner and filtered accumulator directly, the same pair rebuildFilteredAggregate uses for a cold filter; they exclude route, cache publication and HTTP time.

    Stage over the whole ledger before #7886 current dev
    JSON.parse of every row ~0.2 s ~0.2 s
    normalizePersistedUsageRow on every row 4.1–4.7 s 1.10–1.11 s
    scanUsageLedgerCooperatively, no-op onEntry 5.1–5.6 s 1.84–1.89 s
    scan + filtered accumulator (provider=openai) 5.5–6.7 s 1.62–1.69 s

    #7886 cut normalization by about 4x (roughly 30 → 7.7 µs per row) and a cold filtered scan by about 3x on this machine. Normalization is still about 60% of the scan. As a rough illustration only: this machine ran the pre-#7886 normalization about 5x faster than the reporter's hub (23.1 s there), and scaling by that factor suggests a cold filtered query on that hub in the high single-digit seconds. The hub's rows are larger (about 1,950 bytes against 1,304 here), its field mix is unknown, and the hardware and OS differ, so only a direct measurement on a build containing #7886 can say what that hub sees now. Either way it is far from the tens of milliseconds the unfiltered cache serves.

    Where the remaining time goes. Each variant was normalized over 20,000 parsed rows on current dev, in µs per row. A minimal row costs 1.36. With served, resolved and wire model added it costs 2.44, with four service-tier fields 3.39, with two attempts 3.32, with the id fields 1.62, and with the effort fields 1.69. The cost is spread across the per-field sanitizeLogMetadataString and redaction passes, not concentrated in one helper. This lane found no bounded, safe local fast path that keeps every one of those passes. That does not rule out a semantics-preserving optimization of those helpers, like #7886 did for folding.

    Decision for this lane: no patch. The remaining cost needs the design Ingwannu described above: either reuse the retained aggregate and checkpoint machinery for filtered queries, or build a bounded derived index whose identity covers file replacement, truncation, rewrite, the cost overlay and time zone. That is a design change, not a bounded fix, so this issue stays open for it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    buggui

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions