fix(session): clamp output token count to prevent negative values (#9168)#9178
fix(session): clamp output token count to prevent negative values (#9168)#9178kagura-agent wants to merge 1 commit intoKilo-Org:mainfrom
Conversation
| total, | ||
| input: adjustedInputTokens, | ||
| output: safe(outputTokens - reasoningTokens), | ||
| output: safe(Math.max(0, outputTokens - reasoningTokens)), |
There was a problem hiding this comment.
WARNING: This fallback still drops real output tokens for the inconsistent provider case
When reasoningTokens > outputTokens, clamping outputTokens - reasoningTokens to 0 avoids the negative value, but it also discards the provider's reported non-reasoning output count entirely. Downstream displays and stats that read tokens.output will still undercount every affected response. A safer fallback here is to treat outputTokens as already-separated when the invariant is violated.
| output: safe(Math.max(0, outputTokens - reasoningTokens)), | |
| output: safe(reasoningTokens > outputTokens ? outputTokens : outputTokens - reasoningTokens), |
Code Review SummaryStatus: 1 Issues Found | Recommendation: Address before merge Overview
Issue Details (click to expand)WARNING
Other Observations (not in diff)No issues found in unchanged code that require summary-only reporting. Files Reviewed (1 files)
Fix these issues in Kilo Cloud Reviewed by gpt-5.4-20260305 · 354,377 tokens |
|
Heads up: this PR now has merge conflicts after recent upstream refactoring of session/index.ts. I'll rebase and update shortly. |
…lo-Org#9168) When reasoningTokens exceeds outputTokens (due to provider SDK inconsistencies), the subtraction produces a negative output token count. Wrap with Math.max(0, ...) to ensure non-negative values. Rebased onto refactored session module structure (session.ts extracted from index.ts).
4241435 to
59a3837
Compare
|
Rebased onto latest main. The session module was refactored (logic extracted from |
Summary
Fixes #9168 — prevents negative
outputtoken counts when a provider reportsreasoningTokens > outputTokens.Problem
getUsage()computesoutput: outputTokens - reasoningTokens, assuming the AI SDK v6 convention thatoutputTokensincludesreasoningTokens. Some providers (e.g. Moonshot kimi-k2.5 via the Kilo gateway) violate this invariant, producing negative values that propagate into the TUI, VS Code extension, session exports, and lifetime stats.Changes
packages/opencode/src/session/index.ts: Wrap the subtraction withMath.max(0, ...)to clamp negative output token counts to zero.reasoningTokens > outputTokensto help track how often this provider-side inconsistency occurs.Impact
stats.tsno longer biased lowTesting
Session.getUsagefunction does not currently have dedicated unit tests; the fix is a one-line defensive clamp with well-understood behavior