Skip to content
This repository was archived by the owner on Jul 30, 2026. It is now read-only.

fix(usage): split Pi and OMP reasoning and recover swarm agents - #137

Merged
makoMakoGo merged 6 commits into
personal/local-clientsfrom
agent/fix-omp-usage-and-swarm-attribution
Jul 12, 2026
Merged

fix(usage): split Pi and OMP reasoning and recover swarm agents#137
makoMakoGo merged 6 commits into
personal/local-clientsfrom
agent/fix-omp-usage-and-swarm-attribution

Conversation

@makoMakoGo

@makoMakoGo makoMakoGo commented Jul 11, 2026

Copy link
Copy Markdown
Owner

Summary

  • split Pi reasoning and OMP reasoningTokens out of their inclusive source output buckets and require exact source totalTokens
  • preserve mutually exclusive reasoning internally while projecting output + reasoning back into inclusive Output across models, monthly, and hourly text/JSON reports and every human-facing TUI output field
  • omit separate Reasoning report columns and JSON keys so displayed buckets reconcile without widening terminal tables
  • count every internal token bucket in Wrapped Top Models and Top Clients rankings
  • treat inclusive output as authoritative when a provider reports a reasoning breakdown above output, clamping reasoning to output without emitting a warning or dropping the message
  • fold OMP provider-side orchestration into matching token buckets
  • recognize official .swarm_<name>/context/swarm-<name>-<agent>-<iteration>.jsonl artifacts as stable OMP swarm agents while preserving the full artifact stem as the instance
  • bump Pi/OMP source parser revisions and the TUI cache schema so stale token buckets and agent labels are rebuilt

Root cause

OMP defines output as the inclusive output-token count and reasoningTokens as a breakdown within it. A real xiaomi-token-plan / mimo-v2.5 response stopped at the length limit with output=32000 and reasoningTokens=32123, while both totalTokens and cost accounted for only 32000 output tokens. The Xiaomi usage detail therefore violated its own subset invariant.

Tokscale now clamps only that malformed breakdown: the example becomes internal reasoning 32000 and non-reasoning output 0, while its exact source total remains unchanged. This prevents one provider metadata anomaly from aborting the entire OMP report. Negative token counts, missing required buckets, and mismatched totalTokens remain hard errors.

Report projection

Internal aggregation, pricing, caches, and explicit raw token-breakdown exports keep reasoning separate from non-reasoning output. Human-facing CLI reports and TUI views use inclusive output instead:

displayed_output = output + reasoning
displayed_total  = input + displayed_output + cache_read + cache_write

This projection applies to the models, monthly, and hourly text/JSON reports and to TUI Models, Overview, Stats, Hourly, Daily, Monthly, and Weekly output fields. Wrapped rankings use the complete five-bucket internal total. No surface adds a Reasoning column merely to expose the internal split.

The local source-coverage survey and rationale for this fork policy are recorded in #138.

Validation

  • cargo fmt --all -- --check
  • cargo test --workspace — 2137 passed, 5 ignored
  • cargo clippy --workspace --all-targets --all-features -- -D warnings
  • OMP report fixtures confirm internal output 25 plus reasoning 25 becomes report Output 50 with no Reasoning column/key; reconcilable reports and TUI totals remain 165
  • Wrapped ranking regression confirms Top Models and Top Clients each count all five buckets and report 165 rather than 140
  • clamp fixture confirms reasoningTokens=51, source output=50 becomes internal reasoning 50/non-reasoning output 0, while reports remain Output 50, Total 165, with no warning field
  • full live OMP scan succeeds: 159313 messages and 18,192,021,544 total tokens
  • cold-scanned the restored 41-file OMP swarm archive: 1605 positive messages, 159,250,111 total tokens, 550,898 non-reasoning output tokens, and 644,152 reasoning tokens
  • rebuilt TUI data from that archive: all 1605 positive messages attributed across 38 stable swarm-agent rows and 41 instances
  • scanned the live Pi data successfully: 84 messages with separate internal output and reasoning totals

