Skip to content

Bug: Message handlers accumulate tokens onto session, risking double-counted totals #32

@Shahfarzane

Description

@Shahfarzane

Bug

messages.upsert and messages.batchUpsert accumulate per-message promptTokens/completionTokens onto the session record each time a new message is inserted. Since session-level sync (sessions.upsert) already writes these values as authoritative absolute totals, the message handler accumulation can result in inflated (double-counted) token values.

How it happens

  1. Session sync sets session.promptTokens = 50000 (authoritative value from the CLI)
  2. Message sync inserts messages, and for each new message does:
    newPromptTokens = session.promptTokens + message.promptTokens
    
  3. After all messages sync, the session's token total becomes 50000 + sum(all_message_prompt_tokens) — roughly 2x the real value.

Current behavior

In convex/messages.ts, both upsert (line ~177) and batchUpsert (line ~413) accumulate per-message tokens:

const newPromptTokens = sessionPromptTokens + (args.promptTokens || 0);
const newCompletionTokens = sessionCompletionTokens + (args.completionTokens || 0);
sessionUpdate.promptTokens = newPromptTokens;

Expected behavior

Message handlers should not modify session token fields. Session tokens should be set exclusively by session-level sync, which receives the authoritative totals from the CLI source. Message handlers should only update messageCount and searchableText.

Impact

  • Session token totals displayed in the dashboard, sidebar, and charts may show inflated values
  • Analytics aggregations (which sum session-level tokens) would also be affected
  • Currently mitigated by the fact that most sync plugins don't send per-message token data, but the code path exists and would double-count if they do

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions