Repository navigation
fix(action): sum usage and num_turns across all result entries - #437
Merged
Merged
Conversation
When a session uses `Bash` with `run_in_background: true`, the SDK emits a second `type: "result"` entry on wakeup (origin.kind == "task-notification"). `usage.*` and `num_turns` are per-event in each result; only `total_cost_usd` is cumulative. Picking the last entry captured just the trailing turn's usage and turn count, so backgrounded sessions reported a few hundred output_tokens and 2-3 turns regardless of session length, while cost remained accurate (#302). Sum the per-event fields across all result entries; keep cost from the last. Verified against three captured execution-output.json files: single-result runs are unaffected; two-result runs that previously under-reported now produce totals consistent with the session JSONL's assistant-message counts.
Merged
max-sixty
added a commit
that referenced
this pull request
May 13, 2026
Bumps generator to 0.0.18. ## Headline Expose the `__TEND_DELETE__` sentinel so TOML overrides can reach RFC 7396 delete-key semantics — useful for dropping a generator-injected key (e.g. `on.schedule` from a scheduled workflow) while keeping the rest. Closes #439, thanks @jrdncstr for reporting. ## Other changes since 0.0.17 - fix(action): sum usage and num_turns across all result entries (#437) - diag(action): upload execution-output.json (#408) - fix(mention): run setup before PR checkout so stale PRs don't drop mentions (#391) - fix(running-in-ci): base skill worktree on default branch (#401) - install-tend: fix oauth-token.sh returning an invalid token on macOS (#398) - oauth-token.sh: don't tee the OAuth token to stderr (#421) - Skill hardening: bang-escape guidance, review-reviewers corruption scans, dedup rules, $GITHUB_RUN_ID requirement 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude <[email protected]>
This was referenced Aug 6, 2026
max-sixty
pushed a commit
that referenced
this pull request
Aug 11, 2026
#873) ## Problem The Claude action's `Token usage` step hardcoded an all-zeros `token-usage.json` whenever the stream-json carried no `type: "result"` entry. A cancelled session never emits one, and the step is `if: always()` — so it still ran, still uploaded the artifact, and still reported `turns=0, output_tokens=0, cost_usd=0` for a run that may have done dozens of turns and already posted its review. `tend-review` uses `cancel-in-progress: true`, so cancellation is routine rather than exotic, and everything reading `token-usage.json` (`token-report.sh`, the `review-reviewers` evidence gist, `review-runs`' per-window cost line) under-counted by the cancellation rate. The bias isn't constant either — it scales with push cadence, which is one of the axes `review-runs` compares windows along. This is distinct from #302 / #437, which were about taking the *last* result entry instead of summing across several. This is the *zero* result entries case. ## Solution Reconstruct the accounting from the session JSONL the step has already consolidated into `LOGS_DIR` — deduplicating `type: "assistant"` lines by `.message.id` and summing `.message.usage`. That file is uploaded for every repo, unlike the raw stream-json (preserved only on tend's own repo). **The reconstruction must read the session JSONL, not the stream-json**, even though both carry `type: "assistant"` events. Verified against real artifacts, the stream-json's assistant events are non-final (`stop_reason: null`): `usage.output_tokens` is the message-start placeholder, single digits against thousands. The input and cache fields, known at message start, do match — so summing the stream's events under-counts output by orders of magnitude while three of four fields look right. On run 31086697446 that filter yields `output_tokens=46` against a true 9406. Two secondary choices, both of which #871 explicitly left to judgement: - **`cost_usd: null`**, not `0`. Only `result.total_cost_usd` carries cost, and emitting `0` would repeat the reported bug one field down — a partial run looking free. Deriving it from a hardcoded per-model price table reproduces the reported cost to the cent, but pins price maintenance inside the action, so this leaves it unknown instead. - **A `partial: true` marker**, so consumers can tell "cancelled, partial accounting" from "ran and cost nothing". `token-report.sh` counts partial runs and labels its cost total a floor; the step summary renders cost as `unknown` and notes the reconstruction. `partial` is absent on the Codex harness's output, which is unaffected — consumers read it as `.partial // false`. The parsing moved into `shared/steps/compute-token-usage.sh` so pytest can cover both paths, matching how `mark-notification-read.sh` is tested. ## Testing Four tests in `generator/tests/test_shared_steps.py`, with fixtures mirroring the shapes observed in real artifacts. The reproduction (`test_token_usage_reconstructs_a_cancelled_session`) fails against the pre-fix logic with `output_tokens=0` and passes after. A companion test locks in that the fallback doesn't sum the stream-json's placeholder output, since that filter would produce a plausible-looking wrong number. Beyond the fixtures, the fallback was validated against five real uploaded artifacts by stripping the `result` event from each stream-json to simulate cancellation. It reproduces the result event's four token fields **and** `num_turns` exactly on all five: | Run | `result` event | Reconstructed | |---|---|---| | 31086697446 | `in 23, out 9406, cc 62655, cr 789006, turns 14` | identical | | 31070595950 | `in 31, out 6111, cc 15350, cr 1091736, turns 18` | identical | | 31080411940 | `in 25, out 8283, cc 71292, cr 895126, turns 16` | identical | | 31080436881 | `in 17, out 3501, cc 52293, cr 536771, turns 11` | identical | | 31083509937 | `in 21, out 4781, cc 14443, cr 731210, turns 13` | identical | That also confirms the `turns = (count of type:"user" lines) - 1` relation #871 flagged as empirical — it holds on the session JSONL, but not on the stream-json, where it is off by two on every session checked. Full generator suite passes (342 tests); `shellcheck` and `ruff` clean. --- Closes #871 — automated triage --------- Co-authored-by: tend-agent <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes #302. When a session uses
Bashwithrun_in_background: true, the SDK emits a secondtype: "result"entry on wakeup (origin.kind == "task-notification").usage.*andnum_turnsare per-event in each result; onlytotal_cost_usdis cumulative. The current jq filter picks the last result and captures just the trailing turn's usage and turn count, so backgrounded sessions report a few hundredoutput_tokensand 2-3turnsregardless of session length (cost stays correct because it's cumulative).The fix sums
input_tokens,output_tokens,cache_creation_input_tokens,cache_read_input_tokens, andnum_turnsacross everyresultentry;cost_usdcontinues to come from the last entry.Diagnosis from captured execution-output.json
Three runs from the
claude-session-logsartifact, post-#408:Per-result inspection of run 25710799595
The second entry is the post-background-wakeup turn. Its
usage.*only covers that one turn; itstotal_cost_usdis the running session total.Single-result runs are unaffected by the change —
sum == lastwhen length is 1.Follow-up
The diagnostic
cp "$EXECUTION_FILE" "$LOGS_DIR/claude-execution-output.json"block added in #408 is no longer needed and can be removed in a separate PR.Test plan
token-usage.jsonwithturnsandoutput_tokensproportional to session length rather than the 2-3 / few-hundred floor.run_in_background: true(e.g. tend-triage, tend-nightly) report the same numbers as before.