The existing 596 all-zero assistant usage records remain skipped.

@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown

Review Change Stack

Walkthrough

本次变更统一了 Pi/OMP 的 reasoning token 解析、校验、聚合和展示口径。CLI 的 JSON 与表格输出将 reasoning 合并到 output,并采用溢出安全的总量计算;OMP/Pi parser version、swarm 身份解析及 TUI 缓存版本同步更新。

Changes

推理 token 解析与聚合

Layer / File(s) Summary
Pi/OMP 用量归一化与身份解析
crates/tokscale-core/src/sessions/pi.rs, crates/tokscale-core/src/adapters/{omp,pi}.rs, docs/adr/...
Pi/OMP usage 新增字段互斥、非负、桶求和、totalTokens 一致性和 reasoning 裁剪校验;OMP 优先从 canonical swarm 路径恢复 agent 身份,并更新 parser version。
月度 reasoning 聚合
crates/tokscale-core/src/aggregate/*, crates/tokscale-core/src/lib.rs
MonthlyUsage 和月度累加器新增 reasoning 字段,并通过月度契约测试验证聚合结果。
CLI 输出与总量计算
crates/tokscale-cli/src/commands/{models,monthly}.rs, crates/tokscale-cli/src/tui/cache.rs, crates/tokscale-cli/tests/cli_tests.rs
JSON、TUI 表格和终端汇总将 reasoning 合并到 output,使用 checked token totals,并更新 OMP 推理、裁剪和缓存版本测试。

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant OMP JSONL
  participant Pi/OMP Parser
  participant Monthly Aggregator
  participant CLI Report
  OMP JSONL->>Pi/OMP Parser: 读取 usage 与 swarm 路径
  Pi/OMP Parser->>Monthly Aggregator: 输出归一化 TokenBreakdown
  Monthly Aggregator->>CLI Report: 提供 MonthlyUsage 与 reasoning
  CLI Report->>CLI Report: 合并 output/reasoning 并计算总量
Loading

Possibly related issues

  • makoMakoGo/tokscale issue 20:涉及 Pi/OMP 的 reasoningTokens 处理及其向总量和展示 output 的传递。

Possibly related PRs

Poem

小兔抱着 token 跳,
reasoning 融进 output 怀抱。
OMP swarm 找到新家,
溢出检查守住数字花。
月报与表格齐欢笑。

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 69.23% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 标题准确概括了本次 PR 的核心变化:拆分 Pi/OMP 的 reasoning,并恢复 swarm agent 识别。
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch agent/fix-omp-usage-and-swarm-attribution

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.

@codspeed-hq

codspeed-hq Bot commented Jul 11, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 27 untouched benchmarks


Comparing agent/fix-omp-usage-and-swarm-attribution (59988f0) with personal/local-clients (ab00841)

Open in CodSpeed

@makoMakoGo makoMakoGo left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking findings: the Pi/OMP usage split matches the upstream bucket definitions, but this change currently drops reasoning from the monthly report and silently coerces an impossible source breakdown. Both affect data correctness and should be fixed before merge.

Comment thread crates/tokscale-core/src/sessions/pi.rs
Comment thread crates/tokscale-core/src/sessions/pi.rs

Copy link
Copy Markdown
Owner Author

Review correction: P2 is withdrawn. The reasoning > output clamp is an intentional resilience policy based on a reproduced provider anomaly: inclusive output and exact totalTokens remain authoritative, while only the malformed reasoning breakdown is bounded so one bad record cannot fail the entire local scan/report pipeline. The resolved P2 thread requires no code change. P1 (monthly reporting dropping the newly split reasoning bucket) remains the only blocking finding from my review.

@makoMakoGo
makoMakoGo marked this pull request as ready for review July 12, 2026 03:31
Treat client reasoning fields as subsets of inclusive output, validate source totals, and include reasoning in CLI totals. Recover canonical OMP swarm agent identity from official artifact paths and invalidate stale parser/TUI caches.
Treat inclusive output as authoritative when a provider reports reasoning above output, preserving exact source totals instead of aborting the report. This handles the observed Xiaomi MiMo length-stop response with output 32000 and reasoningTokens 32123.
@makoMakoGo
makoMakoGo force-pushed the agent/fix-omp-usage-and-swarm-attribution branch from ad699e1 to 1feba94 Compare July 12, 2026 03:37

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread crates/tokscale-cli/src/commands/models.rs Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
crates/tokscale-core/src/adapters/omp.rs (1)

20-22: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

建议补充注释,说明该版本号同时覆盖 swarm 识别变更

常量名为 OMP_USAGE_AND_SWARM_REVISION,但注释只解释了 reasoning clamp 的动机,未提及 swarm agent 识别(.swarm_<name>/context/... 规范路径识别)同样是触发该版本跳变的原因。parser_version 是缓存失效的关键字段,补全注释有助于后续再次调整版本号时理解历史动机。

📝 建议补充注释
-// Earlier OMP revisions were emitted before malformed inclusive-reasoning
-// breakdowns were clamped to their authoritative output bucket.
+// Earlier OMP revisions were emitted before malformed inclusive-reasoning
+// breakdowns were clamped to their authoritative output bucket, and before
+// canonical `.swarm_<name>/context/...` artifacts were recognized as stable
+// swarm agent identities.
 const OMP_USAGE_AND_SWARM_REVISION: u32 = crate::adapters::MODEL_ID_CANONICALIZATION_REVISION + 4;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/tokscale-core/src/adapters/omp.rs` around lines 20 - 22, 补充
OMP_USAGE_AND_SWARM_REVISION 上方的注释,明确说明该版本号同时覆盖 swarm agent 的识别变更,包括规范路径
`.swarm_<name>/context/...` 的识别;保留现有关于 malformed inclusive-reasoning breakdowns
被归并到权威输出桶的说明。
crates/tokscale-cli/tests/cli_tests.rs (1)

2378-2512: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

建议为 monthly 命令补充等价的 clamp 回归测试

test_models_report_clamps_reasoning_above_output 只覆盖了 models 命令的 reasoning 超过 output 时的 clamp 场景,而本次修复的 P1 阻塞项恰恰是关于 monthly 报表丢弃 reasoning 桶的问题。建议为 monthly --json(以及可选的表格输出)补充一条对称的回归测试,直接覆盖该场景,而不仅依赖两个命令共享同一套底层解析逻辑这一间接保证。

As per path instructions, "Add integration tests under the relevant crate tests/ directory for CLI/session behavior."

#[test]
fn test_monthly_report_clamps_reasoning_above_output() {
    let tmp = TempDir::new().expect("failed to create temp dir");
    let base = tmp.path();
    prime_pricing_cache(base);
    let sessions = base.join(".omp/agent/sessions");
    fs::create_dir_all(&sessions).unwrap();
    fs::write(
        sessions.join("monthly-invalid-reasoning-breakdown.jsonl"),
        concat!(
            r#"{"type":"session","id":"monthly-reasoning-overflow-session","timestamp":"2026-01-01T00:00:00.000Z","cwd":"/tmp"}"#,
            "\n",
            r#"{"type":"message","id":"monthly-reasoning-overflow-message","parentId":null,"timestamp":"2026-01-01T00:00:01.000Z","message":{"role":"assistant","model":"gpt-5.5","provider":"openai","usage":{"input":100,"output":50,"cacheRead":10,"cacheWrite":5,"reasoningTokens":51,"totalTokens":165}}}"#,
            "\n"
        ),
    )
    .unwrap();

    let output = cmd_with_home(base)
        .args(["monthly", "--json", "--client", "omp", "--no-spinner"])
        .output()
        .unwrap();
    assert!(output.status.success(), "command failed: {output:?}");

    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(json["entries"][0]["output"], 50);
    assert!(json["entries"][0].get("reasoning").is_none());
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/tokscale-cli/tests/cli_tests.rs` around lines 2378 - 2512, Extend the
integration coverage in the monthly reporting tests by adding a test equivalent
to test_models_report_clamps_reasoning_above_output for the monthly command.
Create a session fixture with reasoningTokens greater than output, invoke
monthly --json, and assert successful execution, output remains 50, and no
reasoning field is emitted; optionally include matching table-output assertions
if supported by the existing test style.

Source: Path instructions

crates/tokscale-cli/src/commands/models.rs (1)

21-38: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

checked_token_total/displayed_outputmonthly.rs 中的等价逻辑重复

monthly.rs 中已经存在功能相同的 checked_token_sum(用于 displayed_output/monthly_token_total),这里新增的 checked_token_total(及 displayed_output/displayed_token_total)是几乎逐字重复的第二份实现,仅 panic 文案不同。提交历史中有一条 "Share token-total calculations across monthly reporting",但实际结果是两个命令文件各自维护了一份几乎相同的溢出安全求和逻辑,后续两处实现出现分歧的风险随之增加。建议将该求和辅助函数(以及可能的 displayed_output 抽象)提取到 CLI 命令间共享的模块中。

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/tokscale-cli/src/commands/models.rs` around lines 21 - 38, 将 models.rs
中的 checked_token_total、displayed_output 和 displayed_token_total 与 monthly.rs
的等价逻辑合并到 CLI 命令间共享模块,删除两处重复实现并让两类命令复用同一套溢出安全求和辅助函数;保留现有 displayed_output 与总
token 计算语义及溢出处理行为。
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@crates/tokscale-cli/src/commands/models.rs`:
- Around line 21-38: 将 models.rs 中的 checked_token_total、displayed_output 和
displayed_token_total 与 monthly.rs 的等价逻辑合并到 CLI
命令间共享模块,删除两处重复实现并让两类命令复用同一套溢出安全求和辅助函数;保留现有 displayed_output 与总 token
计算语义及溢出处理行为。

In `@crates/tokscale-cli/tests/cli_tests.rs`:
- Around line 2378-2512: Extend the integration coverage in the monthly
reporting tests by adding a test equivalent to
test_models_report_clamps_reasoning_above_output for the monthly command. Create
a session fixture with reasoningTokens greater than output, invoke monthly
--json, and assert successful execution, output remains 50, and no reasoning
field is emitted; optionally include matching table-output assertions if
supported by the existing test style.

In `@crates/tokscale-core/src/adapters/omp.rs`:
- Around line 20-22: 补充 OMP_USAGE_AND_SWARM_REVISION 上方的注释,明确说明该版本号同时覆盖 swarm
agent 的识别变更,包括规范路径 `.swarm_<name>/context/...` 的识别;保留现有关于 malformed
inclusive-reasoning breakdowns 被归并到权威输出桶的说明。

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 89d58a33-cd19-463a-a81d-ebbc2305f2ac

📥 Commits

Reviewing files that changed from the base of the PR and between ab00841 and ede9e86.

📒 Files selected for processing (11)
  • crates/tokscale-cli/src/commands/models.rs
  • crates/tokscale-cli/src/commands/monthly.rs
  • crates/tokscale-cli/src/tui/cache.rs
  • crates/tokscale-cli/tests/cli_tests.rs
  • crates/tokscale-core/src/adapters/omp.rs
  • crates/tokscale-core/src/adapters/pi.rs
  • crates/tokscale-core/src/aggregate/accumulators.rs
  • crates/tokscale-core/src/aggregate/parity_tests.rs
  • crates/tokscale-core/src/lib.rs
  • crates/tokscale-core/src/sessions/pi.rs
  • docs/adr/0006-agent-identity-for-agents-tab.md

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 10 files (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread crates/tokscale-core/src/usage_views.rs
@makoMakoGo
makoMakoGo merged commit 802bb29 into personal/local-clients Jul 12, 2026
10 checks passed
@makoMakoGo
makoMakoGo deleted the agent/fix-omp-usage-and-swarm-attribution branch July 12, 2026 09:43
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant