Skip to content

fix(ai): persist chat token usage on early stream close - #430

Merged
prvnsmpth merged 1 commit into
masterfrom
fix/chat-usage-tracking
Aug 31, 2026
Merged

fix(ai): persist chat token usage on early stream close#430
prvnsmpth merged 1 commit into
masterfrom
fix/chat-usage-tracking

Conversation

@prvnsmpth

@prvnsmpth prvnsmpth commented Aug 31, 2026

Copy link
Copy Markdown
Contributor
  • Move tracker.save() into a finally block in the chat streaming generator: the agent loop stops consuming the stream at message_stop, so the post-loop save never ran and every chat turn's usage was silently dropped from model_usage.
  • Extend the chat stream lifecycle integration test to assert the model_usage row lands with purpose=chat and the expected token counts; verified red (unfixed) / green (fixed).
  • Harden the chat fixture teardown against the fire-and-forget usage persist racing the FK-constrained chat delete.
  • Make the live Gemini/Anthropic provider API tests assert usage arrives on streamed message_delta events instead of only reporting it, so usage-delivery regressions fail CI.

…m at message_stop

The agent loop (stream_generator) stops consuming the provider stream as
soon as message_stop arrives, so event_stream_with_context_retry never
runs to exhaustion and its post-loop tracker.save() was dead code. Every
chat turn's captured usage was discarded: model_usage has no 'chat'
purpose rows even though title_generation and compaction records land
fine. Move save() into a finally block so it fires on generator close
(early break, error, cancellation) as well as normal completion.

Tests:
- Extend the happy-path chat stream integration test to assert the
  model_usage row (purpose=chat, correct token counts) is persisted;
  red-green verified against the unfixed code.
- Harden seeded_chat teardown against the fire-and-forget persist task
  racing the chat delete (FK from model_usage to chats).
- test_providers_api (live LLM): assert usage actually flows through
  streamed message_delta events instead of only reporting it.
@prvnsmpth prvnsmpth changed the title fix(ai): persist chat token usage when the agent loop stops the stream at message_stop fix(ai): persist chat token usage on early stream close Aug 31, 2026
@prvnsmpth
prvnsmpth merged commit b2d88db into master Aug 31, 2026
36 checks passed
@prvnsmpth
prvnsmpth deleted the fix/chat-usage-tracking branch August 31, 2026 06:06
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.

1 participant