Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/cli/run.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ depend on the process cwd.
| `override_source` | Where `requested_model` came from (`--model flag`, `FULLSEND_MODEL`, `FULLSEND_PI_MODEL`, `FULLSEND_CODEX_MODEL`, `<config path> agents.<name>`, `harness`, `default`), suffixed `, remapped by <config path> models.aliases` when a per-repo alias override applied to it |
| `runtime_source` | Where `requested_runtime` came from (`--runtime flag`, `FULLSEND_RUNTIME`, the config file path — suffixed ` agents.<name>` when the agent's entry decided — or `default (config not found)`) |
| `total_cost_usd` | Total inference cost in USD, as reported by the runtime (raw floating-point aggregate across all iterations; no fullsend-side pricing-table fallback). See [Cost data contract](../guides/infrastructure/distributed-tracing.md#cost-data-contract) |
| `num_turns` | Number of conversation turns |
| `num_turns` | Number of conversation turns. Claude Code takes this from the terminal result event when the process completes normally; if the stream ends without that event (killed or crashed process), the runner counts `message_start` events instead. Dollar cost has no equivalent fallback — see [Cost data contract](../guides/infrastructure/distributed-tracing.md#cost-data-contract) |
| `iterations` | Number of agent iterations run; an iteration killed at the budget is not retried (see [Budget and deadline](#budget-and-deadline)) |
| `per_model_usage` | Per-model-spec breakdown, present only when a runtime reports one (today: `pi` with the `Agent` tool enabled). See below |

Expand Down
4 changes: 2 additions & 2 deletions internal/cli/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -3936,8 +3936,8 @@ func transcriptErrorMessage(te agentruntime.TranscriptError) string {
// NOTE: TotalCostUSD will be zero in the persisted metrics because dollar
// cost is only available from the terminal ResultEvent, which a cancelled
// run never emits. Token counts (input, output, cache_read, cache_creation)
// are captured via the deferred TokensEvent and will be non-zero. See #6936
// for background.
// and NumTurns are captured via the deferred TokensEvent and will be
// non-zero when the stream produced work. See #6936 and #6806.
//
// cancelled is false when ctx is still live, in which case the caller's
// normal control flow continues unchanged; the other return values are
Expand Down
16 changes: 10 additions & 6 deletions internal/cli/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5152,12 +5152,14 @@ func TestAggregateRunMetrics_PartialCancelledRun(t *testing.T) {
var agg aggregateMetrics

// Simulate a cancelled run: metrics populated via TokensEvent (no
// ResultEvent, so NumTurns/TotalCostUSD stay zero).
// ResultEvent, so TotalCostUSD stays zero). NumTurns is counted from
// message_start and carried on TokensEvent (#6806).
m := agentruntime.RunMetrics{
InputTokens: 599,
OutputTokens: 119,
CacheCreationInputTokens: 148_943,
CacheReadInputTokens: 583_298,
NumTurns: 3,
Model: "claude-opus-4-6",
}
m.ToolCalls.Store(10)
Expand All @@ -5182,11 +5184,11 @@ func TestAggregateRunMetrics_PartialCancelledRun(t *testing.T) {
if agg.Model != "claude-opus-4-6" {
t.Errorf("model = %q, want claude-opus-4-6", agg.Model)
}
if agg.NumTurns != 0 {
t.Errorf("num_turns = %d, want 0 (cancelled run has no ResultEvent)", agg.NumTurns)
if agg.NumTurns != 3 {
t.Errorf("num_turns = %d, want 3 (TokensEvent carries turns when ResultEvent is missing)", agg.NumTurns)
}
if agg.TotalCostUSD != 0 {
t.Errorf("total_cost_usd = %f, want 0 (cancelled run has no ResultEvent)", agg.TotalCostUSD)
t.Errorf("total_cost_usd = %f, want 0 (dollar cost is only on ResultEvent)", agg.TotalCostUSD)
}
}

Expand All @@ -5213,11 +5215,13 @@ func TestAggregateRunMetrics_MultiIterationCancel(t *testing.T) {
aggregateRunMetrics(&agg, &m1, 1)

// Iteration 2: cancelled — TokensEvent only (no ResultEvent).
// NumTurns is still counted from message_start (#6806); cost is not.
m2 := agentruntime.RunMetrics{
InputTokens: 599,
OutputTokens: 119,
CacheCreationInputTokens: 148_943,
CacheReadInputTokens: 583_298,
NumTurns: 2,
Model: "claude-opus-4-6",
}
m2.ToolCalls.Store(3)
Expand All @@ -5241,8 +5245,8 @@ func TestAggregateRunMetrics_MultiIterationCancel(t *testing.T) {
if agg.TotalCostUSD != 0.42 {
t.Errorf("total_cost_usd = %f, want 0.42", agg.TotalCostUSD)
}
if agg.NumTurns != 5 {
t.Errorf("num_turns = %d, want 5 (cancelled iteration contributes zero turns)", agg.NumTurns)
if agg.NumTurns != 7 {
t.Errorf("num_turns = %d, want 7 (cancelled iteration still contributes TokensEvent turns)", agg.NumTurns)
}
if agg.ToolCalls != 11 {
t.Errorf("tool_calls = %d, want 11", agg.ToolCalls)
Expand Down
26 changes: 1 addition & 25 deletions internal/runtime/claude.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,31 +163,7 @@ func (ClaudeRuntime) Run(ctx context.Context, params RunParams, printer *ui.Prin
// Always wrap handler to capture metrics regardless of custom/default path.
innerHandler := handler
handler = func(evt AgentEvent) {
switch e := evt.(type) {
case InitEvent:
if metrics.Model == "" {
metrics.Model = e.Model
}
case TokensEvent:
// Capture cumulative token usage from the stream so cancelled
// runs (no ResultEvent) retain non-zero telemetry (#6905).
metrics.InputTokens = e.InputTokens
metrics.OutputTokens = e.OutputTokens
metrics.CacheReadInputTokens = e.CacheRead
metrics.CacheCreationInputTokens = e.CacheWrite
case ResultEvent:
// Authoritative totals from the terminal result event overwrite
// the incremental snapshot.
metrics.NumTurns = e.NumTurns
metrics.TotalCostUSD = e.TotalCostUSD
metrics.InputTokens = e.InputTokens
metrics.OutputTokens = e.OutputTokens
metrics.ReasoningTokens = e.ReasoningTokens
metrics.CacheCreationInputTokens = e.CacheCreationInputTokens
metrics.CacheReadInputTokens = e.CacheReadInputTokens
case ToolUseEvent:
metrics.ToolCalls.Add(1)
}
applyClaudeMetrics(metrics, evt)
innerHandler(evt)
}

Expand Down
70 changes: 46 additions & 24 deletions internal/runtime/claude_progress.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,12 +161,15 @@ func parseClaudeStream(r io.Reader, onEvent func(AgentEvent)) error {
cumulativeCacheWrite int
seenResult bool
totalReasoning int // accumulated thinking tokens across all messages (for ResultEvent)
numTurns int // message_start count; carried on TokensEvent (#6806)
lastEmittedTurns int
)

// Emit a final cumulative TokensEvent when the stream ends without
// a ResultEvent (cancelled/killed run) and the cumulative total
// exceeds the last emitted snapshot. The deferred call covers
// every exit path: EOF, read error, and normal return.
// exceeds the last emitted snapshot, or turns arrived after the
// last snapshot. The deferred call covers every exit path: EOF,
// read error, and normal return.
defer func() {
if seenResult {
return
Expand All @@ -176,12 +179,13 @@ func parseClaudeStream(r io.Reader, onEvent func(AgentEvent)) error {
finalCacheRead := cumulativeCacheRead + totalCacheRead
finalCacheWrite := cumulativeCacheWrite + totalCacheWrite
total := finalInput + finalOutput + finalCacheRead + finalCacheWrite
if total > lastEmittedTotal {
if total > lastEmittedTotal || numTurns > lastEmittedTurns {
onEvent(TokensEvent{
InputTokens: finalInput,
OutputTokens: finalOutput,
CacheRead: finalCacheRead,
CacheWrite: finalCacheWrite,
NumTurns: numTurns,
})
}
}()
Expand Down Expand Up @@ -313,6 +317,7 @@ func parseClaudeStream(r io.Reader, onEvent func(AgentEvent)) error {
})

case "message_start":
numTurns++
var msg struct {
Message struct {
Usage struct {
Expand Down Expand Up @@ -354,12 +359,14 @@ func parseClaudeStream(r io.Reader, onEvent func(AgentEvent)) error {
msgReasoning + cumulativeCacheRead + totalCacheRead + cumulativeCacheWrite + totalCacheWrite
if total-lastEmittedTotal >= tokenThreshold {
lastEmittedTotal = total
lastEmittedTurns = numTurns
onEvent(TokensEvent{
InputTokens: cumulativeInput + totalInput,
OutputTokens: cumulativeOutput + totalOutput,
ReasoningTokens: msgReasoning,
CacheRead: cumulativeCacheRead + totalCacheRead,
CacheWrite: cumulativeCacheWrite + totalCacheWrite,
NumTurns: numTurns,
})
}
}
Expand Down Expand Up @@ -527,33 +534,48 @@ func toolResultText(raw json.RawMessage) (text string, partial bool) {
return strings.Join(texts, "\n"), partial
}

// applyClaudeMetrics folds a stream event into RunMetrics. TokensEvent is
// the incremental snapshot used when the process dies before the terminal
// result line (#6905, #6806); ResultEvent overwrites with authoritative
// totals. Dollar cost is ResultEvent-only: Claude Code does not report
// incremental cost, and fullsend does not estimate it from token counts.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[low] api-shape-pattern

applyClaudeMetrics dereferences metrics without a nil guard. Its counterpart applyCodexMetrics (internal/runtime/codex_progress.go:668-671) returns immediately on nil. This PR extracted the Claude fold into a package-level helper used from ClaudeRuntime.Run and progressParser; both still panic on a nil *RunMetrics. No current production or test call site passes nil (internal/cli/run.go uses var metrics ...; rt.Run(..., &metrics), and ClaudeRuntime{}.Run tests do the same), so this is a defensive consistency gap, not a live crash.

Suggested fix: Add if metrics == nil { return } at the start of applyClaudeMetrics to match applyCodexMetrics.

func applyClaudeMetrics(metrics *RunMetrics, evt AgentEvent) {
if metrics == nil {
return
}
switch e := evt.(type) {
case InitEvent:
if metrics.Model == "" {
metrics.Model = e.Model
}
case TokensEvent:
metrics.InputTokens = e.InputTokens
metrics.OutputTokens = e.OutputTokens
metrics.CacheReadInputTokens = e.CacheRead
metrics.CacheCreationInputTokens = e.CacheWrite
if e.NumTurns > 0 {
metrics.NumTurns = e.NumTurns
}
case ResultEvent:
metrics.NumTurns = e.NumTurns
metrics.TotalCostUSD = e.TotalCostUSD
metrics.InputTokens = e.InputTokens
metrics.OutputTokens = e.OutputTokens
metrics.ReasoningTokens = e.ReasoningTokens
metrics.CacheCreationInputTokens = e.CacheCreationInputTokens
metrics.CacheReadInputTokens = e.CacheReadInputTokens
case ToolUseEvent:
metrics.ToolCalls.Add(1)
}
}

// progressParser reads NDJSON from Claude Code's stream-json output and emits
// progress updates via the printer. It is a thin wrapper around parseClaudeStream
// that creates an EventRenderer and populates RunMetrics.
func progressParser(r io.Reader, printer *ui.Printer, metrics *RunMetrics) error {
renderer := NewEventRenderer(printer)
return parseClaudeStream(r, func(evt AgentEvent) {
switch e := evt.(type) {
case InitEvent:
if metrics.Model == "" {
metrics.Model = e.Model
}
case TokensEvent:
metrics.InputTokens = e.InputTokens
metrics.OutputTokens = e.OutputTokens
metrics.CacheReadInputTokens = e.CacheRead
metrics.CacheCreationInputTokens = e.CacheWrite
case ResultEvent:
metrics.NumTurns = e.NumTurns
metrics.TotalCostUSD = e.TotalCostUSD
metrics.InputTokens = e.InputTokens
metrics.OutputTokens = e.OutputTokens
metrics.ReasoningTokens = e.ReasoningTokens
metrics.CacheCreationInputTokens = e.CacheCreationInputTokens
metrics.CacheReadInputTokens = e.CacheReadInputTokens
case ToolUseEvent:
metrics.ToolCalls.Add(1)
}
applyClaudeMetrics(metrics, evt)
renderer.Handle(evt)
})
}
Expand Down
Loading
Loading