Skip to content

fix(gemini): declare cache reporting as inclusive on generations - #860

Merged
Radu-Raicea merged 2 commits into
mainfrom
posthog-code/gemini-cache-reporting-exclusive
Aug 7, 2026
Merged

fix(gemini): declare cache reporting as inclusive on generations#860
Radu-Raicea merged 2 commits into
mainfrom
posthog-code/gemini-cache-reporting-exclusive

Conversation

@fivestarspicy

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Cache-heavy Gemini generations can be priced wrong in AI observability, because the SDK never tells ingestion how Gemini counts cache tokens.

Gemini counts cached_content_token_count inside prompt_token_count, so cache reads are a subset of input, not a separate pool. The SDK reports both numbers but declares nothing, so ingestion infers the accounting model from the token counts.

That inference is unreliable for Gemini. Under explicit context caching the two counts come from separate measurements: the cache object is counted when it is created, and the prompt is counted per request. They describe the same tokens but can disagree by a few percent, which puts the cache pool just above the input total and makes the counts look like two separate pools.

This PR sets the flag where the answer is actually known. PostHog/posthog#79781 is the matching ingestion-side change, which stops inferring exclusive accounting from a small overshoot and covers SDK versions that predate this one.

💚 How did you test it?

  • Ran uv run pytest posthog/test/ai/ --ignore=posthog/test/ai/otel. 446 passed. Two failures, test_integration_stop_reason in the Anthropic and OpenAI suites, need live provider credentials and fail the same way on a clean checkout.
  • Extended test_cache_and_reasoning_tokens and test_streaming_cache_and_reasoning_tokens to assert $ai_cache_reporting_exclusive is False. These cover the two capture paths separately, so they catch the flag being dropped in the converter, in the streaming merge, or at either tagging site.
  • Did not skip the otel suites for any reason related to this change. Their dependencies are not installed in this sandbox.
  • Did not run a live Gemini call.

📝 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

  • Ran sampo add to generate a changeset file

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

I (the PostHog Slack app, running Claude) traced this from a Slack thread on Gemini cost reconciliation, and a PostHog engineer directed the fix. I did not set an assignee because I could not verify their GitHub handle in session.

The flag is set only on generations that actually report cache reads, so generations without caching do not carry an extra property.

Along the way I checked whether the skew came from our own mapping and concluded it does not: _extract_usage_from_metadata copies both counts off a single usage_metadata object with no arithmetic. I also found a real asymmetry in merge_usage_stats, where cumulative mode overwrites input_tokens on every chunk but only writes cache_read_input_tokens when it is above zero. That lets the two counts come from different chunks on a streaming call. It is not the cause of the case that prompted this PR, which is non-streaming, and I left it alone rather than widening the diff. It looks worth a separate look.

Public artifact: no customer or session material reached this PR.


Created with PostHog from a Slack thread

Gemini counts `cached_content_token_count` inside `prompt_token_count`, but the
SDK never said so, leaving ingestion to infer the accounting model from the token
counts alone.

That inference is unreliable here. Under explicit context caching the two counts
come from separate measurements, the cache object at creation time and the prompt
per request, so they can disagree by a few percent and the cache pool can land
just above the input total.

Set `cache_reporting_exclusive` to False on generations that report cache reads,
and carry it through the streaming merge and both capture paths so ingestion
prices cached tokens from the declared value.

Generated-By: PostHog Code
Task-Id: 06160e48-feb9-4d39-8b7b-3dcfd1d9ca24
@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-08-07 17:57:06 UTC
Duration: 256423ms

