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(metrics): count OTel metrics ingestion in usage reports and activate on data (#95278)

Daniel Visca2919ef89be1e
diff --git a/posthog/models/product_intent/product_intent.py b/posthog/models/product_intent/product_intent.py
index 78aa8818caaa..b6a88bbf02d6 100644
--- a/posthog/models/product_intent/product_intent.py
+++ b/posthog/models/product_intent/product_intent.py
@@ -229,10 +229,14 @@ class ProductIntent(UUIDTModel, RootTeamMixin):
return contexts.get("mcp_analytics_viewed", 0) >= 1
def has_activated_metrics(self) -> bool:
- # The user has charted or queried metrics. Charting/querying is only possible
- # once metrics have reached the team (a metric name has to exist to pick), so an
- # engagement signal is itself proof of ingestion — and ingestion on its own is a
- # connected pipeline, not an activated product.
+ # Two independent paths activate metrics:
+ #
+ # 1. Engagement: the user has charted or queried metrics. Charting/querying is only
+ # possible once metrics have reached the team (a metric name has to exist to pick),
+ # so an engagement signal is itself proof of ingestion.
+ #
+ # 2. Ingestion: the team has metric data flowing. Sending data does not require the
+ # viewer, so a team can reach the product outcome without ever firing a UI event.
#
# We deliberately do NOT gate on `metrics_first_ingested`: that context fires only
# when the frontend observes a no-metrics -> has-metrics flip in-session, so a team
@@ -247,7 +251,21 @@ class ProductIntent(UUIDTModel, RootTeamMixin):
return False
contexts = intent.contexts or {}
- return contexts.get("metrics_viewer_query_run", 0) >= 1 or contexts.get("metrics_sql_query_run", 0) >= 1
+ if contexts.get("metrics_viewer_query_run", 0) >= 1 or contexts.get("metrics_sql_query_run", 0) >= 1:
+ return True
+
+ # Local import: this module loads during django.setup() (via posthog.models), and the
+ # metrics facade pulls in HogQL execution (circular).
+ from products.metrics.backend.facade.api import team_has_metrics # noqa: PLC0415
+
+ # Activation checks run on the request path (intent registration), so a ClickHouse
+ # failure must not fail the caller — treat it as "no data yet" and let the periodic
+ # recheck pick the team up later.
+ try:
+ return team_has_metrics(self.team)
+ except Exception:
+ logger.exception("has_activated_metrics: data lookup failed", team_id=self.team_id)
+ return False
def has_activated_workflows(self) -> bool:
# At least one workflow needs to be active (not just drafted)
diff --git a/posthog/models/test/test_product_intent.py b/posthog/models/test/test_product_intent.py
index 1280088ea93b..c1d76a65bee5 100644
--- a/posthog/models/test/test_product_intent.py
+++ b/posthog/models/test/test_product_intent.py
@@ -802,25 +802,34 @@ class TestProductIntent(BaseTest):
[
# Charting or querying is only possible once metrics have reached the team,
# so any engagement signal is itself proof of ingestion + activation.
- ("charted", {"metrics_viewer_query_run": 1}, True),
- ("queried in sql", {"metrics_sql_query_run": 2}, True),
+ ("charted", {"metrics_viewer_query_run": 1}, False, True),
+ ("queried in sql", {"metrics_sql_query_run": 2}, False, True),
(
"first-ingested recorded then charted",
{"metrics_first_ingested": 1, "metrics_viewer_query_run": 1},
+ False,
True,
),
# Pre-existing-metrics teams never record the transition-only first-ingested
# context, so engagement alone must still activate them.
- ("charted without first-ingested intent", {"metrics_viewer_query_run": 3}, True),
- # Ingestion alone (no engagement) is a connected pipeline, not activation.
- ("first-ingested but never looked at", {"metrics_first_ingested": 1}, False),
- ("no engagement at all", {}, False),
+ ("charted without first-ingested intent", {"metrics_viewer_query_run": 3}, False, True),
+ # Data flowing activates without any engagement: sending does not require the
+ # viewer, so ingestion alone is the product outcome.
+ ("ingesting but never looked at", {"metrics_first_ingested": 1}, True, True),
+ ("ingesting with no contexts at all", {}, True, True),
+ # No engagement and no data is not activation.
+ ("first-ingested context but no data found", {"metrics_first_ingested": 1}, False, False),
+ ("no engagement at all", {}, False, False),
]
)
- def test_has_activated_metrics(self, _name: str, contexts: dict, expected: bool) -> None:
+ def test_has_activated_metrics(self, _name: str, contexts: dict, has_data: bool, expected: bool) -> None:
intent = self._make_metrics_intent(contexts)
- assert intent.has_activated_metrics() is expected
+ with patch(
+ "products.metrics.backend.facade.api.team_has_metrics",
+ return_value=has_data,
+ ):
+ assert intent.has_activated_metrics() is expected
def test_check_and_update_activation_activates_metrics(self) -> None:
# Guards the registration, not the criterion: an unregistered check never runs.
diff --git a/posthog/tasks/test/__snapshots__/test_usage_report.ambr b/posthog/tasks/test/__snapshots__/test_usage_report.ambr
index 15dc5fb5ae5b..74e7f843bd01 100644
--- a/posthog/tasks/test/__snapshots__/test_usage_report.ambr
+++ b/posthog/tasks/test/__snapshots__/test_usage_report.ambr
@@ -623,6 +623,22 @@
# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.31
'''
+ SELECT team_id,
+ metric_name,
+ SUM(count) as count
+ FROM app_metrics2
+ WHERE app_source='metrics'
+ AND metric_name IN ('bytes_ingested',
+ 'records_ingested')
+ AND timestamp >= '2022-01-10 00:00:00'
+ AND timestamp < '2022-01-10 23:59:59'
+ GROUP BY team_id,
+ metric_name
+ '''
+# ---
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.32
+ '''
+
SELECT team_id,
multiIf(replaceRegexpAll(JSONExtractRaw(properties, '$lib'), '^"|"$', '') = 'web', 'web', replaceRegexpAll(JSONExtractRaw(properties, '$lib'), '^"|"$', '') = 'js', 'web_lite', replaceRegexpAll(JSONExtractRaw(properties, '$lib'), '^"|"$', '') = 'posthog-node', 'node', replaceRegexpAll(JSONExtractRaw(properties, '$lib'), '^"|"$', '') = 'posthog-edge', 'node', replaceRegexpAll(JSONExtractRaw(properties, '$lib'), '^"|"$', '') = 'posthog-android', 'android', replaceRegexpAll(JSONExtractRaw(properties, '$lib'), '^"|"$', '') = 'posthog-flutter', 'flutter', replaceRegexpAll(JSONExtractRaw(properties, '$lib'), '^"|"$', '') = 'posthog-ios', 'ios', replaceRegexpAll(JSONExtractRaw(properties, '$lib'), '^"|"$', '') = 'posthog-go', 'go', replaceRegexpAll(JSONExtractRaw(properties, '$lib'), '^"|"$', '') = 'posthog-java', 'java', replaceRegexpAll(JSONExtractRaw(properties, '$lib'), '^"|"$', '') = 'posthog-server', 'java', replaceRegexpAll(JSONExtractRaw(properties, '$lib'), '^"|"$', '') = 'posthog-react-native', 'react_native', replaceRegexpAll(JSONExtractRaw(properties, '$lib'), '^"|"$', '') = 'posthog-ruby', 'ruby', replaceRegexpAll(JSONExtractRaw(properties, '$lib'), '^"|"$', '') = 'posthog-python', 'python', 'unknown') AS library,
count(1) as total
@@ -634,7 +650,7 @@
library
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.32
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.33
'''
SELECT team_id,
@@ -646,7 +662,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.33
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.34
'''
SELECT team_id,
@@ -658,7 +674,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.34
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.35
'''
SELECT team_id,
@@ -670,7 +686,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.35
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.36
'''
SELECT team_id,
@@ -682,7 +698,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.36
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.37
'''
SELECT team_id,
@@ -694,7 +710,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.37
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.38
'''
SELECT team_id,
@@ -706,7 +722,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.38
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.39
'''
SELECT team_id,
@@ -718,18 +734,6 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.39
- '''
-
- SELECT team_id,
- count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as count
- FROM events
- WHERE timestamp >= '2022-01-10 14:00:00'
- AND timestamp < '2022-01-10 16:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$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.4
'''
@@ -776,8 +780,8 @@
SELECT team_id,
count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as count
FROM 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', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$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
'''
@@ -788,8 +792,8 @@
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'
+ WHERE timestamp >= '2022-01-10 16:00:00'
+ AND timestamp < '2022-01-10 18:00:00'
AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$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
'''
@@ -800,8 +804,8 @@
SELECT team_id,
count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as count
FROM 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', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$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
'''
@@ -812,8 +816,8 @@
SELECT team_id,
count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as count
FROM 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', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$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
'''
@@ -824,11 +828,9 @@
SELECT team_id,
count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as count
FROM 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', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$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
'''
# ---
@@ -838,8 +840,8 @@
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'
+ WHERE timestamp >= '2022-01-10 00:00:00'
+ AND timestamp < '2022-01-10 02:00:00'
AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$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')
@@ -852,8 +854,8 @@
SELECT team_id,
count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as count
FROM 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', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$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')
@@ -866,8 +868,8 @@
SELECT team_id,
count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as count
FROM 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', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$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')
@@ -880,8 +882,8 @@
SELECT team_id,
count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as count
FROM 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', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$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')
@@ -894,8 +896,8 @@
SELECT team_id,
count(distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)) as count
FROM 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', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$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')
@@ -945,6 +947,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 10:00:00'
+ AND timestamp < '2022-01-10 12:00:00'
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$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 count
FROM events
@@ -956,7 +972,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.51
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.52
'''
SELECT team_id,
@@ -970,7 +986,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.52
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.53
'''
SELECT team_id,
@@ -984,7 +1000,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.53
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.54
'''
SELECT team_id,
@@ -998,7 +1014,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.54
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.55
'''
SELECT team_id,
@@ -1012,7 +1028,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.55
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.56
'''
SELECT team_id,
@@ -1026,7 +1042,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.56
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.57
'''
SELECT team_id,
@@ -1042,7 +1058,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.57
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.58
'''
SELECT team_id,
@@ -1053,29 +1069,6 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.58
- '''
-
- 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), 'web') == 'mobile') == 0
- 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.59
'''
@@ -1088,7 +1081,7 @@
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 dateDiff('milliseconds', min(min_first_timestamp), max(max_last_timestamp)) = 0
+ HAVING (ifNull(argMinMerge(snapshot_source), 'web') == 'mobile') == 0
AND max(is_deleted) = 0)
WHERE session_id NOT IN
(SELECT DISTINCT session_id
@@ -1142,6 +1135,29 @@
# 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 dateDiff('milliseconds', min(min_first_timestamp), max(max_last_timestamp)) = 0
+ 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 team_id,
sum(total_size) as bytes
FROM
@@ -1163,7 +1179,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.61
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.62
'''
SELECT team_id,
@@ -1186,7 +1202,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.62
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.63
'''
SELECT team_id,
@@ -1210,7 +1226,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.63
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.64
'''
SELECT team_id,
@@ -1233,7 +1249,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.64
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.65
'''
SELECT distinct_id as team,
@@ -1247,7 +1263,7 @@
GROUP BY team
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.65
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.66
'''
SELECT distinct_id as team,
@@ -1261,7 +1277,7 @@
GROUP BY team
'''
# ---
-# 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,
@@ -1280,7 +1296,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,
@@ -1299,7 +1315,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.68
+# 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,
@@ -1318,25 +1334,6 @@
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_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 = 'personal_api_key'
- GROUP BY team_id
- '''
-# ---
# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.7
'''
@@ -1383,7 +1380,7 @@
JSONExtractString(log_comment, 'query_type') as query_type,
JSONExtractString(log_comment, 'access_method') as access_method
SELECT team_id,
- sum(read_rows) as count
+ sum(read_bytes) as count
FROM clusterAllReplicas(posthog, system.query_log)
WHERE (type = 'QueryFinish'
OR type = 'ExceptionWhileProcessing')
@@ -1402,7 +1399,7 @@
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
+ sum(read_rows) as count
FROM clusterAllReplicas(posthog, system.query_log)
WHERE (type = 'QueryFinish'
OR type = 'ExceptionWhileProcessing')
@@ -1416,6 +1413,25 @@
'''
# ---
# 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,
+ 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 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 = 'personal_api_key'
+ GROUP BY team_id
+ '''
+# ---
+# 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,
@@ -1435,7 +1451,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,
@@ -1455,7 +1471,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.74
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.75
'''
WITH JSONExtractInt(log_comment, 'team_id') as team_id,
JSONExtractString(log_comment, 'query_type') as query_type,
@@ -1475,7 +1491,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.75
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.76
'''
WITH JSONExtractInt(log_comment, 'team_id') as team_id,
JSONExtractString(log_comment, 'query_type') as query_type,
@@ -1495,7 +1511,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.76
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.77
'''
WITH JSONExtractInt(log_comment, 'team_id') as team_id,
JSONExtractString(log_comment, 'query_type') as query_type,
@@ -1515,7 +1531,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.77
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.78
'''
WITH JSONExtractInt(log_comment, 'team_id') as team_id,
JSONExtractString(log_comment, 'query_type') as query_type,
@@ -1535,7 +1551,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.78
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.79
'''
SELECT team_id,
@@ -1559,21 +1575,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_function'
- AND metric_name IN ('succeeded',
- 'failed')
- AND timestamp >= '2022-01-10 00:00:00'
- AND timestamp < '2022-01-10 23:59:59'
- GROUP BY team_id,
- metric_name
- '''
-# ---
# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.8
'''
@@ -1621,7 +1622,8 @@
SUM(count) as count
FROM app_metrics2
WHERE app_source='hog_function'
- AND metric_name IN ('fetch')
+ AND metric_name IN ('succeeded',
+ 'failed')
AND timestamp >= '2022-01-10 00:00:00'
AND timestamp < '2022-01-10 23:59:59'
GROUP BY team_id,
@@ -1631,6 +1633,20 @@
# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.81
'''
+ SELECT team_id,
+ SUM(count) as count
+ FROM app_metrics2
+ WHERE app_source='hog_function'
+ AND metric_name IN ('fetch')
+ AND timestamp >= '2022-01-10 00:00:00'
+ AND timestamp < '2022-01-10 23:59:59'
+ GROUP BY team_id,
+ metric_name
+ '''
+# ---
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.82
+ '''
+
SELECT team_id,
SUM(count) as count
FROM app_metrics2
@@ -1641,7 +1657,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.82
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.83
'''
SELECT team_id,
@@ -1663,7 +1679,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.83
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.84
'''
SELECT team_id,
@@ -1677,7 +1693,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.84
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.85
'''
SELECT team_id,
@@ -1691,7 +1707,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.85
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.86
'''
SELECT team_id,
@@ -1705,7 +1721,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.86
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.87
'''
SELECT team_id,
@@ -1719,7 +1735,7 @@
GROUP BY team_id
'''
# ---
-# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.87
+# name: TestFeatureFlagsUsageReport.test_usage_report_decide_requests.88
'''
SELECT team_id,
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index a5b3580bc3e9..ead6f69a0c44 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -3655,6 +3655,47 @@ class TestHogFunctionUsageReports(ClickhouseDestroyTablesMixin, TestCase, Clickh
assert org_1_report[field] == value, field
assert team_1_report[field] == value, field
+ @patch("posthog.tasks.usage_report.get_ph_client")
+ @patch("posthog.tasks.usage_report.send_report_to_billing_service")
+ def test_metrics_usage_metrics(
+ self,
+ billing_task_mock: MagicMock,
+ posthog_capture_mock: MagicMock,
+ ) -> None:
+ self._setup_teams()
+
+ for metric_name, count in {"bytes_ingested": 3_500_000, "records_ingested": 120}.items():
+ create_app_metric2(
+ team_id=self.org_1_team_1.id,
+ app_source="metrics",
+ metric_name=metric_name,
+ count=count,
+ )
+ # Same metric names under the logs app_source must not leak into the metrics counters.
+ create_app_metric2(
+ team_id=self.org_1_team_1.id,
+ app_source="logs",
+ metric_name="records_ingested",
+ count=999,
+ )
+
+ period = get_previous_day(at=now() + relativedelta(days=1))
+ all_reports = _get_all_org_reports(period=period)
+
+ org_1_report = _get_full_org_usage_report_as_dict(
+ _get_full_org_usage_report(all_reports[str(self.org_1.id)], get_instance_metadata(period))
+ )
+
+ expected = {
+ "metrics_records_in_period": 120,
+ "metrics_mb_in_period": 3,
+ }
+ # Only org_1_team_1 has metrics usage, so the org-level rollup equals that team's values.
+ team_1_report = org_1_report["teams"][str(self.org_1_team_1.id)]
+ for field, value in expected.items():
+ assert org_1_report[field] == value, field
+ assert team_1_report[field] == value, field
+
@freeze_time("2022-01-10T10:00:00Z")
class TestErrorTrackingUsageReport(ClickhouseDestroyTablesMixin, TestCase, ClickhouseTestMixin):
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index 535806b77e28..5c0b6b526f49 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -389,6 +389,11 @@ class UsageReportCounters:
apm_tracing_spans_in_period: int
apm_tracing_mb_in_period: int
+ # Metrics (OTel). Report-only while the product is in alpha — makes per-team ingestion
+ # visible fleet-wide, the same signal logs_records_in_period provides for logs.
+ metrics_records_in_period: int
+ metrics_mb_in_period: int
+
# Instance metadata to be included in overall report
@dataclasses.dataclass
@@ -2708,6 +2713,44 @@ def get_teams_with_apm_tracing_usage_in_period(
return usage
+@timed_log()
+@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)
+def get_teams_with_metrics_usage_in_period(
+ begin: datetime,
+ end: datetime,
+ # nosemgrep: tuple-return-prefer-dataclass -- (team_id, count) rows are the shared usage-report contract consumed by convert_team_usage_rows_to_dict, like the logs and traces functions above.
+) -> dict[str, list[tuple[int, int]]]:
+ """
+ Returns Metrics (OTel) ingested bytes and record counts per team for the period,
+ keyed by `bytes` / `records`; each value is a list of `(team_id, count)` tuples ready
+ for `convert_team_usage_rows_to_dict`.
+
+ The metrics ingestion consumer emits the same pre-aggregated `app_metrics2` counters
+ as logs and traces, under `app_source='metrics'`.
+ """
+ with tags_context(product=Product.METRICS, feature=Feature.USAGE_REPORT):
+ rows = sync_execute(
+ """
+ SELECT team_id, metric_name, SUM(count) as count
+ FROM app_metrics2
+ WHERE app_source='metrics'
+ AND metric_name IN ('bytes_ingested', 'records_ingested')
+ AND timestamp >= %(begin)s AND timestamp < %(end)s
+ GROUP BY team_id, metric_name
+ """,
+ {"begin": begin, "end": end},
+ workload=Workload.OFFLINE,
+ settings=CH_BILLING_SETTINGS,
+ ch_user=ClickHouseUser.BILLING,
+ )
+
+ key_by_metric = {"bytes_ingested": "bytes", "records_ingested": "records"}
+ usage: dict[str, list[tuple[int, int]]] = {"bytes": [], "records": []}
+ for team_id, metric_name, count in rows:
+ usage[key_by_metric[metric_name]].append((team_id, count))
+ return usage
+
+
def _trim_oversize_usage_report_payload(full_report_dict: dict[str, Any]) -> dict[str, Any]:
"""Drop the per-team breakdown when the serialized report would exceed Kafka's
message size limit, so the org-level roll-up still makes it through ingestion.
@@ -2827,6 +2870,7 @@ def has_non_zero_usage(report: UsageReportCounters) -> bool:
or report.task_sandbox_seconds_in_period > 0
or report.logs_bytes_in_period > 0
or report.apm_tracing_bytes_in_period > 0
+ or report.metrics_records_in_period > 0
or report.workflow_emails_sent_in_period > 0
or report.workflow_push_sent_in_period > 0
or report.workflow_sms_sent_in_period > 0
@@ -2865,6 +2909,7 @@ def _get_all_usage_data(period_start: datetime, period_end: datetime) -> dict[st
logs_retention_by_tier = get_teams_with_logs_retention_bytes_in_period(period_start, period_end)
logs_retention_byte_days_rows = get_teams_with_logs_retention_byte_days_in_period(period_start, period_end)
apm_tracing_usage = get_teams_with_apm_tracing_usage_in_period(period_start, period_end)
+ metrics_usage = get_teams_with_metrics_usage_in_period(period_start, period_end)
exception_metrics_by_library, exception_metrics = get_teams_with_exceptions_captured_in_period(
period_start, period_end
)
@@ -3153,6 +3198,8 @@ def _get_all_usage_data(period_start: datetime, period_end: datetime) -> dict[st
"teams_with_ruby_logs_records_in_period": sdk_logs_by_suffix["ruby"],
"teams_with_apm_tracing_bytes_in_period": apm_tracing_usage["bytes"],
"teams_with_apm_tracing_spans_in_period": apm_tracing_usage["spans"],
+ "teams_with_metrics_bytes_in_period": metrics_usage["bytes"],
+ "teams_with_metrics_records_in_period": metrics_usage["records"],
}
@@ -3408,6 +3455,8 @@ def _get_team_report(all_data: dict[str, Any], team: Team) -> UsageReportCounter
apm_tracing_bytes_in_period=apm_tracing_bytes_in_period,
apm_tracing_spans_in_period=all_data["teams_with_apm_tracing_spans_in_period"].get(team.id, 0),
apm_tracing_mb_in_period=int(apm_tracing_bytes_in_period // 1_000_000),
+ metrics_records_in_period=all_data["teams_with_metrics_records_in_period"].get(team.id, 0),
+ metrics_mb_in_period=int(all_data["teams_with_metrics_bytes_in_period"].get(team.id, 0) // 1_000_000),
)
diff --git a/posthog/temporal/usage_report/queries.py b/posthog/temporal/usage_report/queries.py
index 43fd1dbb8ceb..f10de06cb86c 100644
--- a/posthog/temporal/usage_report/queries.py
+++ b/posthog/temporal/usage_report/queries.py
@@ -75,6 +75,7 @@ from posthog.tasks.usage_report import (
get_teams_with_logs_records_in_period,
get_teams_with_logs_retention_byte_days_in_period,
get_teams_with_logs_retention_bytes_in_period,
+ get_teams_with_metrics_usage_in_period,
get_teams_with_mobile_billable_recording_count_in_period,
get_teams_with_posthog_code_credits_used_in_period,
get_teams_with_query_metric,
@@ -585,6 +586,16 @@ QUERIES: list[QuerySpec] = [
"spans": "teams_with_apm_tracing_spans_in_period",
},
),
+ # ---- ClickHouse: Metrics (OTel) -------------------------------------------
+ QuerySpec(
+ name="metrics_usage",
+ fn=get_teams_with_metrics_usage_in_period,
+ output="multi",
+ multi_keys_mapping={
+ "bytes": "teams_with_metrics_bytes_in_period",
+ "records": "teams_with_metrics_records_in_period",
+ },
+ ),
# ---- Snapshot queries (kind="snapshot") ---------------------------------
# ⚠️ Read the disclaimer at the top of this module. These ignore the
# period and reflect *current* state at run time. Re-running for the same
diff --git a/products/metrics/backend/has_metrics_query_runner.py b/products/metrics/backend/has_metrics_query_runner.py
index 9d07fadfb16f..b561c6aa1e66 100644
--- a/products/metrics/backend/has_metrics_query_runner.py
+++ b/products/metrics/backend/has_metrics_query_runner.py
@@ -12,6 +12,15 @@ from posthog.models import Team
HAS_METRICS_CACHE_TTL = int(dt.timedelta(days=7).total_seconds())
+# Negative results are cached too, but only briefly. The activation check
+# (posthog/models/product_intent) reaches this from the un-throttled
+# add_product_intent request path, so an uncached False is a fresh ClickHouse
+# query per request — a resource-exhaustion path. The TTL stays well under the
+# setup prompt's 5s poll interval (metricsSetupLogic.pollIntervalMs), so a team
+# that just wired up OTel sees the no-metrics -> has-metrics flip within one
+# extra poll cycle instead of being pinned to a stale empty state.
+HAS_METRICS_NEGATIVE_CACHE_TTL = int(dt.timedelta(seconds=4).total_seconds())
+
class HasMetricsQueryRunner:
def __init__(self, team: Team) -> None:
@@ -41,10 +50,10 @@ class HasMetricsQueryRunner:
def team_has_metrics(team: Team) -> bool:
cache_key = f"team:{team.id}:has_metrics"
- if cache.get(cache_key) is True:
- return True
+ cached = cache.get(cache_key)
+ if cached is not None:
+ return cached
has_metrics = HasMetricsQueryRunner(team).run()
- if has_metrics:
- cache.set(cache_key, True, HAS_METRICS_CACHE_TTL)
+ cache.set(cache_key, has_metrics, HAS_METRICS_CACHE_TTL if has_metrics else HAS_METRICS_NEGATIVE_CACHE_TTL)
return has_metrics
diff --git a/products/metrics/backend/tests/test_has_metrics_query_runner.py b/products/metrics/backend/tests/test_has_metrics_query_runner.py
index a8f7772cc45c..708711f62c4a 100644
--- a/products/metrics/backend/tests/test_has_metrics_query_runner.py
+++ b/products/metrics/backend/tests/test_has_metrics_query_runner.py
@@ -123,7 +123,12 @@ class TestHasMetricsAPI(ClickhouseTestMixin, APIBaseTest):
assert mock_report.call_count == 2
- def test_has_metrics_api_does_not_cache_negative_results(self):
+ def test_has_metrics_api_caches_negative_results_briefly(self):
+ # Negatives are cached with a short TTL: the activation check reaches
+ # this through the un-throttled add_product_intent request path, so an
+ # uncached False is a per-request ClickHouse query. The TTL stays under
+ # the setup prompt's 5s poll interval, so a team that just wired up
+ # OTel still sees the flip within one extra poll cycle.
cache.clear()
with patch("products.metrics.backend.has_metrics_query_runner.HasMetricsQueryRunner") as mock_runner:
@@ -134,7 +139,25 @@ class TestHasMetricsAPI(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.json(), {"hasMetrics": False})
self.assertEqual(mock_runner.return_value.run.call_count, 1)
+ # Second call within the TTL hits the cache, not ClickHouse
response = self.client.get(f"/api/projects/{self.team.id}/metrics/has_metrics")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json(), {"hasMetrics": False})
+ self.assertEqual(mock_runner.return_value.run.call_count, 1)
+
+ def test_has_metrics_negative_cache_expires(self):
+ cache.clear()
+
+ with (
+ patch("products.metrics.backend.has_metrics_query_runner.HasMetricsQueryRunner") as mock_runner,
+ patch("products.metrics.backend.has_metrics_query_runner.HAS_METRICS_NEGATIVE_CACHE_TTL", 0),
+ ):
+ mock_runner.return_value.run.return_value = False
+
+ response = self.client.get(f"/api/projects/{self.team.id}/metrics/has_metrics")
+ self.assertEqual(response.json(), {"hasMetrics": False})
+
+ # TTL of 0 means the negative is not held: the next call re-queries
+ response = self.client.get(f"/api/projects/{self.team.id}/metrics/has_metrics")
+ self.assertEqual(response.json(), {"hasMetrics": False})
self.assertEqual(mock_runner.return_value.run.call_count, 2)