Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(billing): dedup gateway AIO meter exemption by request_id (#64808)

Richard Solomou2af8cdf67b39
diff --git a/posthog/tasks/test/__snapshots__/test_usage_report.ambr b/posthog/tasks/test/__snapshots__/test_usage_report.ambr
index 44e8faee0d8e..8d0a67552af9 100644
--- a/posthog/tasks/test/__snapshots__/test_usage_report.ambr
+++ b/posthog/tasks/test/__snapshots__/test_usage_report.ambr
@@ -1429,11 +1429,16 @@
'''
SELECT team_id,
- COUNT() as count
- FROM events
- WHERE event IN ['$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters']
- AND timestamp >= '2022-01-10 00:00:00'
- AND timestamp < '2022-01-10 23:59:59'
+ COUNT() - uniqExactIf(request_id, verified
+ AND request_id != '') as count
+ FROM
+ (SELECT team_id,
+ JSONExtractBool(properties, '$ai_gateway_verified') as verified,
+ if(verified, JSONExtractString(properties, '$ai_gateway_request_id'), '') as request_id
+ FROM events
+ WHERE event IN ['$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters']
+ AND timestamp >= '2022-01-10 00:00:00'
+ AND timestamp < '2022-01-10 23:59:59')
GROUP BY team_id
'''
# ---
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index a997c990cf4a..03321dd121b0 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -5511,6 +5511,98 @@ class TestQuerySplitting(ClickhouseDestroyTablesMixin, ClickhouseTestMixin, Test
billable_result_final = get_teams_with_billable_event_count_in_period(self.begin, self.end)
self.assertEqual(billable_result_final[0][1], baseline_count + 1)
+ def test_gateway_verified_ai_events_excluded_from_ai_count(self) -> None:
+ """Gateway-originated events carry the ingestion-verified $ai_gateway_verified
+ marker and are billed via the gateway wallet, so they must not be counted in
+ the AIO llm_events meter (double-billing)."""
+ from posthog.tasks.usage_report import get_teams_with_ai_event_count_in_period
+
+ def ai_count() -> int:
+ result = get_teams_with_ai_event_count_in_period(self.begin, self.end)
+ return result[0][1] if result else 0
+
+ baseline_count = ai_count()
+
+ # Normal AI events: counted.
+ for i in range(3):
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id=f"sdk_ai_user_{i}",
+ timestamp=self.begin + relativedelta(hours=i + 1),
+ properties={"$ai_model": "claude-3"},
+ )
+ flush_persons_and_events()
+ self.assertEqual(ai_count(), baseline_count + 3, "normal AI events should be counted")
+
+ # Gateway-verified events with distinct (signature-bound) request_ids:
+ # each earns one exemption, so the count must not move.
+ for i in range(2):
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id=f"gateway_ai_user_{i}",
+ timestamp=self.begin + relativedelta(hours=i + 1),
+ properties={
+ "$ai_model": "claude-3",
+ "$ai_gateway_verified": True,
+ "$ai_gateway_request_id": f"gw-req-{i}",
+ },
+ )
+ flush_persons_and_events()
+ self.assertEqual(ai_count(), baseline_count + 3, "gateway-verified events should be excluded")
+
+ # Client-forged $ai_gateway without the ingestion-verified marker: still
+ # counted, since the filter keys only on $ai_gateway_verified (which a
+ # client can't set — ingestion strips $ai_gateway* and stamps it).
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id="forged_gateway_user",
+ timestamp=self.begin + relativedelta(hours=1),
+ properties={"$ai_model": "claude-3", "$ai_gateway": True},
+ )
+ flush_persons_and_events()
+ self.assertEqual(ai_count(), baseline_count + 4, "forged $ai_gateway (no verified marker) should be counted")
+
+ # Replay: three verified events sharing one request_id (a captured signature
+ # replayed) earn only a single exemption — the other two stay billable.
+ for i in range(3):
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id=f"replay_user_{i}",
+ timestamp=self.begin + relativedelta(hours=i + 1),
+ properties={
+ "$ai_model": "claude-3",
+ "$ai_gateway_verified": True,
+ "$ai_gateway_request_id": "replayed-req",
+ },
+ )
+ flush_persons_and_events()
+ self.assertEqual(
+ ai_count(),
+ baseline_count + 6,
+ "a replayed request_id earns one exemption; the other two replays stay billable",
+ )
+
+ # Verified but no request_id: can't be deduped, so they stay billable
+ # rather than collapsing the empty-string bucket into one exemption.
+ for i in range(2):
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id=f"no_req_id_user_{i}",
+ timestamp=self.begin + relativedelta(hours=i + 1),
+ properties={"$ai_model": "claude-3", "$ai_gateway_verified": True},
+ )
+ flush_persons_and_events()
+ self.assertEqual(
+ ai_count(),
+ baseline_count + 8,
+ "verified events with no request_id are not blanket-deduped; both stay counted",
+ )
+
def test_conversations_events_excluded_from_billable_count(self) -> None:
"""Test that Conversations widget events are excluded from billable event counts."""
from posthog.tasks.usage_report import get_teams_with_billable_event_count_in_period
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index 23fe5f6a2d12..bba93ea54979 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -1235,9 +1235,25 @@ def get_teams_with_ai_event_count_in_period(
with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.USAGE_REPORT):
return sync_execute(
"""
- SELECT team_id, COUNT() as count
- FROM events
- WHERE event IN %(ai_events)s AND timestamp >= %(begin)s AND timestamp < %(end)s
+ -- Gateway events are wallet-billed, so exempt them: subtract one per distinct
+ -- verified $ai_gateway_request_id (a replayed signature reuses one id, so it's
+ -- worth one exemption and the copies stay billable). Both markers are
+ -- capture-stamped (#64806), not client-settable; a non-empty request_id is
+ -- required so one without it stays billable.
+ -- Perf: extract request_id only for verified rows (normally ≈0), so
+ -- non-gateway rows pay just the verified-bool extraction, not a string
+ -- extraction each, across the full AI event volume.
+ SELECT
+ team_id,
+ COUNT() - uniqExactIf(request_id, verified AND request_id != '') as count
+ FROM (
+ SELECT
+ team_id,
+ JSONExtractBool(properties, '$ai_gateway_verified') as verified,
+ if(verified, JSONExtractString(properties, '$ai_gateway_request_id'), '') as request_id
+ FROM events
+ WHERE event IN %(ai_events)s AND timestamp >= %(begin)s AND timestamp < %(end)s
+ )
GROUP BY team_id
""",
{"begin": begin, "end": end, "ai_events": AI_EVENTS},