Skip to content

[Bug]: session.total_tokens accumulates full-context tokens across steps, producing inflated values #150

Open

Description

@enternal111

Description

The session.total_tokens attribute on the session span reports the sum of every LLM step's total tokens instead of the conversation's current context size.

Each step's d.tokens from session.step.ended represents the full conversation context for that call (input + output + reasoning + cache). accumulateTotals in src/handlers/step.ts adds these across steps:

tokens: existing.tokens + tokens,

For a session with 10 LLM calls averaging ~12M tokens each, session.total_tokens reports ~120M instead of ~12M.

Additionally, session.total_cost_usd and session.token.total histogram are affected the same way.

Expected behavior

session.total_tokens should reflect the latest known cumulative usage (from session.usage.updated when available, or the last step's value as fallback), not the arithmetic sum of per-step context sizes.

Observed in

OpenCode 2.2.7, plugin 2.1.0, span attribute session.total_tokens = 115,218,555 for a ~12M token conversation.

Suggested fix

In accumulateTotals (src/handlers/step.ts), replace the running sum with the latest value:

tokens: tokens > 0 ? tokens : existing.tokens,
cost: existing.cost + cost,

handleUsageUpdated in session.ts already provides the authoritative cumulative replacement via session.usage.updated events.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions