Skip to content

fix(ai): omit token counts the provider never reported - #906

Open
bernatixer wants to merge 2 commits into
mainfrom
posthog/ai-omit-unreported-token-counts
Open

fix(ai): omit token counts the provider never reported#906
bernatixer wants to merge 2 commits into
mainfrom
posthog/ai-omit-unreported-token-counts

Conversation

@bernatixer

@bernatixer bernatixer commented Aug 31, 2026

Copy link
Copy Markdown

💡 Motivation and Context

An LLM call whose provider never reported usage shows up as $0.00 in LLM analytics. Every integration sent $ai_input_tokens: 0 and $ai_output_tokens: 0 for it, and ingestion prices a call by multiplying a rate with that count. The common case is a cancelled stream: it consumed its prompt, but usage only arrives at the end.

Token counts are now written only when they trace back to a provider report:

  • A count the provider never reported is omitted, on every event writer: the shared capture paths in posthog/ai/utils.py, the OpenAI and Gemini embedding events, the LangChain callback, and the OpenAI Agents and Claude Agent SDK processors.
  • The stream accumulators (OpenAI, Anthropic, Gemini) and the response extractors no longer seed counts at zero, so an interrupted stream carries only what actually arrived.
  • A zero the provider reported is still sent as 0. Zero keeps meaning a real report of nothing.
  • LangChain cache and reasoning counts follow the same rule. They previously coalesced unreported values to 0.
  • $ai_total_tokens on the Agents processor is the sum of the reported sides, omitted when neither side reported.

This applies the PostHog/posthog-js#4664 semantic to this SDK, following the cross-SDK assessment on that PR. Ingestion distinguishes absent from zero since PostHog/posthog#90211. Older ingestion coalesces absent to 0 at read time, so this ships independently.

Note

$ai_input_tokens and $ai_output_tokens were previously always present on wrapper events. Anything reading them downstream has to handle absence.

💚 How did you test it?

  • A new parameterized test at the shared capture chokepoint covers three cases: no usage omits both counts, explicit zeros still send 0, one-sided usage sends one side. It fails when the .get(..., 0) default is restored, verified by reverting it.
  • A new Gemini streaming test covers a stream whose chunks never carry usage. It fails when the zero-seeded accumulator is restored, verified by reverting it.
  • The existing tests that pinned the fabricated zeros now assert absence (Gemini embeddings, Agents spans without usage, LangChain cache and reasoning defaults). Assertions backed by an explicit zero in their fixture stay == 0, which pins the boundary.
  • The posthog/test/ai suite passes locally: 648 passed, 5 skipped. The 9 failing tests make live provider calls that this sandbox's gateway rejects with 403, and they fail identically with the change stashed.
  • ruff format, ruff check, and the CI mypy command (through mypy-baseline filter) pass.
  • The public API snapshot is regenerated: extract_gemini_embedding_token_count now returns Optional[int], the one intentional signature change.
  • The red MCP SDK matrix is unrelated to this change: it was green on this PR's first run five hours earlier with the same code, the failing test fails identically on main in the same environment (verified locally), and two of the four jobs fail during setup before any test runs. It points at an upstream MCP SDK or fastmcp release from today and will affect the next run on main too.

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Added a changeset under .sampo/changesets/ (hand-written in the sampo add format)

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

Written by Claude Code in a PostHog Desktop session directed by @bernatixer, as the cross-SDK follow-up agreed on PostHog/posthog-js#4664. An audit found the fabrication concentrated at the shared property-write layer plus the zero-seeded accumulators. Cancellation handling needed no work here: the stream wrappers already capture from a finally and close the generator on early exit.

Decisions: provider-reported zeros keep sending 0, pinned by two existing LangChain fixtures. $ai_total_tokens stays a sum of reported sides rather than being omitted on partial usage, matching the lower-bound totals decision on the JS PR. The unused zero defaults inside _get_tokens_source stay untouched to keep the diff behavioral.

Skills invoked: writing-tests, writing-pr-descriptions.


Created with PostHog Desktop

Every integration wrote $ai_input_tokens: 0 and $ai_output_tokens: 0 when the provider never reported usage, so an interrupted stream priced as a free call downstream. Token counts are now written only when they trace back to a provider report: the shared capture paths, both embedding events, the LangChain callback and the Agents and Claude Agent SDK processors omit unreported counts, and the stream accumulators and response extractors no longer seed at zero.

A zero the provider reported is still sent as 0, so zero keeps meaning a real report of nothing. LangChain cache and reasoning counts follow the same rule instead of coalescing to 0, and the Agents processor's $ai_total_tokens is the sum of the reported sides, omitted when neither side reported.

Mirrors the posthog-js change (PostHog/posthog-js#4664). Ingestion distinguishes absent from zero since PostHog/posthog#90211 and older ingestion coalesces absent to 0 at read time, so this ships independently.

Generated-By: PostHog Desktop
Task-Id: ec0cc27f-fc40-4994-b153-2bfe74de1edf
@bernatixer bernatixer self-assigned this Aug 31, 2026
@github-actions

github-actions Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-08-31 21:20:27 UTC
Duration: 256356ms

✅ All Tests Passed!

111/111 tests passed


Capture_V1 Tests

94/94 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint 517ms
Endpoint And Method.Does Not Use Legacy Endpoints 510ms
Required Headers.Has Authorization Bearer Header 511ms
Required Headers.Has Content Type Json 510ms
Required Headers.Has Posthog Sdk Info Format 510ms
Required Headers.Has Posthog Attempt Header 510ms
Required Headers.Has Posthog Request Id 510ms
Required Headers.Has Posthog Request Timestamp 510ms
Required Headers.Has User Agent 511ms
Body Format.Body Has Created At And Batch 509ms
Body Format.No Api Key In Body 512ms
Body Format.No Sent At In Body 510ms
Event Format.Event Has Required Root Fields 510ms
Event Format.Event Uuid Is Valid 510ms
Event Format.Event Timestamp Is Rfc3339 510ms
Event Format.Distinct Id Is String 510ms
Event Format.Distinct Id At Root Not Properties 510ms
Event Format.Custom Properties Preserved 511ms
Event Format.Set Properties Preserved 510ms
Event Format.Set Once Properties Preserved 510ms
Event Format.Groups Properties Preserved 510ms
Event Format.Sdk Generates Uuid If Not Provided 510ms
Event Format.Event Has Required Root Fields Batch 513ms
Event Format.Event Uuid Is Valid Batch 514ms
Event Format.Event Timestamp Is Rfc3339 Batch 513ms
Event Format.Distinct Id Is String Batch 514ms
Event Format.Distinct Id At Root Not Properties Batch 513ms
Event Format.Custom Properties Preserved Batch 514ms
Event Format.Set Properties Preserved Batch 514ms
Event Format.Set Once Properties Preserved Batch 513ms
Event Format.Groups Properties Preserved Batch 514ms
Event Format.Sdk Generates Uuid If Not Provided Batch 514ms
Batch Behavior.Multiple Events In Single Batch 517ms
Batch Behavior.Batch Envelope Smoke 516ms
Batch Behavior.Flush With No Events Sends Nothing 506ms
Batch Behavior.Flush At Triggers Batch 1011ms
Batch Behavior.Created At Reflects Batch Creation Time 511ms
Deduplication.Generates Unique Uuids 517ms
Deduplication.Different Events Same Content Different Uuids 513ms
Deduplication.Preserves Uuid On Retry 6519ms
Deduplication.Preserves Timestamp On Retry 6518ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 6524ms
Deduplication.No Duplicate Events In Batch 521ms
Header Behavior On Retry.Attempt Header Starts At One 510ms
Header Behavior On Retry.Attempt Header Increments On Retry 13520ms
Header Behavior On Retry.Request Id Preserved On Retry 6519ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3021ms
Header Behavior On Retry.Request Timestamp Changes On Retry 6516ms
Response Format Validation.Success Response Has Uuid Keyed Results 510ms
Response Format Validation.Success Response Has Ok For Each Event 514ms
Response Format Validation.Success No Retry After When All Ok 513ms
Response Format Validation.Success Retry After Present When Retry Events 1516ms
Response Format Validation.Success No Retry After When Drop Only 513ms
Response Format Validation.Response Echoes Request Id 509ms
Retry Behavior.Retries On 408 6516ms
Retry Behavior.Retries On 500 6516ms
Retry Behavior.Retries On 503 8523ms
Retry Behavior.Retries On 504 6520ms
Retry Behavior.Retryable Errors Have Retry After 3517ms
Retry Behavior.Respects Retry After On Retryable Error 11523ms
Retry Behavior.Does Not Retry On 400 2515ms
Retry Behavior.Does Not Retry On 401 2513ms
Retry Behavior.Does Not Retry On 402 2514ms
Retry Behavior.Does Not Retry On 413 2513ms
Retry Behavior.Does Not Retry On 415 2513ms
Retry Behavior.Non Retryable Errors Have No Retry After 2513ms
Retry Behavior.Implements Backoff 22526ms
Retry Behavior.Max Retries Respected 22537ms
Partial Batch Handling.Handles 200 Full Success 2513ms
Partial Batch Handling.Handles 200 With All Ok 3517ms
Partial Batch Handling.Does Not Retry Dropped Events 3514ms
Partial Batch Handling.Does Not Retry Limited Events 3516ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 6519ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 6517ms
Partial Batch Handling.Retries Only Retry Events From Partial 6520ms
Partial Batch Handling.Partial Retry Preserves Uuids 6521ms
Partial Batch Handling.Partial Retry Attempt Header Increments 6521ms
Partial Batch Handling.Partial Retry Request Id Preserved 6518ms
Partial Batch Handling.Respects Retry After On Partial 8521ms
Partial Batch Handling.Unknown Result Treated As Terminal 3514ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 3520ms
Compression.Sends Gzip Content Encoding 510ms
Compression.No Content Encoding When Disabled 510ms
Compression.Compressed Body Is Decompressible 510ms
Error Handling.Does Not Retry On Unknown 4Xx 2513ms
Event Options.Cookieless Mode Override 510ms
Event Options.Disable Skew Correction Override 511ms
Event Options.Process Person Profile Override 510ms
Event Options.Product Tour Id Override 510ms
Event Options.Unset Options Omitted 510ms
Event Options.Options Override In Batch 514ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 509ms
Geoip And Historical Migration.Historical Migration Set In Body 510ms
Geoip And Historical Migration.Historical Migration Absent By Default 510ms

Feature_Flags Tests

17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id 11ms
Request Payload.Flags Request Uses V2 Query Param 10ms
Request Payload.Flags Request Hits Flags Path Not Decide 9ms
Request Payload.Flags Request Omits Authorization Header 9ms
Request Payload.Token In Flags Body Matches Init 9ms
Request Payload.Groups Round Trip 9ms
Request Payload.Groups Default To Empty Object 10ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 9ms
Request Payload.Disable Geoip Omitted Defaults To False 9ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 10ms
Request Lifecycle.No Flags Request On Init Alone 3ms
Request Lifecycle.No Flags Request On Normal Capture 510ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 15ms
Request Lifecycle.Mock Response Value Is Returned To Caller 9ms
Retry Behavior.Retries Flags On 502 313ms
Retry Behavior.Retries Flags On 504 313ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 512ms

extract_gemini_embedding_token_count now returns Optional[int], returning None when no embedding carried a token count. Regenerated with make public_api_snapshot.

Generated-By: PostHog Desktop
Task-Id: ec0cc27f-fc40-4994-b153-2bfe74de1edf
@bernatixer
bernatixer marked this pull request as ready for review August 31, 2026 21:21
@bernatixer
bernatixer requested a review from a team as a code owner August 31, 2026 21:21
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