Skip to content

refactor(agent): unify chat and headless token accumulation - #860

Merged
edenreich merged 2 commits into
mainfrom
refactor/835-unify-token-accumulation
Jul 11, 2026
Merged

edenreich merged 2 commits into
mainfrom
refactor/835-unify-token-accumulation

Conversation

@edenreich

Copy link
Copy Markdown
Contributor

Closes #835

What

Routes the sync AgentService.Run path (headless) through the same storeIterationMetrics accumulator the streaming (chat) path already uses, and deletes the headless duplicates. The shared sink was already there — the conversation repository's AddTokenUsage/GetSessionTokens/GetSessionCostStats (what /cost reads); the root cause was that Run skipped it.

  • internal/agent/agent.go: Run now calls storeIterationMetrics (tokenizer polyfill included) and returns the effective usage in ChatSyncResponse.Usage, so per-message output matches what was accumulated.
  • cmd/agent.go: drops the four inline counters, the ad-hoc AddTokenUsage goroutine, and the direct PricingService cost recomputation; emitSessionStats reads the repo's session token and cost stats. --no-save now calls SetAutoSave(false) so accumulation stays in-memory only.
  • internal/services/persistent_conversation.go: SetAutoSave takes the metadata mutex (one-line hardening).
  • New integration test TestSyncAndStreamAccumulateIdenticalSessionTokens: both paths against the mock gateway's usage-report scenario accumulate identical session totals (142 tokens).

Acceptance criteria (#835)

  • ✅ Single accumulation code path; headless totals equal chat totals for identical mock scenarios (asserted via usage-report, 142 tokens)
  • ✅ /cost and the headless final stats read from the same source (the conversation repo session stats)

Intended behavior changes

  • session_stats is now session/conversation-scoped (same numbers /cost shows) instead of run-scoped. Fresh sessions (CI, subagents, scheduler/heartbeat) are unchanged; resumed sessions (--session-id under channels) now include restored history; a mid-run rollover resets totals with the conversation. No programmatic consumer parses these values (agentrunner ignores session_stats lines).
  • A usage-less provider response previously didn't count toward headless requests; the polyfill now counts it with estimated tokens — chat parity, the point of the change.
  • --no-save + resumed session + mid-run rollover: StartNewConversation saves explicitly (ignores auto-save), and the persisted metadata's token stats now include the --no-save run's usage. Pre-existing save path, marginally widened.

Verification

  • task test, task test:e2e (race), task lint all green.
  • Manual: INFER_GATEWAY_MOCK=true infer agent "report your usage" --no-save emits session_stats with 142+15 tokens and repo-computed cost; storage untouched under --no-save; save-enabled run persists the same accumulated stats.

no docs ticket: internal-only refactor

Route the sync AgentService.Run path through storeIterationMetrics so both
chat (streaming) and headless share one accumulation path: tokenizer polyfill,
per-request ChatMetrics, and the conversation repository's session sink that
/cost reads. Headless drops its four inline counters and ad-hoc AddTokenUsage
goroutine; emitSessionStats now reads GetSessionTokens/GetSessionCostStats.
--no-save disables repo auto-save so accumulation stays in-memory only.

Closes #835
@edenreich
edenreich requested a review from a team as a code owner July 11, 2026 15:16
Comment thread cmd/agent_test.go Resolved
@edenreich
edenreich merged commit 95cd551 into main Jul 11, 2026
1 check passed
@edenreich
edenreich deleted the refactor/835-unify-token-accumulation branch July 11, 2026 15:26
@inference-gateway-releaser

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 0.142.2 🎉

The release is available on:

Your semantic-release bot 📦🚀

@inference-gateway-releaser inference-gateway-releaser Bot added the released Shipped in a release label Jul 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released Shipped in a release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[REFACTOR] Unify chat and headless token accumulation

1 participant