Skip to content

fix(#9228): sum Claude turns across result events - #9814

Merged
waynesun09 merged 2 commits into
fullsend-ai:mainfrom
AshwinUgale:fix/9228-claude-num-turns
Dec 3, 2026
Merged

waynesun09 merged 2 commits into
fullsend-ai:mainfrom
AshwinUgale:fix/9228-claude-num-turns

Conversation

@AshwinUgale

@AshwinUgale AshwinUgale commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Claude Code writes another result event each time a background task resumes a finished session. num_turns covers only that segment, but fullsend kept the last one, so metrics.json and fullsend.num_turns undercounted.

Related Issue

Part of #9228. The single "→ Result" log block is left for a follow-up.

Changes

  • parseClaudeStream totals num_turns, so each ResultEvent carries the turns so far. recordClaudeMetrics stays last-wins, which also works with fix(#6806): capture num_turns from incomplete Claude streams #7687.
  • Cost and modelUsage are already running totals and are unchanged.
  • The log still prints one block per result, but turns now rise to the total.

Testing

  • make lint passes (stage changes first, then run): not run locally; go vet and gofmt are clean

  • Tests added/updated for new or modified logic

  • Replayed 355 Claude streams from the agents nightlies (Claude Code 2.1.306): 11 change, all review runs, from 2–11 turns to 23–30. Every other metric is identical.

  • New test with one of those runs' turn counts; the existing two-result test now checks turns. Both fail without the fix.

  • 53 internal/runtime tests fail under WSL here, all of which fail without the fix too.

Not covered

  • Results without modelUsage fall back to usage, which is per segment on Claude Code 2.1.306, the image pin (2.1.334 derives it from modelUsage). All 11 runs had modelUsage.
  • No resumed or steered sessions were in the data.

Checklist

  • PR title follows Conventional Commits (correct type, ! for breaking changes)
  • Commits are signed off (DCO) — human and human-directed agent sessions only
  • I wrote this contribution myself and can explain all changes in it

Signed-off-by: Ashwin Govind Ugale <ugaleashwin@gmail.com>
@AshwinUgale
AshwinUgale requested a review from a team as a code owner November 23, 2026 19:04
@qodo-code-review

qodo-code-review Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Sum Claude turns across result events

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 10-20 Minutes

Grey Divider

AI Description

• Sum segment-level Claude turns so resumed sessions report accurate run totals.
• Preserve last-result cost and model usage, which are already session totals.
• Test cumulative result events and final metrics across multiple results.
Merge Risk 🟡 Medium

Blast radius 🟢 Low 💥 1 capability

  • 1 affected end-to-end capability after fault-specific containment; implementation boundaries do not widen its functional scope.
  • The parser, RunMetrics record, cross-iteration aggregate, metrics artifact, and telemetry all implement one bounded outcome: reporting usage for a Claude execution.
  • The propagation path connects the changed parser value to that single accounting behavior rather than to independent user capabilities.
Behavioral complexity 🟡 Medium 🧩 Interacting branches

  • Before: one terminal result normally supplied the run turn count directly.
  • After: multiple result events update totalTurns and overwrite the emitted snapshot.
  • New correctness condition: segment-local counts must be summed exactly once while cumulative cost and usage remain last-wins across resumed, steered, retried, or duplicate events.
Potential damage 🟡 Medium 🩹 Incorrect results

  • A wrong accumulated turn count can appear in per-run metrics, metrics.json, aggregate run metrics, and related telemetry.
  • It does not change the agent task result, persistent application state, or external side effects.
  • The assessment uses the equal business-importance baseline.
  • Reverting the parser restores correct accounting for future runs, but already emitted records and telemetry remain incorrect and require regeneration, manual correction, or rerunning the affected execution.
Assessed commit 0da871f
Diagram

graph TD
  Stream["Claude stream"] --> Parser["Stream parser"] --> Turns["Turn accumulator"] --> Results["Result events"] --> Metrics["Run metrics"]
  Results --> Renderer["Progress renderer"]
  Parser -->|"session totals"| Results
Loading
High-Level Assessment

Accumulating turns in the parser is the best fit: both emitted result events and recorded metrics become accurate without summing already-cumulative cost or model usage. Accumulating only in the metrics recorder would leave progress output and other event consumers with incorrect turns.

Files changed (3) +65 / -7

Bug fix (1) +17 / -6
claude_progress.goAccumulate turns before emitting Claude results +17/-6

Accumulate turns before emitting Claude results

• Sums segment-level num_turns across result events so each emitted event carries turns so far. Clarifies why metric recording still replaces cost and model usage with the latest result.

internal/runtime/claude_progress.go

Tests (1) +44 / -0
claude_progress_test.goCover cumulative turns across multiple results +44/-0

Cover cumulative turns across multiple results

• Adds a six-result regression test for intermediate turns and final metrics. Extends the existing two-result test to check turn accumulation without double-counting model usage.

internal/runtime/claude_progress_test.go

Documentation (1) +4 / -1
event.goClarify result-event semantics +4/-1

Clarify result-event semantics

• Documents that Claude can emit multiple result events, with turns accumulated through each event and token totals conditional on modelUsage.

internal/runtime/event.go

@qodo-code-review

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review

Grey Divider

Tip of the day
💡 Did you know, you can keep summaries lean with Findings visible per group, which tucks the rest behind a View link

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@codecov

codecov Bot commented Nov 23, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@AshwinUgale

Copy link
Copy Markdown
Member Author

/fs-review

@fullsend-ai-review

fullsend-ai-review Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 7:51 PM UTC · Completed 7:57 PM UTC

Commit: e286b31 · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $0.90

@fullsend-ai-review fullsend-ai-review Bot added the risk/moderate PR risk: moderate label Nov 23, 2026
@fullsend-ai-review

Copy link
Copy Markdown

Risk Assessment: moderate (2/5)

Details

Small, focused telemetry bug fix with test coverage matching issue scope, though moderate risk is driven by high regression history and change coupling in touched runtime files.

@fullsend-ai-review

fullsend-ai-review Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Looks good to me

Previous run

<!-- fullsend:review-findings-v2:eyJ2ZXJzaW9uIjoyLCJhY3Rpb24iOiJhcHByb3ZlIiwiZmluZGluZ3MiOltdfQ== -->

Looks good to me

fullsend-ai-review[bot]

This comment was marked as outdated.

@fullsend-ai-review fullsend-ai-review Bot added the ready-for-merge All reviewers approved — ready to merge label Nov 23, 2026
@AshwinUgale

Copy link
Copy Markdown
Member Author

@dhshah13 could you take a look when you have a moment? It's a small fix in claude_progress.go for #9228: num_turns is summed across result events instead of taken from the last one. CI is green and the review bot has approved.

@jflowers jflowers left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Council Review: fix(#9228): sum Claude turns across result events

Council verdict: APPROVE WITH ADVISORIES — 6 reviewer runs (4 APPROVE, 2 APPROVE WITH ADVISORIES); findings: 0 CRITICAL, 0 HIGH, 1 MEDIUM, 1 LOW. Neither advisory blocks merge.

Summary

The totalTurns accumulator in parseClaudeStream fixes the num_turns undercount from #9228 with a minimal change that mirrors the existing totalReasoning pattern. Regression tests cover the summed-turns behavior (a six-result fixture from a live review run) and the no-double-counting invariants for cost and tokens, and the PR replays 355 real Claude streams showing the 11 affected runs rise to true totals with every other metric identical. CI is fully green, including codecov/patch. Local gates did not run (external fork PR, UNTRUSTED_HEAD); CI evidence covers them.

Findings

  • MEDIUM (test-coverage) internal/runtime/event.go:111 — the rewritten ResultEvent and resultEvent doc comments document no-modelUsage multi-result token semantics that no test verifies: both multi-result fixtures carry modelUsage. A table-driven no-modelUsage multi-result fixture would either verify the claim or expose it as wrong before it hardens into API documentation.
  • LOW (correctness) internal/runtime/claude_progress.go:273 — only num_turns receives running-total treatment; duration_ms/duration_api_ms and the usage fallback (results without modelUsage) keep last-value overwrite. The PR documents these as deliberate deferrals with no observed data in the 11 replayed streams; worth auditing in the follow-up that handles the single "→ Result" log block.

This review was generated by /uf.review-pr (AI-assisted).

Comment thread internal/runtime/event.go Resolved
Comment thread internal/runtime/claude_progress.go Resolved
Comment thread internal/runtime/claude_progress.go Resolved
…s hold for

The comments said a result's usage covers one segment. That holds for
Claude Code 2.1.306, the image pin: in the agents nightly streams usage
is per segment and for the top-level loop only. Claude Code 2.1.334
derives usage from modelUsage, a running total. The comments now name
both versions and say usage is kept last-wins, never summed.

A new test runs three results with no modelUsage, from a live 2.1.306
run, and checks that the turns are summed while the token counts are
the last result's, so a change that sums usage fails on either version.

Signed-off-by: Ashwin Govind Ugale <ugaleashwin@gmail.com>
@fullsend-ai-review

fullsend-ai-review Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 3:32 PM UTC · Completed 3:38 PM UTC

Commit: 0da871f · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $1.08

@fullsend-ai-review fullsend-ai-review Bot removed the ready-for-merge All reviewers approved — ready to merge label Dec 3, 2026
@fullsend-ai-review

Copy link
Copy Markdown

Risk Assessment: moderate (2/5)

Details

Focused telemetry bug fix with test coverage matching issue scope, with moderate risk driven by elevated regression history and change coupling in modified runtime files.

@fullsend-ai-review

fullsend-ai-review Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Looks good to me


Labels: PR changes the Claude runtime metrics parsing in internal/runtime.

@fullsend-ai-review
fullsend-ai-review Bot dismissed their stale review December 3, 2026 15:38

Superseded by updated review

@fullsend-ai-review fullsend-ai-review Bot added ready-for-merge All reviewers approved — ready to merge component/runner Agent runner behavior and lifecycle labels Dec 3, 2026

@jflowers jflowers left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: APPROVE

Light re-review since e286b31 (3 files, 54 lines); this supersedes my earlier review, which predates 0da871f.

from what I can tell, the fix is minimal: totalTurns mirrors the totalReasoning pattern beside it, and the follow-up commit resolves the earlier coverage gap without disturbing the running-total semantics.

Since e286b31

0da871f version-qualifies the usage semantics in the doc comments: 2.1.306 reports usage per segment for the top-level loop; 2.1.334 derives it from modelUsage, a running total. It also adds TestProgressParserMultiResultWithoutModelUsageKeepsLastUsage, a regression test built from a live 2.1.306 stream.

Prior findings

  • MEDIUM, test-coverage (internal/runtime/event.go:111): resolved. The new test, TestProgressParserMultiResultWithoutModelUsageKeepsLastUsage, now pins the contract the earlier round found untested: three results, num_turns 19/1/5 summed to 25; last usage kept (in=9, out=4661); cost 0.70; PerModelUsage nil. An implementation that summed usage would fail on either Claude Code version; the fixture discriminates.
  • LOW, correctness (internal/runtime/claude_progress.go:277): open, deferred on-thread. duration_ms and the usage fallback keep last-wins across multi-result streams. The single "→ Result" log block follow-up should settle it; one summary per stream makes each field's scope explicit.

Issue #9228

Two of three validation criteria covered: the multi-result fixture test sums num_turns, and cost and token totals stay last-wins with no double counting. The single "→ Result" log block on live runs stays deferred as follow-up.

Checks

CI is green at 0da871f: test, codecov/patch, semgrep, DCO, commit-lint, pr-title-lint, web, gateway-doc-configs, fork-pr, and the behaviour suites. Local gates did not run; the head comes from a fork whose author has read permission, so this review relies on CI evidence.

This review was generated by /uf.review-pr (AI-assisted).

Comment thread internal/runtime/claude_progress.go Resolved

@waynesun09 waynesun09 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approving 0da871f. Two-agent review of this head found nothing; go test ./internal/runtime/ -run 'Claude|Progress|Event|Usage|Turn|Result', go vet and gofmt pass locally, and CI is green.

@waynesun09
waynesun09 enabled auto-merge December 3, 2026 21:44
@waynesun09
waynesun09 added this pull request to the merge queue Dec 3, 2026
Merged via the queue into fullsend-ai:main with commit 2079dc1 Dec 3, 2026
112 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

component/runner Agent runner behavior and lifecycle ready-for-merge All reviewers approved — ready to merge risk/moderate PR risk: moderate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants