: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): report MCP tool call usage (#70365)
Paul D'Ambra1052bb30718f
diff --git a/posthog/tasks/test/__snapshots__/test_usage_report.ambr b/posthog/tasks/test/__snapshots__/test_usage_report.ambrindex 9702699d5a2b..2f4018b253a2 100644--- a/posthog/tasks/test/__snapshots__/test_usage_report.ambr+++ b/posthog/tasks/test/__snapshots__/test_usage_report.ambr@@ -142,6 +142,17 @@# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.12'''+ SELECT team_id,+ uniqExact(tuple(toDate(timestamp), cityHash64(distinct_id), cityHash64(uuid))) AS count+ FROM events PREWHERE timestamp >= '2022-01-10 00:00:00'+ AND timestamp < '2022-01-10 23:59:59'+ WHERE event = '$mcp_tool_call'+ GROUP BY team_id+ '''+# ---+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.13+ '''+SELECT team_id,replaceRegexpAll(JSONExtractRaw(properties, '$ai_lib'), '^"|"$', '') AS ai_lib,count(1) as count@@ -156,7 +167,7 @@ai_lib'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.13+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.14'''SELECT team_id,@@ -173,7 +184,7 @@ai_lib'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.14+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.15'''SELECT team_id,@@ -190,7 +201,7 @@ai_lib'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.15+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.16'''SELECT team_id,@@ -207,7 +218,7 @@ai_lib'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.16+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.17'''SELECT team_id,@@ -224,7 +235,7 @@ai_lib'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.17+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.18'''SELECT team_id,@@ -241,7 +252,7 @@ai_lib'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.18+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.19'''SELECT team_id,@@ -258,23 +269,6 @@ai_lib'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.19- '''-- SELECT team_id,- replaceRegexpAll(JSONExtractRaw(properties, '$ai_lib'), '^"|"$', '') AS ai_lib,- count(1) as count- FROM events PREWHERE timestamp >= '2022-01-10 14:00:00'- AND timestamp < '2022-01-10 16:00:00'- AND replaceRegexpAll(JSONExtractRaw(properties, '$lib'), '^"|"$', '') IN ('posthog-node')- AND startsWith(event, '$ai_')- WHERE replaceRegexpAll(JSONExtractRaw(properties, '$ai_lib'), '^"|"$', '') IN ('posthog-openclaw',- '@posthog/pi',- 'posthog-ai')- GROUP BY team_id,- ai_lib- '''-# ---# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.2'''@@ -313,6 +307,23 @@# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.20'''+ SELECT team_id,+ replaceRegexpAll(JSONExtractRaw(properties, '$ai_lib'), '^"|"$', '') AS ai_lib,+ count(1) as count+ FROM events PREWHERE timestamp >= '2022-01-10 14:00:00'+ AND timestamp < '2022-01-10 16:00:00'+ AND replaceRegexpAll(JSONExtractRaw(properties, '$lib'), '^"|"$', '') IN ('posthog-node')+ AND startsWith(event, '$ai_')+ WHERE replaceRegexpAll(JSONExtractRaw(properties, '$ai_lib'), '^"|"$', '') IN ('posthog-openclaw',+ '@posthog/pi',+ 'posthog-ai')+ GROUP BY team_id,+ ai_lib+ '''+# ---+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.21+ '''+SELECT team_id,replaceRegexpAll(JSONExtractRaw(properties, '$ai_lib'), '^"|"$', '') AS ai_lib,count(1) as count@@ -327,7 +338,7 @@ai_lib'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.21+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.22'''SELECT team_id,@@ -344,7 +355,7 @@ai_lib'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.22+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.23'''SELECT team_id,@@ -361,7 +372,7 @@ai_lib'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.23+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.24'''SELECT team_id,@@ -378,7 +389,7 @@ai_lib'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.24+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.25'''SELECT JSONExtractInt(log_comment, 'team_id') team_id,@@ -394,7 +405,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.25+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.26'''SELECT team_id,@@ -407,7 +418,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.26+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.27'''SELECT team_id,@@ -424,7 +435,7 @@metric_name'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.27+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.28'''SELECT team_id,@@ -438,7 +449,7 @@library'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.28+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.29'''SELECT team_id,@@ -450,18 +461,6 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.29- '''-- SELECT team_id,- count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as count- FROM events- WHERE timestamp >= '2022-01-10 02:00:00'- AND timestamp < '2022-01-10 04:00:00'- AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']- GROUP BY team_id- '''-# ---# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.3'''@@ -503,8 +502,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 04:00:00'- AND timestamp < '2022-01-10 06:00:00'+ WHERE timestamp >= '2022-01-10 02:00:00'+ AND timestamp < '2022-01-10 04:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']GROUP BY team_id'''@@ -515,8 +514,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 06:00:00'- AND timestamp < '2022-01-10 08:00:00'+ WHERE timestamp >= '2022-01-10 04:00:00'+ AND timestamp < '2022-01-10 06:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']GROUP BY team_id'''@@ -527,8 +526,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 08:00:00'- AND timestamp < '2022-01-10 10:00:00'+ WHERE timestamp >= '2022-01-10 06:00:00'+ AND timestamp < '2022-01-10 08:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']GROUP BY team_id'''@@ -539,8 +538,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 10:00:00'- AND timestamp < '2022-01-10 12:00:00'+ WHERE timestamp >= '2022-01-10 08:00:00'+ AND timestamp < '2022-01-10 10:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']GROUP BY team_id'''@@ -551,8 +550,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 12:00:00'- AND timestamp < '2022-01-10 14:00:00'+ WHERE timestamp >= '2022-01-10 10:00:00'+ AND timestamp < '2022-01-10 12:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']GROUP BY team_id'''@@ -563,8 +562,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 14:00:00'- AND timestamp < '2022-01-10 16:00:00'+ WHERE timestamp >= '2022-01-10 12:00:00'+ AND timestamp < '2022-01-10 14:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']GROUP BY team_id'''@@ -575,8 +574,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 16:00:00'- AND timestamp < '2022-01-10 18:00:00'+ WHERE timestamp >= '2022-01-10 14:00:00'+ AND timestamp < '2022-01-10 16:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']GROUP BY team_id'''@@ -587,8 +586,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 18:00:00'- AND timestamp < '2022-01-10 20:00:00'+ WHERE timestamp >= '2022-01-10 16:00:00'+ AND timestamp < '2022-01-10 18:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']GROUP BY team_id'''@@ -599,8 +598,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 20:00:00'- AND timestamp < '2022-01-10 22:00:00'+ WHERE timestamp >= '2022-01-10 18:00:00'+ AND timestamp < '2022-01-10 20:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']GROUP BY team_id'''@@ -611,8 +610,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 22:00:00'- AND timestamp < '2022-01-10 23:59:59'+ WHERE timestamp >= '2022-01-10 20:00:00'+ AND timestamp < '2022-01-10 22:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']GROUP BY team_id'''@@ -658,11 +657,9 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 00:00:00'- AND timestamp < '2022-01-10 02:00:00'+ WHERE timestamp >= '2022-01-10 22:00:00'+ AND timestamp < '2022-01-10 23:59:59'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']- AND person_mode IN ('full',- 'force_upgrade')GROUP BY team_id'''# ---@@ -672,8 +669,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 02:00:00'- AND timestamp < '2022-01-10 04:00:00'+ WHERE timestamp >= '2022-01-10 00:00:00'+ AND timestamp < '2022-01-10 02:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']AND person_mode IN ('full','force_upgrade')@@ -686,8 +683,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 04:00:00'- AND timestamp < '2022-01-10 06:00:00'+ WHERE timestamp >= '2022-01-10 02:00:00'+ AND timestamp < '2022-01-10 04:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']AND person_mode IN ('full','force_upgrade')@@ -700,8 +697,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 06:00:00'- AND timestamp < '2022-01-10 08:00:00'+ WHERE timestamp >= '2022-01-10 04:00:00'+ AND timestamp < '2022-01-10 06:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']AND person_mode IN ('full','force_upgrade')@@ -714,8 +711,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 08:00:00'- AND timestamp < '2022-01-10 10:00:00'+ WHERE timestamp >= '2022-01-10 06:00:00'+ AND timestamp < '2022-01-10 08:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']AND person_mode IN ('full','force_upgrade')@@ -728,8 +725,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 10:00:00'- AND timestamp < '2022-01-10 12:00:00'+ WHERE timestamp >= '2022-01-10 08:00:00'+ AND timestamp < '2022-01-10 10:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']AND person_mode IN ('full','force_upgrade')@@ -742,8 +739,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 12:00:00'- AND timestamp < '2022-01-10 14:00:00'+ WHERE timestamp >= '2022-01-10 10:00:00'+ AND timestamp < '2022-01-10 12:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']AND person_mode IN ('full','force_upgrade')@@ -756,8 +753,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 14:00:00'- AND timestamp < '2022-01-10 16:00:00'+ WHERE timestamp >= '2022-01-10 12:00:00'+ AND timestamp < '2022-01-10 14:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']AND person_mode IN ('full','force_upgrade')@@ -770,8 +767,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 16:00:00'- AND timestamp < '2022-01-10 18:00:00'+ WHERE timestamp >= '2022-01-10 14:00:00'+ AND timestamp < '2022-01-10 16:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']AND person_mode IN ('full','force_upgrade')@@ -784,8 +781,8 @@SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events- WHERE timestamp >= '2022-01-10 18:00:00'- AND timestamp < '2022-01-10 20:00:00'+ WHERE timestamp >= '2022-01-10 16:00:00'+ AND timestamp < '2022-01-10 18:00:00'AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']AND person_mode IN ('full','force_upgrade')@@ -830,6 +827,20 @@# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.50'''+ SELECT team_id,+ count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as count+ FROM events+ WHERE timestamp >= '2022-01-10 18:00:00'+ AND timestamp < '2022-01-10 20:00:00'+ AND event NOT IN ['$feature_flag_called', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$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', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']+ AND person_mode IN ('full',+ 'force_upgrade')+ GROUP BY team_id+ '''+# ---+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.51+ '''+SELECT team_id,count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as countFROM events@@ -841,7 +852,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.51+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.52'''SELECT team_id,@@ -855,7 +866,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.52+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.53'''SELECT team_id,@@ -871,7 +882,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.53+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.54'''SELECT team_id,@@ -894,7 +905,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.54+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.55'''SELECT team_id,@@ -917,7 +928,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.55+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.56'''SELECT team_id,@@ -941,7 +952,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.56+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.57'''SELECT team_id,@@ -964,7 +975,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.57+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.58'''SELECT team_id,@@ -988,7 +999,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.58+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.59'''SELECT team_id,@@ -1015,20 +1026,6 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.59- '''-- SELECT distinct_id as team,- sum(JSONExtractInt(properties, 'count')) as sum- FROM events- WHERE team_id = 99999- AND event='decide usage'- AND timestamp >= '2022-01-10 00:00:00'- AND timestamp < '2022-01-10 23:59:59'- AND has(['correct'], replaceRegexpAll(JSONExtractRaw(properties, 'token'), '^"|"$', ''))- GROUP BY team- '''-# ---# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.6'''@@ -1071,7 +1068,7 @@sum(JSONExtractInt(properties, 'count')) as sumFROM eventsWHERE team_id = 99999- AND event='local evaluation usage'+ AND event='decide usage'AND timestamp >= '2022-01-10 00:00:00'AND timestamp < '2022-01-10 23:59:59'AND has(['correct'], replaceRegexpAll(JSONExtractRaw(properties, 'token'), '^"|"$', ''))@@ -1080,21 +1077,16 @@# ---# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.61'''- 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 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++ SELECT distinct_id as team,+ sum(JSONExtractInt(properties, 'count')) as sum+ FROM events+ WHERE team_id = 99999+ AND event='local evaluation usage'+ AND timestamp >= '2022-01-10 00:00:00'+ AND timestamp < '2022-01-10 23:59:59'+ AND has(['correct'], replaceRegexpAll(JSONExtractRaw(properties, 'token'), '^"|"$', ''))+ GROUP BY team'''# ---# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.62@@ -1103,7 +1095,7 @@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')@@ -1122,7 +1114,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')@@ -1141,7 +1133,7 @@JSONExtractString(log_comment, 'query_type') as query_type,JSONExtractString(log_comment, 'access_method') as access_methodSELECT team_id,- sum(read_bytes) as count+ sum(query_duration_ms) as countFROM clusterAllReplicas(posthog, system.query_log)WHERE (type = 'QueryFinish'OR type = 'ExceptionWhileProcessing')@@ -1150,7 +1142,7 @@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 = 'personal_api_key'+ AND access_method = ''GROUP BY team_id'''# ---@@ -1160,7 +1152,7 @@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')@@ -1179,7 +1171,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')@@ -1198,17 +1190,16 @@JSONExtractString(log_comment, 'query_type') as query_type,JSONExtractString(log_comment, 'access_method') as access_methodSELECT team_id,- sum(read_bytes) as count+ sum(query_duration_ms) as countFROM 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 = ''+ AND access_method = 'personal_api_key'GROUP BY team_id'''# ---@@ -1218,7 +1209,7 @@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')@@ -1238,7 +1229,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')@@ -1288,6 +1279,26 @@'''# ---# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.70+ '''+ 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.71'''WITH JSONExtractInt(log_comment, 'team_id') as team_id,JSONExtractString(log_comment, 'query_type') as query_type,@@ -1307,7 +1318,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.71+# 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,@@ -1327,7 +1338,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,@@ -1347,7 +1358,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.73+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.74'''SELECT team_id,@@ -1371,7 +1382,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.74+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.75'''SELECT team_id,@@ -1386,7 +1397,7 @@metric_name'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.75+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.76'''SELECT team_id,@@ -1400,7 +1411,7 @@metric_name'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.76+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.77'''SELECT team_id,@@ -1413,7 +1424,7 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.77+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.78'''SELECT team_id,@@ -1430,20 +1441,6 @@GROUP BY team_id'''# ----# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.78- '''-- 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.79'''@@ -1452,7 +1449,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@@ -1501,7 +1498,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@@ -1515,7 +1512,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@@ -1524,6 +1521,20 @@# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.82'''+ 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.83+ '''+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 5955519ab632..47c6e1ce6c7f 100644--- a/posthog/tasks/test/test_usage_report.py+++ b/posthog/tasks/test/test_usage_report.py@@ -24,7 +24,7 @@ from unittest.mock import MagicMock, Mock, patchfrom django.apps import appsfrom django.db import connection-from django.test import TestCase+from django.test import SimpleTestCase, TestCasefrom django.utils.timezone import nowimport structlog@@ -53,6 +53,7 @@ from posthog.tasks.usage_report import (OrgReport,UsageReportCounters,_add_team_report_to_org_reports,+ _execute_calendar_aligned_split_query,_get_all_org_reports,_get_all_usage_data_as_team_rows,_get_full_org_usage_report,@@ -63,6 +64,7 @@ from posthog.tasks.usage_report import (capture_report,get_all_event_metrics_in_period,get_instance_metadata,+ get_teams_with_billable_event_count_in_period,get_teams_with_query_metric,has_non_zero_usage,send_all_org_usage_reports,@@ -650,6 +652,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM"web_events_count_in_period": 37,"web_lite_events_count_in_period": 1,"node_events_count_in_period": 1,+ "mcp_tool_call_events_count_in_period": 0,"openclaw_events_count_in_period": 1,"posthog_pi_events_count_in_period": 1,"posthog_ai_events_count_in_period": 1,@@ -726,6 +729,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM"web_events_count_in_period": 25,"web_lite_events_count_in_period": 1,"node_events_count_in_period": 1,+ "mcp_tool_call_events_count_in_period": 0,"openclaw_events_count_in_period": 1,"posthog_pi_events_count_in_period": 1,"posthog_ai_events_count_in_period": 1,@@ -796,6 +800,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM"web_events_count_in_period": 12,"web_lite_events_count_in_period": 0,"node_events_count_in_period": 0,+ "mcp_tool_call_events_count_in_period": 0,"openclaw_events_count_in_period": 0,"posthog_pi_events_count_in_period": 0,"posthog_ai_events_count_in_period": 0,@@ -889,6 +894,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM"web_events_count_in_period": 11,"web_lite_events_count_in_period": 0,"node_events_count_in_period": 0,+ "mcp_tool_call_events_count_in_period": 0,"openclaw_events_count_in_period": 0,"posthog_pi_events_count_in_period": 0,"posthog_ai_events_count_in_period": 0,@@ -965,6 +971,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM"web_events_count_in_period": 11,"web_lite_events_count_in_period": 0,"node_events_count_in_period": 0,+ "mcp_tool_call_events_count_in_period": 0,"openclaw_events_count_in_period": 0,"posthog_pi_events_count_in_period": 0,"posthog_ai_events_count_in_period": 0,@@ -1397,10 +1404,12 @@ class TestQueryUsageReportSQL:assert params["event_time_end"] == end + timedelta(hours=6)@patch("posthog.tasks.usage_report._execute_split_query")+ @patch("posthog.tasks.usage_report.sync_execute", return_value=[(1, 4)])@patch("posthog.tasks.usage_report.get_property_string_expr")def test_get_all_event_metrics_splits_ai_breakdown_out_of_main_scan(self,mock_get_property_string_expr: MagicMock,+ mock_sync_execute: MagicMock,mock_execute_split_query: MagicMock,) -> None:mock_get_property_string_expr.side_effect = [("lib_expr", True), ("ai_lib_expr", True)]@@ -1421,6 +1430,7 @@ class TestQueryUsageReportSQL:assert "event LIKE 'helicone%%'" in main_queryassert "event LIKE 'traceloop%%'" in main_queryassert "OR lib_expr IN (" in main_query+ assert "event = '$mcp_tool_call'" not in main_queryassert "'posthog-node'" in main_queryassert "'posthog-rs'" in main_queryassert "ai_lib_expr" not in main_query@@ -1434,6 +1444,11 @@ class TestQueryUsageReportSQL:assert "ai_lib_expr IN (" in ai_queryassert "'posthog-ai'" in ai_query+ mcp_query = mock_sync_execute.call_args.args[0]+ assert "event = '$mcp_tool_call'" in mcp_query+ assert "uniqExact(tuple(toDate(timestamp), cityHash64(distinct_id), cityHash64(uuid)))" in mcp_query+ assert result["mcp_tool_call_events"] == [(1, 4)]+# AI counts are folded back in and subtracted from node_events (10 - 2 - 3 = 5).assert result["posthog_ai_events"] == [(1, 2)]assert result["openclaw_events"] == [(1, 3)]@@ -5114,6 +5129,32 @@ class TestOrganizationFiltering(LicensedTestMixin, ClickhouseDestroyTablesMixin,assert properties["total_orgs"] == 3+class TestCalendarAlignedQuerySplitting(SimpleTestCase):+ @patch("posthog.tasks.usage_report.sync_execute")+ def test_uses_midnight_boundaries(self, mock_sync_execute: MagicMock) -> None:+ mock_sync_execute.side_effect = [[(1, 1)], [(1, 2)], [(1, 3)]]+ begin = datetime(2023, 1, 1, 12, 0)+ end = datetime(2023, 1, 3, 12, 0)++ result = _execute_calendar_aligned_split_query(+ begin=begin,+ end=end,+ query_template="SELECT team_id, count() FROM events",+ params={},+ num_splits=12,+ )++ self.assertEqual(result, [(1, 6)])+ self.assertEqual(+ [call.args[1] for call in mock_sync_execute.call_args_list],+ [+ {"begin": begin, "end": datetime(2023, 1, 2)},+ {"begin": datetime(2023, 1, 2), "end": datetime(2023, 1, 3)},+ {"begin": datetime(2023, 1, 3), "end": end},+ ],+ )++class TestQuerySplitting(ClickhouseDestroyTablesMixin, ClickhouseTestMixin, TestCase):def setUp(self) -> None:super().setUp()@@ -5387,6 +5428,55 @@ class TestQuerySplitting(ClickhouseDestroyTablesMixin, ClickhouseTestMixin, Test# Should still be 15 since we created 15 distinct billable events (excluding AI events)self.assertEqual(result_distinct[0][1], 15)+ def test_mcp_tool_calls_are_deduplicated_and_remain_billable_events(self) -> None:+ reporting_end = self.end + relativedelta(days=1)+ billable_result_before = get_teams_with_billable_event_count_in_period(+ self.begin, reporting_end, count_distinct=True+ )+ baseline_count = billable_result_before[0][1]++ tool_call_event_uuid = _create_event(+ event="$mcp_tool_call",+ team=self.team,+ distinct_id="mcp_user",+ timestamp=self.begin + relativedelta(hours=1),+ properties={"$lib": "posthog-node-mcp"},+ )+ _create_event(+ event="$mcp_tool_call",+ team=self.team,+ distinct_id="mcp_user",+ event_uuid=tool_call_event_uuid,+ timestamp=self.begin + relativedelta(hours=1),+ properties={"$lib": "custom-mcp-client"},+ )+ _create_event(+ event="$mcp_tool_call",+ team=self.team,+ distinct_id="mcp_user",+ event_uuid=tool_call_event_uuid,+ timestamp=self.end + relativedelta(hours=1),+ properties={"$lib": "posthog-node-mcp"},+ )+ _create_event(+ event="$mcp_initialize",+ team=self.team,+ distinct_id="python_mcp_user",+ timestamp=self.begin + relativedelta(hours=3),+ properties={"$lib": "posthog-python"},+ )++ flush_persons_and_events()++ billable_result_after = get_teams_with_billable_event_count_in_period(+ self.begin, reporting_end, count_distinct=True+ )+ event_metrics = get_all_event_metrics_in_period(self.begin, reporting_end)++ self.assertEqual(billable_result_after, [(self.team.id, baseline_count + 3)])+ self.assertEqual(dict(event_metrics["mcp_tool_call_events"]).get(self.team.id), 2)+ self.assertEqual(dict(event_metrics["python_events"]).get(self.team.id), 1)+def test_get_teams_with_billable_enhanced_persons_event_count_in_period(self,) -> None:diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.pyindex 2e3a1c66ac33..6e36664da793 100644--- a/posthog/tasks/usage_report.py+++ b/posthog/tasks/usage_report.py@@ -239,6 +239,11 @@ class UsageReportCounters:web_events_count_in_period: intweb_lite_events_count_in_period: intnode_events_count_in_period: int++ # MCP usage overlaps billable event and per-SDK totals.+ mcp_tool_call_events_count_in_period: int++ # SDK usage (continued)openclaw_events_count_in_period: intposthog_pi_events_count_in_period: intposthog_ai_events_count_in_period: int@@ -544,6 +549,39 @@ def _execute_split_query(return combine_results_func(all_results)+def _execute_calendar_aligned_split_query(+ begin: datetime,+ end: datetime,+ query_template: str,+ params: dict,+ num_splits: int,+) -> list[tuple[int, int]]:+ total_days = (end.date() - begin.date()).days+ split_boundaries = {begin, end}++ for split_index in range(1, num_splits):+ day_offset = (total_days * split_index + num_splits - 1) // num_splits+ split_boundary = begin.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=day_offset)+ if begin < split_boundary < end:+ split_boundaries.add(split_boundary)++ ordered_boundaries = sorted(split_boundaries)+ all_results = []+ for split_begin, split_end in zip(ordered_boundaries, ordered_boundaries[1:]):+ split_params = params | {"begin": split_begin, "end": split_end}+ all_results.append(+ sync_execute(+ query_template,+ split_params,+ workload=Workload.OFFLINE,+ settings=CH_BILLING_SETTINGS,+ ch_user=ClickHouseUser.BILLING,+ )+ )++ return _combine_team_count_results(all_results)++def _combine_team_count_results(results_list: list) -> list[tuple[int, int]]:"""Default function to combine results from multiple queries that return (team_id, count) tuples.@@ -855,6 +893,21 @@ def get_all_event_metrics_in_period(begin: datetime, end: datetime) -> dict[str,num_splits=12,combine_results_func=combine_event_metrics_results,)+ metrics["mcp_tool_call_events"] = _execute_calendar_aligned_split_query(+ begin=begin,+ end=end,+ query_template="""+ SELECT+ team_id,+ uniqExact(tuple(toDate(timestamp), cityHash64(distinct_id), cityHash64(uuid))) AS count+ FROM events+ PREWHERE timestamp >= %(begin)s AND timestamp < %(end)s+ WHERE event = '$mcp_tool_call'+ GROUP BY team_id+ """,+ params={},+ num_splits=12,+ )ai_counts_by_metric, node_subtractions = _get_ai_sub_sdk_event_metric_counts(begin=begin,end=end,@@ -2308,6 +2361,7 @@ def _get_all_usage_data(period_start: datetime, period_end: datetime) -> dict[st"teams_with_web_events_count_in_period": all_metrics["web_events"],"teams_with_web_lite_events_count_in_period": all_metrics["web_lite_events"],"teams_with_node_events_count_in_period": all_metrics["node_events"],+ "teams_with_mcp_tool_call_events_count_in_period": all_metrics["mcp_tool_call_events"],"teams_with_openclaw_events_count_in_period": all_metrics["openclaw_events"],"teams_with_posthog_pi_events_count_in_period": all_metrics["posthog_pi_events"],"teams_with_posthog_ai_events_count_in_period": all_metrics["posthog_ai_events"],@@ -2675,6 +2729,9 @@ def _get_team_report(all_data: dict[str, Any], team: Team) -> UsageReportCounterweb_events_count_in_period=all_data["teams_with_web_events_count_in_period"].get(team.id, 0),web_lite_events_count_in_period=all_data["teams_with_web_lite_events_count_in_period"].get(team.id, 0),node_events_count_in_period=all_data["teams_with_node_events_count_in_period"].get(team.id, 0),+ mcp_tool_call_events_count_in_period=all_data["teams_with_mcp_tool_call_events_count_in_period"].get(+ team.id, 0+ ),openclaw_events_count_in_period=all_data["teams_with_openclaw_events_count_in_period"].get(team.id, 0),posthog_pi_events_count_in_period=all_data["teams_with_posthog_pi_events_count_in_period"].get(team.id, 0),posthog_ai_events_count_in_period=all_data["teams_with_posthog_ai_events_count_in_period"].get(team.id, 0),diff --git a/posthog/temporal/tests/usage_report/test_aggregate_activity.py b/posthog/temporal/tests/usage_report/test_aggregate_activity.pyindex 574876b4ddad..f6817de8b360 100644--- a/posthog/temporal/tests/usage_report/test_aggregate_activity.py+++ b/posthog/temporal/tests/usage_report/test_aggregate_activity.py@@ -64,6 +64,7 @@ def _canned_query_payload(query_name: str, team_a_id: int, team_b_id: int, *extr"web_events": [(team_a_id, 7), (team_b_id, 11), *extra_event_rows],"web_lite_events": [],"node_events": [],+ "mcp_tool_call_events": [(team_a_id, 2), (team_b_id, 3)],"android_events": [],"flutter_events": [],"ios_events": [],@@ -228,6 +229,8 @@ async def test_aggregate_writes_chunks_and_manifest(minio_workflow_ctx: Workflow# destination key on each org's report.assert by_org[str(org_a.id)]["web_events_count_in_period"] == 7assert by_org[str(org_b.id)]["web_events_count_in_period"] == 11+ assert by_org[str(org_a.id)]["mcp_tool_call_events_count_in_period"] == 2+ assert by_org[str(org_b.id)]["mcp_tool_call_events_count_in_period"] == 3# exceptions_captured "total" maps to the flat counter on the org's report.assert by_org[str(org_a.id)]["exceptions_captured_in_period"] == 5diff --git a/posthog/temporal/usage_report/queries.py b/posthog/temporal/usage_report/queries.pyindex 00a8f9682e64..cbb5f47ede90 100644--- a/posthog/temporal/usage_report/queries.py+++ b/posthog/temporal/usage_report/queries.py@@ -244,6 +244,7 @@ QUERIES: list[QuerySpec] = ["web_events": "teams_with_web_events_count_in_period","web_lite_events": "teams_with_web_lite_events_count_in_period","node_events": "teams_with_node_events_count_in_period",+ "mcp_tool_call_events": "teams_with_mcp_tool_call_events_count_in_period","openclaw_events": "teams_with_openclaw_events_count_in_period","posthog_pi_events": "teams_with_posthog_pi_events_count_in_period","posthog_ai_events": "teams_with_posthog_ai_events_count_in_period",