✅ 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 516ms
Endpoint And Method.Does Not Use Legacy Endpoints 511ms
Required Headers.Has Authorization Bearer Header 510ms
Required Headers.Has Content Type Json 510ms
Required Headers.Has Posthog Sdk Info Format 511ms
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 510ms
Body Format.Body Has Created At And Batch 510ms
Body Format.No Api Key In Body 511ms
Body Format.No Sent At In Body 510ms
Event Format.Event Has Required Root Fields 511ms
Event Format.Event Uuid Is Valid 510ms
Event Format.Event Timestamp Is Rfc3339 511ms
Event Format.Distinct Id Is String 510ms
Event Format.Distinct Id At Root Not Properties 510ms
Event Format.Custom Properties Preserved 510ms
Event Format.Set Properties Preserved 510ms
Event Format.Set Once Properties Preserved 509ms
Event Format.Groups Properties Preserved 511ms
Event Format.Sdk Generates Uuid If Not Provided 511ms
Event Format.Event Has Required Root Fields Batch 515ms
Event Format.Event Uuid Is Valid Batch 514ms
Event Format.Event Timestamp Is Rfc3339 Batch 514ms
Event Format.Distinct Id Is String Batch 515ms
Event Format.Distinct Id At Root Not Properties Batch 514ms
Event Format.Custom Properties Preserved Batch 515ms
Event Format.Set Properties Preserved Batch 515ms
Event Format.Set Once Properties Preserved Batch 514ms
Event Format.Groups Properties Preserved Batch 513ms
Event Format.Sdk Generates Uuid If Not Provided Batch 517ms
Batch Behavior.Multiple Events In Single Batch 520ms
Batch Behavior.Batch Envelope Smoke 516ms
Batch Behavior.Flush With No Events Sends Nothing 507ms
Batch Behavior.Flush At Triggers Batch 1012ms
Batch Behavior.Created At Reflects Batch Creation Time 511ms
Deduplication.Generates Unique Uuids 520ms
Deduplication.Different Events Same Content Different Uuids 513ms
Deduplication.Preserves Uuid On Retry 6518ms
Deduplication.Preserves Timestamp On Retry 6518ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 6523ms
Deduplication.No Duplicate Events In Batch 518ms
Header Behavior On Retry.Attempt Header Starts At One 510ms
Header Behavior On Retry.Attempt Header Increments On Retry 13528ms
Header Behavior On Retry.Request Id Preserved On Retry 6516ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3021ms
Header Behavior On Retry.Request Timestamp Changes On Retry 6520ms
Response Format Validation.Success Response Has Uuid Keyed Results 511ms
Response Format Validation.Success Response Has Ok For Each Event 515ms
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 511ms
Retry Behavior.Retries On 408 6519ms
Retry Behavior.Retries On 500 6519ms
Retry Behavior.Retries On 503 8519ms
Retry Behavior.Retries On 504 6516ms
Retry Behavior.Retryable Errors Have Retry After 3517ms
Retry Behavior.Respects Retry After On Retryable Error 11518ms
Retry Behavior.Does Not Retry On 400 2512ms
Retry Behavior.Does Not Retry On 401 2514ms
Retry Behavior.Does Not Retry On 402 2513ms
Retry Behavior.Does Not Retry On 413 2513ms
Retry Behavior.Does Not Retry On 415 2514ms
Retry Behavior.Non Retryable Errors Have No Retry After 2512ms
Retry Behavior.Implements Backoff 22524ms
Retry Behavior.Max Retries Respected 22537ms
Partial Batch Handling.Handles 200 Full Success 2513ms
Partial Batch Handling.Handles 200 With All Ok 3514ms
Partial Batch Handling.Does Not Retry Dropped Events 3516ms
Partial Batch Handling.Does Not Retry Limited Events 3516ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 6518ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 6521ms
Partial Batch Handling.Retries Only Retry Events From Partial 6523ms
Partial Batch Handling.Partial Retry Preserves Uuids 6523ms
Partial Batch Handling.Partial Retry Attempt Header Increments 6519ms
Partial Batch Handling.Partial Retry Request Id Preserved 6523ms
Partial Batch Handling.Respects Retry After On Partial 8522ms
Partial Batch Handling.Unknown Result Treated As Terminal 3514ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 3519ms
Compression.Sends Gzip Content Encoding 512ms
Compression.No Content Encoding When Disabled 509ms
Compression.Compressed Body Is Decompressible 510ms
Error Handling.Does Not Retry On Unknown 4Xx 2514ms
Event Options.Cookieless Mode Override 511ms
Event Options.Disable Skew Correction Override 510ms
Event Options.Process Person Profile Override 511ms
Event Options.Product Tour Id Override 511ms
Event Options.Unset Options Omitted 510ms
Event Options.Options Override In Batch 514ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 510ms
Geoip And Historical Migration.Historical Migration Set In Body 509ms
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 9ms
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 10ms
Request Payload.Groups Default To Empty Object 11ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 10ms
Request Payload.Disable Geoip Omitted Defaults To False 10ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 9ms
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 13ms
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 511ms

Generated-By: PostHog Code
Task-Id: 06160e48-feb9-4d39-8b7b-3dcfd1d9ca24
@Radu-Raicea
Radu-Raicea marked this pull request as ready for review August 7, 2026 17:58
@Radu-Raicea
Radu-Raicea requested a review from a team as a code owner August 7, 2026 17:58
fivestarspicy added a commit to PostHog/posthog-js that referenced this pull request Aug 7, 2026
Gemini counts `cachedContentTokenCount` inside `promptTokenCount`, but the SDK
never said so, leaving ingestion to infer the accounting model from the token
counts alone.

That inference is unreliable here. Under explicit context caching the two counts
come from separate measurements, the cache object at creation time and the prompt
per request, so they can disagree by a few percent and the cache pool can land
just above the input total.

Set `cacheReportingExclusive` to false on generations that report cache reads, on
both the streaming and non-streaming paths, and map it onto
`$ai_cache_reporting_exclusive`. The property mapping checks against undefined
rather than truthiness, because false is the meaningful value here.

Mirrors PostHog/posthog-python#860.

Generated-By: PostHog Code
Task-Id: 06160e48-feb9-4d39-8b7b-3dcfd1d9ca24
@Radu-Raicea
Radu-Raicea merged commit bd5cff4 into main Aug 7, 2026
39 checks passed
@Radu-Raicea
Radu-Raicea deleted the posthog-code/gemini-cache-reporting-exclusive branch August 7, 2026 17:58
Radu-Raicea pushed a commit to PostHog/posthog-js that referenced this pull request Aug 7, 2026
…4473)

* fix(ai): declare gemini cache reporting as inclusive on generations

Gemini counts `cachedContentTokenCount` inside `promptTokenCount`, but the SDK
never said so, leaving ingestion to infer the accounting model from the token
counts alone.

That inference is unreliable here. Under explicit context caching the two counts
come from separate measurements, the cache object at creation time and the prompt
per request, so they can disagree by a few percent and the cache pool can land
just above the input total.

Set `cacheReportingExclusive` to false on generations that report cache reads, on
both the streaming and non-streaming paths, and map it onto
`$ai_cache_reporting_exclusive`. The property mapping checks against undefined
rather than truthiness, because false is the meaningful value here.

Mirrors PostHog/posthog-python#860.

Generated-By: PostHog Code
Task-Id: 06160e48-feb9-4d39-8b7b-3dcfd1d9ca24

* fix(ai): drop derived cache reporting flag when token counts are overridden

The derived flag describes how the SDK's own input and cache counts relate to
each other. When a caller passes their own token counts through
`posthogProperties`, those override the derived counts but the flag survived
alongside them, so it could describe numbers that are no longer on the event.

That is wrong in the expensive direction: declaring inclusive over counts that
are actually exclusive makes ingestion subtract a cache pool that was never part
of the input.

Suppress the derived flag whenever the caller overrides any token count. A caller
who knows their own accounting model can still pass
`$ai_cache_reporting_exclusive` explicitly, and that value wins.

Extracts the passthrough check behind `hasTokenOverrides`, which `getTokensSource`
now shares.

Generated-By: PostHog Code
Task-Id: 06160e48-feb9-4d39-8b7b-3dcfd1d9ca24
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.

2 participants