Skip to content

perf(usage): skip Unicode folding for plain ASCII metadata - #7886

Merged
lidge-jun merged 1 commit into
devfrom
fix/7846-usage-normalization
Oct 29, 2026
Merged

lidge-jun merged 1 commit into
devfrom
fix/7846-usage-normalization

Conversation

@lidge-jun

@lidge-jun lidge-jun commented Oct 28, 2026 •

Copy link
Copy Markdown
Owner

Summary

Closes #7846.

A filtered GET /api/usage (provider, model, apiKeyId, since/until) re-reads the whole usage ledger, and almost all of that time went into normalizePersistedUsageRow. The cost was in metadata redaction: foldForMatching in src/lib/redact-folding.ts ran escape detection and Unicode normalization (NFKD) on every character of every metadata string, for every row.

For pure ASCII input with no escape introducer (\, %, &), the folded matching view is the input itself with an identity offset map: ASCII has no confusables, no invisible format characters, and no NFKD change. This PR returns that result directly. Every credential masking pass still runs on the folded view, and any string with non-ASCII characters or an escape introducer takes the existing path unchanged. Persisted format, filter semantics, cache invalidation and singleflight behavior are untouched.

Synthetic ledger, 100,000 rows / 105 MB, Bun 1.4.4, local Windows machine:

Stage Before After
Row normalization 4,922 ms 1,587 ms
Ledger scan 6,091 ms 2,132 ms
Provider-filtered scan + aggregation 7,361 ms 2,531 ms

The benchmark script is local scratch and is not committed; the reporter's 279 MB ledger was not available.

Verification

Focused files ran with OCX_TEST_NO_QUEUE=1 because the host's shared test queue was saturated by other lanes.

Check Result
New regression in tests/usage/usage-ledger-scanner.test.ts (counts Unicode normalization calls, no timing threshold) without the fix fails: 70,000 calls instead of 0
tests/lib/redact.test.ts, tests/usage/usage-ledger-scanner.test.ts, tests/usage/usage-log.test.ts, tests/usage/usage-aggregate-cache.test.ts, tests/server/api-usage.test.ts 178 pass, 0 fail, 1 pre-existing skip
Base vs. patched foldForMatching over 100,000 rows, all 1,114,112 code points, and 32,776 ASCII cases (folded text and offset map) 0 mismatches
bun run typecheck, bun run structure:check, bun run privacy:scan, git diff --check pass
Independent security/correctness review (equivalence proof, escape coverage, all three callers in src/lib/redact.ts) PASS, 0 blocking

Hosted PR CI on head 4d60bf9b4 passed, including gates and test changed.

Not run locally: full bun run test, a completed local bun run test:changed (it selected 2,250 files and hit its 900 s limit on the saturated host), and a live HTTP latency benchmark.

Checklist

  • Scope stays focused and avoids unrelated cleanup.
  • Docs or release notes were updated when needed. (structure/transports/byte-accounting.md documents the fast path.)
  • Security-sensitive changes were reviewed for secrets, auth, and unsafe defaults.

Summary by CodeRabbit

  • Performance
    • Usage records containing standard ASCII text are processed more efficiently during scanning, while preserving existing handling of Unicode and escaped text.
  • Bug Fixes
    • Redaction results remain consistent across optimized and general text-processing paths, including for strings with escape-like content.

@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between fdc6dd8 and 4d60bf9.

Files selected for processing: 4
  • src/lib/redact-folding.ts
  • structure/transports/byte-accounting.md
  • tests/lib/redact.test.ts
  • tests/usage/usage-ledger-scanner.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

Walkthrough

foldForMatching now bypasses Unicode folding and escape decoding for eligible ASCII input. The changes add tests for folding results, offset maps, usage-ledger scan normalization, and persisted-row normalization. The transport documentation describes the fast-path conditions.

Changes: Usage normalization performance

Layer / File(s) Summary
ASCII folding fast path
src/lib/redact-folding.ts
foldForMatching returns eligible ASCII input unchanged with an identity offset map.
Folding and scanner validation
tests/lib/redact.test.ts, tests/usage/usage-ledger-scanner.test.ts, structure/transports/byte-accounting.md
Tests compare folded text and offsets across paths, verify scanner behavior for ASCII metadata and persisted-row shapes, and document the fast-path conditions.

Priority: Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Refactor · Severity of issue fixed: Medium

Suggested reviewers: paosder, luvs01

Merge Risk: Minimal · up to 4d60b

ASCII metadata can be processed faster without an established behavior change. No merge-blocking risk is identified.

Pre-merge checks: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: adding a performance fast path that skips Unicode folding for plain ASCII usage metadata.
Linked Issues check Passed Issue #7846 permits a normalization fast path as one solution. src/lib/redact-folding.ts:64-71 returns the input and an identity map for ASCII strings without \\\\, %, or &. Other inputs retain …
Out of Scope Changes check Passed The changes remain within issue #7846. The source change optimizes foldForMatching. The scanner and redaction tests verify performance behavior and unchanged masking and normalization behavior. The …
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Full details: Linked Issues check

Explanation

Issue #7846 permits a normalization fast path as one solution. src/lib/redact-folding.ts:64-71 returns the input and an identity map for ASCII strings without \\, %, or &. Other inputs retain the existing folding path. tests/usage/usage-ledger-scanner.test.ts:51-65 verifies zero String.prototype.normalize calls for ASCII metadata during a 100-row ledger scan. The equivalence test in the same file covers legacy, redacted, nested, malformed, and rejected row shapes. The reported synthetic scan also shows a material reduction. The issue does not require a specific index or aggregate design.

Full details: Out of Scope Changes check

Explanation

The changes remain within issue #7846. The source change optimizes foldForMatching. The scanner and redaction tests verify performance behavior and unchanged masking and normalization behavior. The structure/transports/byte-accounting.md update documents the same fast path. No unrelated product behavior or cleanup is identified in the supplied change summary.

Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 1 functions across 3 files. (1 skipped: 1 unsupported.)

Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown
Contributor

✅ Deterministic PR hygiene checks passed.

@github-actions github-actions Bot added the enhancement New feature or request label Oct 28, 2026
@lidge-jun
lidge-jun marked this pull request as ready for review October 28, 2026 08:26
@lidge-jun
lidge-jun requested a review from Ingwannu as a code owner October 28, 2026 08:26
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-28T08:26:18.042653Z 4d60bf9 Draft marked ready
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@lidge-jun
lidge-jun merged commit 4179e8a into dev Oct 29, 2026
36 of 37 checks passed
@lidge-jun
lidge-jun deleted the fix/7846-usage-normalization branch October 29, 2026 04:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant