Skip to content

fix(action): sum usage and num_turns across all result entries - #437

Merged
max-sixty merged 1 commit into
mainfrom
fix/302-sum-result-usage
May 12, 2026
Merged

max-sixty merged 1 commit into
mainfrom
fix/302-sum-result-usage

Conversation

@tend-agent

Copy link
Copy Markdown
Collaborator

Summary

Fixes #302. 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. 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 hundred output_tokens and 2-3 turns regardless 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, and num_turns across every result entry; cost_usd continues to come from the last entry.

Diagnosis from captured execution-output.json

Three runs from the claude-session-logs artifact, post-#408:

Run result entries Before (turns / output) After (turns / output) cost assistant entries in JSONL
25710799595 (tend-review) 2 2 / 182 19 / 4373 $1.04 26
25707130169 (tend-review) 2 2 / 203 41 / 20886 $2.36 56
25738925390 (tend-mention, no background) 1 6 / 1028 6 / 1028 $0.29 —
Per-result inspection of run 25710799595
[
  {"num_turns": 17, "output_tokens": 4191, "total_cost_usd": 0.967,  "origin": null},
  {"num_turns":  2, "output_tokens":  182, "total_cost_usd": 1.037,  "origin": {"kind": "task-notification"}}
]

The second entry is the post-background-wakeup turn. Its usage.* only covers that one turn; its total_cost_usd is the running session total.

Single-result runs are unaffected by the change — sum == last when 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

  • After merge, watch a tend-review or tend-mention run that polls CI in the background land a token-usage.json with turns and output_tokens proportional to session length rather than the 2-3 / few-hundred floor.
  • Confirm runs without run_in_background: true (e.g. tend-triage, tend-nightly) report the same numbers as before.

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.
@max-sixty
max-sixty merged commit 9c675d2 into main May 12, 2026
4 checks passed
@max-sixty
max-sixty deleted the fix/302-sum-result-usage branch May 12, 2026 15:12
@max-sixty max-sixty mentioned this pull request May 13, 2026
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]>
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

token-usage.json under-reports turns and output_tokens when session uses run_in_background Bash

2 participants