fix(pi): turn token usage counts cached tokens as input and stays per turn #40762 (GitHub #40758)
Mergedjuliusmarmingemerged 3 commits into
main fromrefs/pull/40758/headmerged by juliusmarminge View on GitHubPushed71d72ad
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:M
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- @@ -1016,10 +1031,17 @@1016- updatedAt: DateTime.formatIso(updatedAt),1017- };1031+ // Stats `tokens` are whole-session totals; the breakdown comes from the turn's last message.1032+ return { usedTokens, maxTokens, ...messageUsage, updatedAt: DateTime.formatIso(updatedAt) };10181033 };101910341020- const readTokenUsage = (fallbackUsedTokens: number | null, updatedAt: DateTime.Utc) =>1035+ const readTokenUsage = (turn: ActivePiTurn, updatedAt: DateTime.Utc) =>10211036 request({ type: "get_session_stats" }, 2_000).pipe(1022- Effect.map((stats) => tokenUsageFromStats(stats, fallbackUsedTokens, updatedAt)),1037+ Effect.map((stats) =>1038+ tokenUsageFromStats(1039+ stats,1040+ turn.latestCompactionAfterTokens,1041+ turn.lastMessageUsage,1042+ updatedAt,1043+ ),1044+ ),10231045 Effect.orElseSucceed(() => undefined),10241046 );10251047@@ -1010,13 +1031,11 @@1010- return {1011- usedTokens,1012- maxTokens,1013- ...(inputTokens === undefined ? {} : { inputTokens }),1014- ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }),1015- ...(outputTokens === undefined ? {} : { outputTokens }),1016- updatedAt: DateTime.formatIso(updatedAt),1017- };1031+ // Stats `tokens` are whole-session totals; the breakdown comes from the turn's last message.1032+ return { usedTokens, maxTokens, ...messageUsage, updatedAt: DateTime.formatIso(updatedAt) };10181033 };101910341020- const readTokenUsage = (fallbackUsedTokens: number | null, updatedAt: DateTime.Utc) =>1035+ const readTokenUsage = (turn: ActivePiTurn, updatedAt: DateTime.Utc) =>10211036 request({ type: "get_session_stats" }, 2_000).pipe(1022- Effect.map((stats) => tokenUsageFromStats(stats, fallbackUsedTokens, updatedAt)),1037+ Effect.map((stats) =>1038+ tokenUsageFromStats(1039+ stats,1040+ turn.latestCompactionAfterTokens,1041+ turn.lastMessageUsage,
juliusmarminge merged thisbcace07
juliusmarminge closed this
Sign in to join this conversation.
No actionable comments were generated in the recent review.
Walkthrough
The Pi adapter now uses message-level input, cached input, and output counts separately from session-level used and maximum token counts. It retains the latest message usage for live updates and turn completion. Tests cover reported usage and settled turn usage.
Changes: Pi token usage
packages/provider-pi/src/server/adapter.tspackages/provider-pi/src/server/adapter.ts,packages/provider-pi/src/server/adapter.test.ts,apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.tsEstimated code review effort: 2 (Simple) | ~10 minutes
Change: Bug fix
Merge Risk:
Low · up to
71d72Pi token usage reporting is now consistent, with cached input counted inside total input for both live and completed turns. In the rare case where Pi reports usage only on the final message, a completed turn can show a missing or earlier-message token breakdown. This is a minor, bounded issue that the owner can address in a follow-up or before merge.
Pre-merge checks:
4
#40747requires that Pi cachedInputTokens be a subset of inputTokens, and that message-level usage not be mixed with session-wide totals. At head 71d72ad, piMessageTokenUsage in packages/provide…#40747and gives the reproduction steps, before and after results, and test runs. The template asks fo…Full details: Title check
Explanation
The title names the Pi turn token usage fix: cached tokens now count as input, and usage is per turn. It matches the main change in the adapter and the fixture assertion. The wording is long and somewhat awkward, but the primary change is clear.
Full details: Linked Issues check
Explanation
Issue
#40747requires that Pi cachedInputTokens be a subset of inputTokens, and that message-level usage not be mixed with session-wide totals. At head 71d72ad, piMessageTokenUsage in packages/provider-pi/src/server/adapter.ts sets inputTokens to input + cacheRead + cacheWrite and cachedInputTokens to cacheRead. The live update in reportLiveUsage spreads turn.lastMessageUsage. The completed turn in tokenUsageFromStats also uses turn.lastMessageUsage. get_session_stats now supplies only usedTokens and maxTokens. The session tokens.input and tokens.cacheRead overwrite is removed. The added test in adapter.test.ts checks inputTokens 50,668 and cachedInputTokens 40,101 for both the live and the completed turn. I did not rerun the tests. Residual gap: if a message has cacheRead or cacheWrite but no input, inputTokens is omitted. The issue does not cover this case.Full details: Out of Scope Changes check
Explanation
The whole-PR diff for adapter.ts changes only Pi token-usage handling. It adds PiMessageTokenUsage, the lastMessageUsage field on ActivePiTurn, the piMessageTokenUsage helper, the tokenUsageFromStats and readTokenUsage signature changes, and the initialization of lastMessageUsage. Each change maps to the live or completed-turn usage requirement in
#40747. The whole-PR diff for adapter.test.ts adds one test for the same behavior. The fixture change in pi_output.ts, described in the summary, updates the replay assertion to the new usage rules. It supports the same change. The PR description's evidence and attribution sections are non-coding and do not affect this result.Full details: Description check
Explanation
The description covers the problem, the change, scope, and verification in detail. It links issue
#40747and gives the reproduction steps, before and after results, and test runs. The template asks for a conventional commit title, and the description does not include one. The Scope section is covered by the linked issue. Verification is thorough, with specific test counts and captured evidence. Some sections are long and include material outside the template, such as the 'Not in this change' and 'Who did the work' sections. These do not block the review. The description is mostly complete, so the check passes.Finishing Touches
Generate unit tests (beta)
318ca116-4f96-40f9-be26-53fa7f10278cReviewing files that changed from the base of the PR and between fb0e7c1e69a9be3c087b6d070ac1975d9d8daac1 and 71d72ad28b5a2a23556f6cf1dd10672cd2054936.
apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.tsIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.