: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(billing): measure heatmap event volume in daily usage report (#71279)
Paul D'Ambra77a94c20d3f0
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex d48476db78ee..eae94fc4313c 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -60,6 +60,7 @@ class Product(StrEnum):FEATURE_FLAGS = "feature_flags"GROUP_ANALYTICS = "group_analytics"GROWTH = "growth" # growth-team activation/lifecycle jobs (e.g. production-event detection)+ HEATMAPS = "heatmaps"INGESTION = "ingestion"LLM_ANALYTICS = "llm_analytics"LOGS = "logs"diff --git a/posthog/tasks/test/__snapshots__/test_usage_report.ambr b/posthog/tasks/test/__snapshots__/test_usage_report.ambrindex d18e65e7e8ae..bfdbe2572e6c 100644--- a/posthog/tasks/test/__snapshots__/test_usage_report.ambr+++ b/posthog/tasks/test/__snapshots__/test_usage_report.ambr@@ -885,6 +885,17 @@# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.54'''+ SELECT team_id,+ count() as count+ FROM heatmaps+ WHERE timestamp >= '2022-01-10 00:00:00'+ AND timestamp < '2022-01-10 23:59:59'+ GROUP BY team_id+ '''+# ---+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.55+ '''+SELECT team_id,count(distinct session_id) as countFROM@@ -905,7 +916,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.55+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.56'''SELECT team_id,@@ -928,7 +939,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.56+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.57'''SELECT team_id,@@ -952,7 +963,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.57+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.58'''SELECT team_id,@@ -975,7 +986,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.58+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.59'''SELECT team_id,@@ -999,33 +1010,6 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.59- '''-- SELECT team_id,- count(distinct session_id) as count- FROM- (SELECT any(team_id) as team_id,- session_id- FROM session_replay_events- WHERE min_first_timestamp >= '2022-01-10 00:00:00'- AND min_first_timestamp < '2022-01-10 23:59:59'- GROUP BY session_id- HAVING (ifNull(argMinMerge(snapshot_source), '') == 'mobile'- AND ifNull(argMinMerge(snapshot_library), '') IN ('posthog-ios',- 'posthog-android',- 'posthog-react-native',- 'posthog-flutter'))- AND max(is_deleted) = 0)- WHERE session_id NOT IN- (SELECT DISTINCT session_id- FROM session_replay_events- WHERE min_first_timestamp >= '2022-01-09 00:00:00'- AND min_first_timestamp < '2022-01-10 00:00:00'- GROUP BY session_id)- GROUP BY team_id- '''-# ---# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.6'''@@ -1064,6 +1048,33 @@# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.60'''+ SELECT team_id,+ count(distinct session_id) as count+ FROM+ (SELECT any(team_id) as team_id,+ session_id+ FROM session_replay_events+ WHERE min_first_timestamp >= '2022-01-10 00:00:00'+ AND min_first_timestamp < '2022-01-10 23:59:59'+ GROUP BY session_id+ HAVING (ifNull(argMinMerge(snapshot_source), '') == 'mobile'+ AND ifNull(argMinMerge(snapshot_library), '') IN ('posthog-ios',+ 'posthog-android',+ 'posthog-react-native',+ 'posthog-flutter'))+ AND max(is_deleted) = 0)+ WHERE session_id NOT IN+ (SELECT DISTINCT session_id+ FROM session_replay_events+ WHERE min_first_timestamp >= '2022-01-09 00:00:00'+ AND min_first_timestamp < '2022-01-10 00:00:00'+ GROUP BY session_id)+ GROUP BY team_id+ '''+# ---+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.61+ '''+SELECT distinct_id as team,sum(toInt64OrZero(replaceRegexpAll(JSONExtractRaw(properties, 'count'), '^"|"$', ''))) as sumFROM events@@ -1075,7 +1086,7 @@GROUP BY team'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.61+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.62'''SELECT distinct_id as team,@@ -1089,7 +1100,7 @@GROUP BY team'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.62+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.63'''WITH JSONExtractInt(log_comment, 'team_id') as team_id,JSONExtractString(log_comment, 'query_type') as query_type,@@ -1108,7 +1119,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.63+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.64'''WITH JSONExtractInt(log_comment, 'team_id') as team_id,JSONExtractString(log_comment, 'query_type') as query_type,@@ -1127,7 +1138,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.64+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.65'''WITH JSONExtractInt(log_comment, 'team_id') as team_id,JSONExtractString(log_comment, 'query_type') as query_type,@@ -1146,7 +1157,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.65+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.66'''WITH JSONExtractInt(log_comment, 'team_id') as team_id,JSONExtractString(log_comment, 'query_type') as query_type,@@ -1165,7 +1176,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.66+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.67'''WITH JSONExtractInt(log_comment, 'team_id') as team_id,JSONExtractString(log_comment, 'query_type') as query_type,@@ -1184,7 +1195,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.67+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.68'''WITH JSONExtractInt(log_comment, 'team_id') as team_id,JSONExtractString(log_comment, 'query_type') as query_type,@@ -1203,33 +1214,13 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.68- '''- WITH JSONExtractInt(log_comment, 'team_id') as team_id,- JSONExtractString(log_comment, 'query_type') as query_type,- JSONExtractString(log_comment, 'access_method') as access_method- SELECT team_id,- sum(read_bytes) as count- FROM clusterAllReplicas(posthog, system.query_log)- WHERE (type = 'QueryFinish'- OR type = 'ExceptionWhileProcessing')- AND is_initial_query = 1- AND query_type IN (['EventsQuery'])- AND event_time >= 'today 00:00:00'- AND event_time < '2022-01-11 05:59:59'- AND query_start_time >= '2022-01-10 00:00:00'- AND query_start_time < '2022-01-10 23:59:59'- AND access_method = ''- GROUP BY team_id- '''-# ---# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.69'''WITH JSONExtractInt(log_comment, 'team_id') as team_id,JSONExtractString(log_comment, 'query_type') as query_type,JSONExtractString(log_comment, 'access_method') as access_methodSELECT team_id,- sum(read_rows) as count+ sum(read_bytes) as countFROM clusterAllReplicas(posthog, system.query_log)WHERE (type = 'QueryFinish'OR type = 'ExceptionWhileProcessing')@@ -1284,7 +1275,7 @@JSONExtractString(log_comment, 'query_type') as query_type,JSONExtractString(log_comment, 'access_method') as access_methodSELECT team_id,- sum(query_duration_ms) as count+ sum(read_rows) as countFROM clusterAllReplicas(posthog, system.query_log)WHERE (type = 'QueryFinish'OR type = 'ExceptionWhileProcessing')@@ -1299,6 +1290,26 @@'''# ---# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.71+ '''+ WITH JSONExtractInt(log_comment, 'team_id') as team_id,+ JSONExtractString(log_comment, 'query_type') as query_type,+ JSONExtractString(log_comment, 'access_method') as access_method+ SELECT team_id,+ sum(query_duration_ms) as count+ FROM clusterAllReplicas(posthog, system.query_log)+ WHERE (type = 'QueryFinish'+ OR type = 'ExceptionWhileProcessing')+ AND is_initial_query = 1+ AND query_type IN (['EventsQuery'])+ AND event_time >= 'today 00:00:00'+ AND event_time < '2022-01-11 05:59:59'+ AND query_start_time >= '2022-01-10 00:00:00'+ AND query_start_time < '2022-01-10 23:59:59'+ AND access_method = ''+ GROUP BY team_id+ '''+# ---+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.72'''WITH JSONExtractInt(log_comment, 'team_id') as team_id,JSONExtractString(log_comment, 'query_type') as query_type,@@ -1318,7 +1329,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.72+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.73'''WITH JSONExtractInt(log_comment, 'team_id') as team_id,JSONExtractString(log_comment, 'query_type') as query_type,@@ -1338,7 +1349,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.73+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.74'''WITH JSONExtractInt(log_comment, 'team_id') as team_id,JSONExtractString(log_comment, 'query_type') as query_type,@@ -1358,7 +1369,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.74+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.75'''SELECT team_id,@@ -1382,7 +1393,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.75+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.76'''SELECT team_id,@@ -1397,7 +1408,7 @@metric_name'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.76+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.77'''SELECT team_id,@@ -1411,7 +1422,7 @@metric_name'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.77+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.78'''SELECT team_id,@@ -1424,7 +1435,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.78+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.79'''SELECT team_id,@@ -1442,20 +1453,6 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.79- '''-- SELECT team_id,- SUM(count) as count- FROM app_metrics2- WHERE app_source='hog_flow'- AND metric_name IN ('billable_invocation')- AND metric_kind IN ('email')- AND timestamp >= '2022-01-10 00:00:00'- AND timestamp < '2022-01-10 23:59:59'- GROUP BY team_id- '''-# ---# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.8'''@@ -1499,7 +1496,7 @@FROM app_metrics2WHERE app_source='hog_flow'AND metric_name IN ('billable_invocation')- AND metric_kind IN ('push')+ AND metric_kind IN ('email')AND timestamp >= '2022-01-10 00:00:00'AND timestamp < '2022-01-10 23:59:59'GROUP BY team_id@@ -1513,7 +1510,7 @@FROM app_metrics2WHERE app_source='hog_flow'AND metric_name IN ('billable_invocation')- AND metric_kind IN ('sms')+ AND metric_kind IN ('push')AND timestamp >= '2022-01-10 00:00:00'AND timestamp < '2022-01-10 23:59:59'GROUP BY team_id@@ -1527,7 +1524,7 @@FROM app_metrics2WHERE app_source='hog_flow'AND metric_name IN ('billable_invocation')- AND metric_kind IN ('fetch')+ AND metric_kind IN ('sms')AND timestamp >= '2022-01-10 00:00:00'AND timestamp < '2022-01-10 23:59:59'GROUP BY team_id@@ -1536,6 +1533,20 @@# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.83'''+ SELECT team_id,+ SUM(count) as count+ FROM app_metrics2+ WHERE app_source='hog_flow'+ AND metric_name IN ('billable_invocation')+ AND metric_kind IN ('fetch')+ AND timestamp >= '2022-01-10 00:00:00'+ AND timestamp < '2022-01-10 23:59:59'+ GROUP BY team_id+ '''+# ---+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.84+ '''+SELECT team_id,SUM(count) as countFROM app_metrics2diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.pyindex 678e3b359056..f8b8cd81d98d 100644--- a/posthog/tasks/test/test_usage_report.py+++ b/posthog/tasks/test/test_usage_report.py@@ -671,6 +671,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM"mobile_recording_bytes_in_period": 6,"mobile_recording_count_in_period": 1,"mobile_billable_recording_count_in_period": 0,+ "heatmap_events_count_in_period": 0,"replay_vision_credits_used_in_period": 0,"group_types_total": 2,"dashboard_count": 2,@@ -748,6 +749,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM"mobile_recording_bytes_in_period": 0,"mobile_recording_count_in_period": 0,"mobile_billable_recording_count_in_period": 0,+ "heatmap_events_count_in_period": 0,"replay_vision_credits_used_in_period": 0,"group_types_total": 2,"dashboard_count": 2,@@ -819,6 +821,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM"mobile_recording_bytes_in_period": 6,"mobile_recording_count_in_period": 1,"mobile_billable_recording_count_in_period": 0,+ "heatmap_events_count_in_period": 0,"replay_vision_credits_used_in_period": 0,"group_types_total": 0,"dashboard_count": 0,@@ -913,6 +916,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM"mobile_recording_bytes_in_period": 0,"mobile_recording_count_in_period": 0,"mobile_billable_recording_count_in_period": 0,+ "heatmap_events_count_in_period": 0,"replay_vision_credits_used_in_period": 0,"group_types_total": 0,"dashboard_count": 0,@@ -990,6 +994,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM"mobile_recording_bytes_in_period": 0,"mobile_recording_count_in_period": 0,"mobile_billable_recording_count_in_period": 0,+ "heatmap_events_count_in_period": 0,"replay_vision_credits_used_in_period": 0,"group_types_total": 0,"dashboard_count": 0,@@ -1287,6 +1292,44 @@ class TestReplayUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTassert report.recording_bytes_in_period == 20 # 2 web * 10 bytes each+class TestHeatmapUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesMixin):+ def _create_heatmap(self, team_id: int, timestamp: datetime, count: int = 1, session_id: str | None = None) -> None:+ session_ids = [session_id] * count if session_id else [f"sess_{i}" for i in range(count)]+ rows = ", ".join(+ f"('{heatmap_session_id}', {team_id}, 'user_1', '{timestamp.strftime('%Y-%m-%d %H:%M:%S')}', "+ f"10, 20, 16, 100, 200, false, 'https://example.com', 'click')"+ for heatmap_session_id in session_ids+ )+ sync_execute(+ "INSERT INTO sharded_heatmaps "+ "(session_id, team_id, distinct_id, timestamp, x, y, scale_factor, "+ "viewport_width, viewport_height, pointer_target_fixed, current_url, type) VALUES " + rows+ )++ def test_heatmap_events_counted_per_team_within_period(self) -> None:+ period_start, period_end = get_previous_day()++ # 3 in-period interactions for our team, 1 the day before (out of period),+ # and 2 for another team — only the 3 in-period ones should be counted for our team.+ self._create_heatmap(+ self.team.pk,+ period_start + relativedelta(hours=1),+ count=3,+ session_id="shared_session",+ )+ self._create_heatmap(self.team.pk, period_start - relativedelta(hours=1), count=1)+ self._create_heatmap(self.team.pk + 1, period_start + relativedelta(hours=1), count=2)++ all_reports = _get_all_usage_data_as_team_rows(period_start, period_end)+ report = _get_team_report(all_reports, self.team)++ assert report.heatmap_events_count_in_period == 3++ org_reports: dict[str, OrgReport] = {}+ _add_team_report_to_org_reports(org_reports, self.team, report, period_start)+ assert org_reports[str(self.organization.id)].heatmap_events_count_in_period == 3++class TestHogQLUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesMixin):# @also_test_with_materialized_columns(event_properties=["$lib", "$exception_values"], verify_no_jsonextract=False)@pytest.mark.skip(reason="Skipping due to flakiness")diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.pyindex be6903127102..5b297f011a8c 100644--- a/posthog/tasks/usage_report.py+++ b/posthog/tasks/usage_report.py@@ -145,6 +145,13 @@ class UsageReportCounters:mobile_recording_bytes_in_period: intmobile_billable_recording_count_in_period: int+ # Heatmaps+ # Measurement-only counter (like the langfuse/helicone event counts below): heatmaps are not+ # billed today, and there is no billing product mapped to this field, so it stays internal to+ # the "organization usage report" telemetry and never surfaces to customers. It lets us size+ # heatmap interaction volume per team before deciding whether/how to charge for it.+ heatmap_events_count_in_period: int+# Replay Visionreplay_vision_credits_used_in_period: int@@ -987,6 +994,27 @@ def get_teams_with_recording_count_in_period()+@timed_log()+@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)+def get_teams_with_heatmap_count_in_period(begin: datetime, end: datetime) -> list[tuple[int, int]]:+ # Heatmap interactions (click / rageclick / mousemove / scrolldepth) live in their own+ # `heatmaps` table, never in `events`, so they are invisible to every other counter here.+ # This is measurement-only for now — see the note on UsageReportCounters.heatmap_events_count_in_period.+ with tags_context(product=Product.HEATMAPS, feature=Feature.USAGE_REPORT):+ return sync_execute(+ """+ SELECT team_id, count() as count+ FROM heatmaps+ WHERE timestamp >= %(begin)s AND timestamp < %(end)s+ GROUP BY team_id+ """,+ {"begin": begin, "end": end},+ workload=Workload.OFFLINE,+ settings=CH_BILLING_SETTINGS,+ ch_user=ClickHouseUser.BILLING,+ )++@timed_log()@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)def get_teams_with_replay_vision_credits_used_in_period(begin: datetime, end: datetime) -> list[tuple[int, int]]:@@ -2460,6 +2488,7 @@ def _get_all_usage_data(period_start: datetime, period_end: datetime) -> dict[st"teams_with_elixir_events_count_in_period": all_metrics["elixir_events"],"teams_with_unity_events_count_in_period": all_metrics["unity_events"],"teams_with_rust_events_count_in_period": all_metrics["rust_events"],+ "teams_with_heatmap_count_in_period": get_teams_with_heatmap_count_in_period(period_start, period_end),"teams_with_recording_count_in_period": get_teams_with_recording_count_in_period(period_start, period_end, snapshot_source="web"),@@ -2733,6 +2762,7 @@ def _get_team_report(all_data: dict[str, Any], team: Team) -> UsageReportCountermobile_billable_recording_count_in_period=all_data["teams_with_mobile_billable_recording_count_in_period"].get(team.id, 0),+ heatmap_events_count_in_period=all_data["teams_with_heatmap_count_in_period"].get(team.id, 0),replay_vision_credits_used_in_period=all_data["teams_with_replay_vision_credits_used_in_period"].get(team.id, 0),diff --git a/posthog/temporal/usage_report/queries.py b/posthog/temporal/usage_report/queries.pyindex cbb5f47ede90..db6a21ed0ea5 100644--- a/posthog/temporal/usage_report/queries.py+++ b/posthog/temporal/usage_report/queries.py@@ -66,6 +66,7 @@ from posthog.tasks.usage_report import (get_teams_with_exceptions_captured_in_period,get_teams_with_feature_flag_requests_count_in_period,get_teams_with_free_historical_rows_synced_in_period,+ get_teams_with_heatmap_count_in_period,get_teams_with_hog_function_calls_in_period,get_teams_with_hog_function_fetch_calls_in_period,get_teams_with_logs_bytes_in_period,@@ -266,6 +267,11 @@ QUERIES: list[QuerySpec] = [},timeout_minutes=30,),+ # ---- ClickHouse: heatmaps ------------------------------------------------+ QuerySpec(+ name="teams_with_heatmap_count_in_period",+ fn=get_teams_with_heatmap_count_in_period,+ ),# ---- ClickHouse: recordings ----------------------------------------------QuerySpec(name="teams_with_recording_count_in_period",