Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(codex): MUL-7374 avoid double-counting reasoning output tokens (#8416)

importcppcf52ba33ccf9
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index 4dd1a11fe6..dbe52f282e 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -209,6 +209,10 @@ type Message struct {
}
// TokenUsage tracks token consumption for a single model.
+// Its four token counts are mutually exclusive: InputTokens excludes cache
+// reads and writes, and OutputTokens already includes reasoning/thinking.
+// Provider-specific breakdowns must not be added to those totals again.
+// Zero counters alone do not establish that the provider reported complete usage.
type TokenUsage struct {
InputTokens int64
OutputTokens int64
diff --git a/server/pkg/agent/claude_usage_test.go b/server/pkg/agent/claude_usage_test.go
index d34fea6172..fe91d06e52 100644
--- a/server/pkg/agent/claude_usage_test.go
+++ b/server/pkg/agent/claude_usage_test.go
@@ -47,7 +47,11 @@ func TestClaudeExecuteFallbackUsage(t *testing.T) {
return mustMarshal(t, map[string]any{
"type": "assistant", "parent_tool_use_id": parent,
"message": map[string]any{"id": id, "role": "assistant", "model": model, "usage": u,
- "content": []any{map[string]any{"type": "text", "text": "visible text"}, map[string]any{"type": "tool_use", "id": fmt.Sprintf("tool_%d", blockIndex), "name": "Read", "input": map[string]string{"file_path": "fixture.txt"}}}},
+ "content": []any{
+ map[string]any{"type": "thinking", "thinking": "fixture thinking", "signature": "fixture-signature"},
+ map[string]any{"type": "text", "text": "visible text"},
+ map[string]any{"type": "tool_use", "id": fmt.Sprintf("tool_%d", blockIndex), "name": "Read", "input": map[string]string{"file_path": "fixture.txt"}},
+ }},
})
}
terminal := func(failed bool, usage any, modelUsage any) json.RawMessage {
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index 9239085a89..18b82bbf75 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -3561,10 +3561,11 @@ func (c *codexClient) updateThreadTokenUsage(params map[string]any) {
}
c.usageTotal = total
c.usageTotalSet = true
- c.usage.InputTokens += codexPlainInputTokens(delta.InputTokens, delta.CachedInputTokens, delta.CacheWriteInputTokens)
- c.usage.OutputTokens += delta.OutputTokens + delta.ReasoningOutputTokens
- c.usage.CacheReadTokens += delta.CachedInputTokens
- c.usage.CacheWriteTokens += delta.CacheWriteInputTokens
+ u := codexTokenUsage(delta)
+ c.usage.InputTokens += u.InputTokens
+ c.usage.OutputTokens += u.OutputTokens
+ c.usage.CacheReadTokens += u.CacheReadTokens
+ c.usage.CacheWriteTokens += u.CacheWriteTokens
c.usageMu.Unlock()
}
@@ -3835,6 +3836,19 @@ type codexRawTokenUsage struct {
ReasoningOutputTokens int64 `json:"reasoning_output_tokens"`
}
+// codexTokenUsage converts either event or rollout counters to the shared
+// TokenUsage contract. Codex input includes cache reads/writes; its output
+// already includes reasoning_output_tokens, which is only a breakdown.
+func codexTokenUsage(raw codexRawTokenUsage) TokenUsage {
+ u := normalizeCodexRawTokenUsage(raw)
+ return TokenUsage{
+ InputTokens: codexPlainInputTokens(u.InputTokens, u.CachedInputTokens, u.CacheWriteInputTokens),
+ OutputTokens: u.OutputTokens,
+ CacheReadTokens: u.CachedInputTokens,
+ CacheWriteTokens: u.CacheWriteInputTokens,
+ }
+}
+
// codexSessionTokenCount represents a token_count event in Codex JSONL.
type codexSessionTokenCount struct {
Timestamp time.Time `json:"timestamp"`
@@ -3932,14 +3946,7 @@ func parseCodexSessionFileSince(path string, startTime time.Time, resumed bool)
if !finalUsageFound {
return nil
}
- cacheReadTokens := finalUsage.CachedInputTokens
- cacheWriteTokens := finalUsage.CacheWriteInputTokens
- result.usage = TokenUsage{
- InputTokens: codexPlainInputTokens(finalUsage.InputTokens, cacheReadTokens, cacheWriteTokens),
- OutputTokens: finalUsage.OutputTokens + finalUsage.ReasoningOutputTokens,
- CacheReadTokens: cacheReadTokens,
- CacheWriteTokens: cacheWriteTokens,
- }
+ result.usage = codexTokenUsage(finalUsage)
return &result
}
diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.go
index e4e8a9998f..922cb7167b 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -921,8 +921,8 @@ func TestParseCodexSessionFileSubtractsCachedInput(t *testing.T) {
if got.usage.CacheReadTokens != 300 {
t.Fatalf("cache read tokens = %d, want 300", got.usage.CacheReadTokens)
}
- if got.usage.OutputTokens != 50 {
- t.Fatalf("output tokens = %d, want 50", got.usage.OutputTokens)
+ if got.usage.OutputTokens != 40 {
+ t.Fatalf("output tokens = %d, want 40 (including reasoning)", got.usage.OutputTokens)
}
}
@@ -1008,7 +1008,7 @@ func TestScanCodexSessionUsageSubtractsResumeBaseline(t *testing.T) {
}
// total_token_usage is cumulative for the resumed Codex session. This task
// should report only the delta after startTime, not the whole session total.
- want := TokenUsage{InputTokens: 100, OutputTokens: 65, CacheReadTokens: 700}
+ want := TokenUsage{InputTokens: 100, OutputTokens: 50, CacheReadTokens: 700}
if got.usage != want {
t.Fatalf("usage = %+v, want resumed-task delta %+v", got.usage, want)
}
@@ -3428,7 +3428,7 @@ func TestCodexThreadTokenUsageUpdatedAccumulatesCurrentTurnResponses(t *testing.
c.usageMu.Lock()
got := c.usage
c.usageMu.Unlock()
- want := (TokenUsage{InputTokens: 160, OutputTokens: 35, CacheReadTokens: 80, CacheWriteTokens: 10})
+ want := (TokenUsage{InputTokens: 160, OutputTokens: 30, CacheReadTokens: 80, CacheWriteTokens: 10})
if got != want {
t.Fatalf("multi-response usage = %+v, want %+v", got, want)
}
diff --git a/server/pkg/agent/usage_contract_test.go b/server/pkg/agent/usage_contract_test.go
new file mode 100644
index 0000000000..3a459eba4e
--- /dev/null
+++ b/server/pkg/agent/usage_contract_test.go
@@ -0,0 +1,90 @@
+package agent
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+// Provider fields do not share an input-token convention, but their normalized
+// usage must share the TokenUsage contract. Reasoning is already in output.
+// https://developers.openai.com/api/docs/guides/reasoning#managing-the-context-window
+// https://platform.claude.com/docs/en/build-with-claude/prompt-caching#tracking-cache-performance
+func TestProviderTokenUsageContract(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ input int64 // Codex's inclusive input count.
+ reasoning int64 // A subset of output, not an additional charge.
+ want TokenUsage
+ }{
+ {"mixed_cache_and_reasoning", 100, 5, TokenUsage{InputTokens: 20, OutputTokens: 10, CacheReadTokens: 30, CacheWriteTokens: 50}},
+ {"uncached_without_reasoning", 100, 0, TokenUsage{InputTokens: 100, OutputTokens: 10}},
+ {"all_output_is_reasoning", 100, 10, TokenUsage{OutputTokens: 10, CacheReadTokens: 100}},
+ {"cache_only", 100, 0, TokenUsage{CacheReadTokens: 40, CacheWriteTokens: 60}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ for _, source := range []string{"codex_event", "codex_rollout", "claude_model_totals", "claude_main_total"} {
+ t.Run(source, func(t *testing.T) {
+ var got TokenUsage
+ switch source {
+ case "codex_event":
+ c := &codexClient{}
+ c.setActiveTurnID("turn-current")
+ usage := map[string]any{
+ "inputTokens": float64(tc.input), "cachedInputTokens": float64(tc.want.CacheReadTokens),
+ "cacheWriteInputTokens": float64(tc.want.CacheWriteTokens), "outputTokens": float64(tc.want.OutputTokens),
+ "reasoningOutputTokens": float64(tc.reasoning), "totalTokens": float64(tc.input + tc.want.OutputTokens),
+ }
+ c.updateThreadTokenUsage(codexThreadTokenUsageParams("thread-1", "turn-current", usage, usage))
+ got = c.usage
+ case "codex_rollout":
+ data := mustMarshal(t, map[string]any{
+ "type": "event_msg", "payload": map[string]any{
+ "type": "token_count", "info": map[string]any{
+ "total_token_usage": map[string]any{
+ "input_tokens": tc.input, "cached_input_tokens": tc.want.CacheReadTokens,
+ "cache_write_input_tokens": tc.want.CacheWriteTokens, "output_tokens": tc.want.OutputTokens,
+ "reasoning_output_tokens": tc.reasoning, "total_tokens": tc.input + tc.want.OutputTokens,
+ },
+ },
+ },
+ })
+ path := filepath.Join(t.TempDir(), "rollout.jsonl")
+ if err := os.WriteFile(path, append(data, '\n'), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ usage := parseCodexSessionFile(path)
+ if usage == nil {
+ t.Fatal("missing rollout usage")
+ }
+ got = usage.usage
+ default:
+ // Claude's input already excludes both cache buckets. Its
+ // final output total already includes thinking.
+ msg := map[string]any{"type": "result", "model": "claude-sonnet-4-6"}
+ if source == "claude_model_totals" {
+ msg["modelUsage"] = map[string]any{"claude-sonnet-4-6": map[string]any{
+ "inputTokens": tc.want.InputTokens, "outputTokens": tc.want.OutputTokens,
+ "cacheReadInputTokens": tc.want.CacheReadTokens, "cacheCreationInputTokens": tc.want.CacheWriteTokens,
+ }}
+ } else {
+ msg["usage"] = map[string]any{
+ "input_tokens": tc.want.InputTokens, "output_tokens": tc.want.OutputTokens,
+ "cache_read_input_tokens": tc.want.CacheReadTokens, "cache_creation_input_tokens": tc.want.CacheWriteTokens,
+ }
+ }
+ var decoded claudeSDKMessage
+ if err := json.Unmarshal(mustMarshal(t, msg), &decoded); err != nil {
+ t.Fatal(err)
+ }
+ got = claudeResultUsage(decoded, "claude-sonnet-4-6")["claude-sonnet-4-6"]
+ }
+ if got != tc.want {
+ t.Fatalf("normalized usage = %+v, want %+v (reasoning is included in output)", got, tc.want)
+ }
+ })
+ }
+ })
+ }
+}