Skip to content

fix(dashboard): 修正 Sessions 页 total_tokens 漏算缓存 token 的聚合口径#240

Merged
ThreeFish-AI merged 1 commit into
feature/1.x.xfrom
ThreeFish-AI/fix-session-token-stats
May 16, 2026
Merged

fix(dashboard): 修正 Sessions 页 total_tokens 漏算缓存 token 的聚合口径#240
ThreeFish-AI merged 1 commit into
feature/1.x.xfrom
ThreeFish-AI/fix-session-token-stats

Conversation

@ThreeFish-AI

Copy link
Copy Markdown
Owner

摘要

修复 Dashboard SessionsTokens 列遗漏 cache_creation / cache_read 两类 token 的统计 Bug,使其与 Overview 页的全口径(input + output + cache_creation + cache_read)保持一致。

背景

Anthropic Prompt Cache 在长会话中常常贡献远超 input/output 的命中量,原口径 SUM(input + output) 导致 Sessions 页总量被显著低估,并与 Overview 页的卡片、Token 时序图统计口径分裂。Schema 与 log() 入参均已完整记录四类 token,问题完全收敛在两条按 session_key 分组的聚合 SQL。

变更

  • src/coding/proxy/logging/db.py:query_recent_sessions / query_session_profile 两条聚合 SQL 的 total_tokens 改为 SUM(input + output + cache_creation + cache_read),复用同文件 query_total_tokens_by_vendor(第 584 行)已验证的全口径,无前端 / API 结构变动。
  • tests/test_session_aware.py:在 test_query_recent_sessions_basic / test_query_session_profile_found 中追加 cache_creation_tokens / cache_read_tokens 入参与完整口径断言,锁定回归。
  • docs/issue.md:追加 Issue 档案,沉淀「SQL 聚合层保持单一权威定义」「usage_log 增列后必须审计所有 SUM 表达式」两条防范经验。

验证

  • uv run pytest tests/test_session_aware.py -q → 28 项通过
  • uv run pytest -q → 全量 1450 项通过,无副作用
  • grep "SUM(input_tokens + output_tokens)" 全仓库已无残留实例

- src/coding/proxy/logging/db.py: query_recent_sessions / query_session_profile 两条按 session_key 分组的聚合 SQL 中, 将 total_tokens 由 SUM(input + output) 修正为 SUM(input + output + cache_creation + cache_read), 与同文件 query_total_tokens_by_vendor / query_usage 已使用的全口径对齐, 消除 Sessions 页与 Overview 页之间的统计口径分裂;
- tests/test_session_aware.py: test_query_recent_sessions_basic / test_query_session_profile_found 中追加 cache_creation_tokens 与 cache_read_tokens 入参及完整口径断言, 锁定回归;
- docs/issue.md: 追加 Issue 档案, 记录 SQL 聚合层 SSOT 缺失导致的口径漂移, 沉淀向 usage_log 增列后必须审计所有 SUM 表达式的防范经验.

🤖 Generated with [Claude Code](https://github.com/claude), [CodeX](https://openai.com), [Gemini](https://github.com/apps/gemini-code-assist)
Co-Authored-By: Aurelius Huang<threefish.ai@gmail.com>
@ThreeFish-AI ThreeFish-AI merged commit abc4136 into feature/1.x.x May 16, 2026
6 checks passed
@ThreeFish-AI ThreeFish-AI deleted the ThreeFish-AI/fix-session-token-stats branch May 17, 2026 14:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant