perf(leaderboard): 优化缓存命中率榜单查询并添加索引
背景
供应商「缓存命中率」排行榜在缓存未命中时会对 usage_ledger 做两次聚合(provider 级 + provider+model 级),在数据量较大时开销偏高。
改动
src/repository/leaderboard.ts:将缓存命中率榜单改为仅执行一次 provider+model 聚合查询,并在应用层汇总 provider 级统计(减少一次 DB 聚合扫描);同时对每个 provider 的modelStats做稳定排序,避免顺序漂移,并为 provider 排名增加稳定第三排序键。- 对 model 字段做
TRIM + NULLIF归一化,避免空白模型名造成无意义分组;模型排行榜在 SQL 层排除空模型,减少无效分组回传。 src/drizzle/schema.ts+ 迁移:为usage_ledger增加 partial indexidx_usage_ledger_cache_required_created_at(blocked_by IS NULL且 cache tokens > 0),加速按时间范围统计。tests/unit/repository/leaderboard-provider-metrics.test.ts:补齐billingModelSource: "original"分支覆盖;并在空模型过滤用例里额外断言 provider 聚合总量不丢失。
兼容性
- 返回字段与排序规则保持不变;
totalTokens仍按原语义保留(deprecated,等同totalInputTokens)。
验证
bun run lintbun run typecheckbun run testbun run build
Greptile Summary
This PR successfully optimizes the cache hit rate leaderboard by reducing database load from 2 aggregation queries to 1, with provider-level statistics now aggregated at the application layer.
Key improvements:
- Adds partial index
idx_usage_ledger_cache_required_created_atonusage_ledgerto accelerate time-range queries for cache-enabled entries - Introduces
buildNormalizedModelField()helper usingTRIM + NULLIFto normalize empty/whitespace model names to NULL - Consolidates cache hit rate query: executes single provider+model aggregation, then derives provider totals in application code (eliminates redundant DB scan)
- Implements stable sorting for
modelStatsby (cacheHitRate desc, totalRequests desc, model name asc) to prevent ordering drift - Filters empty models at SQL level for model leaderboard using
isNotNull(modelField)instead of post-query filtering - Changes from
getSystemSettingstogetCachedSystemSettingsfor better cache utilization
Behavior preservation:
- Empty/blank model names excluded from
modelStatsarray but still contribute to provider-level totals (intentional, verified by tests) - Return fields and ranking order unchanged;
totalTokensdeprecated field maintained for backward compatibility - Test coverage expanded for
billingModelSource: "original"branch and empty model handling
Confidence Score: 4/5
- This PR is safe to merge with minimal risk - it's a well-tested performance optimization with no breaking changes
- Score reflects solid implementation of a performance optimization with comprehensive test coverage. The logic change from dual DB queries to single query + application aggregation is sound and tested. Model name normalization and stable sorting prevent edge cases. Minor confidence reduction due to complexity of aggregation logic migration, but extensive test assertions verify correctness including edge cases (empty models, multiple providers, sorting stability).
- No files require special attention - the changes are well-structured and tested
Important Files Changed
| Filename | Overview |
|---|---|
| drizzle/0078_dear_alex_power.sql | Adds partial index on usage_ledger.created_at with cache-required filter for optimized leaderboard queries |
| src/drizzle/schema.ts | Adds index definition matching migration, properly scoped to cache-enabled and non-blocked ledger entries |
| src/repository/leaderboard.ts | Optimizes cache hit rate query from 2 DB aggregations to 1, adds model name normalization, stable sorting for modelStats, and filters empty models at SQL level |
| tests/unit/repository/leaderboard-provider-metrics.test.ts | Adds coverage for billingModelSource: "original" branch and verifies empty model filtering preserves provider-level totals |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
Start[Cache Hit Rate Leaderboard Request] --> OldOrNew{Implementation}
OldOrNew -->|Before| Old1[Query 1: Provider-level aggregation<br/>GROUP BY providerId]
Old1 --> Old2[Query 2: Model-level aggregation<br/>GROUP BY providerId, model]
Old2 --> OldMerge[Merge results<br/>Attach modelStats to providers]
OldMerge --> OldReturn[Return leaderboard]
OldOrNew -->|After| New1[Single Query: Model-level aggregation<br/>GROUP BY providerId, providerName, model<br/>with NULLIF TRIM model normalization]
New1 --> NewAgg[Application-layer aggregation:<br/>- Accumulate provider totals from model rows<br/>- Filter null models from modelStats<br/>- Stable sort modelStats]
NewAgg --> NewSort[Sort providers by:<br/>cacheHitRate desc, totalRequests desc, providerId asc]
NewSort --> NewReturn[Return leaderboard]
NewReturn -.Index acceleration.-> Index[Partial Index:<br/>idx_usage_ledger_cache_required_created_at<br/>WHERE blockedBy IS NULL AND cache tokens > 0]
style Old1 fill:#ffcccc
style Old2 fill:#ffcccc
style New1 fill:#ccffcc
style Index fill:#cce5ff
Last reviewed commit: 0f1f682
Summary of Changes
Hello, I'm Gemini Code Assist[^1]! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
此拉取请求旨在通过优化数据库查询和引入新的索引来提升供应商缓存命中率排行榜的性能。核心改动在于将原有的双层数据库聚合查询精简为单层模型级别聚合,并在应用层进行数据汇总,从而减少了数据库负载。同时,通过模型字段的归一化处理,提升了排行榜数据的准确性和可用性。
Highlights
- 性能优化: 重构了供应商缓存命中率排行榜的查询逻辑,将两次数据库聚合查询(供应商级别和供应商+模型级别)优化为仅执行一次供应商+模型级别的聚合,并在应用层汇总供应商级别统计,显著降低了大数据量下的查询开销。
- 数据库索引: 为
usage_ledger表新增了一个名为idx_usage_ledger_cache_required_created_at的部分索引,以加速涉及缓存请求的时间范围查询。 - 数据归一化: 对模型字段(
model)应用了TRIM + NULLIF函数进行归一化处理,避免因空白模型名导致无意义的分组,提高了数据准确性。 - 测试更新: 更新了相关的单元测试,以适应新的排行榜计算逻辑和数据结构,确保了变更的正确性。
Changelog
- drizzle/0078_dear_alex_power.sql
- 新增了一个迁移脚本,用于在
usage_ledger表上创建部分索引idx_usage_ledger_cache_required_created_at。
- 新增了一个迁移脚本,用于在
- drizzle/meta/_journal.json
- 更新了 Drizzle 迁移日志,记录了新的迁移文件
0078_dear_alex_power.sql。
- 更新了 Drizzle 迁移日志,记录了新的迁移文件
- src/drizzle/schema.ts
- 在
usageLedger表的模式定义中,添加了新的部分索引usageLedgerCacheRequiredCreatedAtIdx,以优化缓存命中率排行榜的查询性能。
- 在
- src/repository/leaderboard.ts
- 将
getSystemSettings替换为getCachedSystemSettings,以利用缓存的系统设置。 - 简化了
cacheRequiredCondition的 SQL 表达式,移除了COALESCE函数。 - 移除了原有的直接针对供应商级别的聚合查询,改为在应用层从模型级别聚合数据中派生。
- 引入了
clampRatio01辅助函数,用于将比率限制在 0 到 1 之间。 - 修改了模型字段的选取逻辑,增加了
TRIM和NULLIF以归一化模型名称。 - 在模型级别查询中增加了
providerName、totalCost和cacheCreationCost字段。 - 重构了排行榜的计算逻辑,先进行模型级别聚合,然后在应用层根据这些聚合数据计算并排序供应商级别的排行榜条目。
- 将
- tests/unit/repository/leaderboard-provider-metrics.test.ts
- 更新了单元测试中的模拟数据和断言,以适应新的排行榜计算逻辑,特别是供应商级别字段现在是从模型聚合中派生的这一变化。
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in pull request comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with :thumbsup: and :thumbsdown: on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
[^1]: Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.
[!NOTE]
Reviews paused
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
- [ ] ▶️ Resume reviews
- [ ] 🔍 Trigger review
📝 Walkthrough
Walkthrough
新增针对此次缓存相关条件且未被阻塞行的部分索引并在 schema 中导出;将 provider 聚合改为先按模型聚合再在内存合并,更新相应单元测试与迁移日记条目。
Changes
| Cohort / File(s) | Summary |
|---|---|
数据库迁移与元数据 drizzle/0078_dear_alex_power.sql, drizzle/meta/_journal.json |
新增 SQL 迁移:按需创建部分索引 idx_usage_ledger_cache_required_created_at(基于 created_at,WHERE: blocked_by IS NULL AND (cache_creation_input_tokens > 0 OR cache_read_input_tokens > 0));在 _journal.json 中插入对应迁移条目。 |
数据库模式声明 src/drizzle/schema.ts |
在导出的 schema 中新增部分索引声明 usageLedgerCacheRequiredCreatedAtIdx,与迁移中的 WHERE 子句一致并导出该索引标识。 |
排行榜聚合与逻辑重构 src/repository/leaderboard.ts |
将 provider 级聚合改为先按模型汇总再在内存合并;引入 getCachedSystemSettings、模型字段规范化 helper、clampRatio01,扩展 modelStats 与 provider 层聚合字段(如 totalCost、cacheCreationCost、totalInputTokens、cacheHitRate 等),并调整排序与空模型过滤逻辑。 |
单元测试更新 tests/unit/repository/leaderboard-provider-metrics.test.ts |
测试改为使用 getCachedSystemSettings 的 mock,更新 mock 数据以包含 providerName/model 与数值型成本字段,调整断言以匹配新的聚合输出及模型明细。 |
Estimated code review effort
🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs
- ding113/claude-code-hub#811: 与
usage_ledger表及索引/迁移声明直接相关,可能包含最初的表或索引变更。 - ding113/claude-code-hub#753: 修改相同的 leaderboard 聚合逻辑(provider/model 聚合与度量字段);实现细节可能交叉。
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | ⚠️ Warning | Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
✅ Passed checks (2 passed)
| Check name | Status | Explanation |
|---|---|---|
| Title check | ✅ Passed | 标题准确总结了主要改动:性能优化缓存命中率榜单查询并添加数据库索引,与变更内容(减少数据库聚合次数、添加partial index)相符。 |
| Description check | ✅ Passed | 拉取请求的描述与变更集相关且详细说明了所有关键改动,包括数据库查询优化、索引添加、模型字段归一化和测试更新。 |
✏️ Tip: You can configure your own custom pre-merge checks in the settings.
✨ Finishing Touches
🧪 Generate unit tests (beta)
- [ ] Create PR with unit tests
- [ ] Post copyable unit tests in a comment
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.
Comment @coderabbitai help to get the list of available commands and usage tips.
Additional Comments (1)
tests/unit/repository/leaderboard-provider-metrics.test.ts
Wrong module mocked - code now uses getCachedSystemSettings from @/lib/config/system-settings-cache, not getSystemSettings from @/repository/system-configvi.mock("@/lib/config/system-settings-cache", () => ({
getCachedSystemSettings: mocks.getSystemSettings,
}));
Prompt To Fix With AI
This is a comment left during a code review.
Path: tests/unit/repository/leaderboard-provider-metrics.test.ts
Line: 89-91
Comment:
Wrong module mocked - code now uses `getCachedSystemSettings` from `@/lib/config/system-settings-cache`, not `getSystemSettings` from `@/repository/system-config`
```suggestion
vi.mock("@/lib/config/system-settings-cache", () => ({
getCachedSystemSettings: mocks.getSystemSettings,
}));
```
How can I resolve this? If you propose a fix, please make it concise.
已根据 CodeRabbit 的 nitpick 调整:modelStats 构建时移除冗余的 row.model?.trim(),改为直接使用已在 SQL 侧归一化(NULLIF(TRIM(...), ''))后的 row.model。
当前 PR 相关 Actions checks 均已通过。若看到早期 Codex PR Review 失败,为 fork PR 在 pull_request_target 下的权限校验所致(与代码无关)。
此 PR 需要解决冲突以便合并。