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(mcp-analytics): emit prometheus metrics for intent clustering (PR8/9) (#59691)

Daniel Visca1ac277ceb0a3
diff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.py
index 14ce365d4299..36cec8777078 100644
--- a/posthog/temporal/common/worker.py
+++ b/posthog/temporal/common/worker.py
@@ -41,6 +41,11 @@ from posthog.temporal.data_modeling.metrics import (
DATA_MODELING_LATENCY_HISTOGRAM_BUCKETS,
DATA_MODELING_LATENCY_HISTOGRAM_METRICS,
)
+from posthog.temporal.mcp_analytics.intent_clustering.metrics import (
+ MCPA_CLUSTERING_LATENCY_HISTOGRAM_BUCKETS,
+ MCPA_CLUSTERING_LATENCY_HISTOGRAM_METRICS,
+ MCPAClusteringMetricsInterceptor,
+)
from posthog.temporal.session_replay.delete_recordings.metrics import (
DELETE_RECORDINGS_LATENCY_HISTOGRAM_BUCKETS,
DELETE_RECORDINGS_LATENCY_HISTOGRAM_METRICS,
@@ -125,6 +130,7 @@ ALL_INTERCEPTOR_CLASSES = [
EvalsMetricsInterceptor,
SummarizationMetricsInterceptor,
ClusteringMetricsInterceptor,
+ MCPAClusteringMetricsInterceptor,
SentimentMetricsInterceptor,
EvalReportsMetricsInterceptor,
LogsAlertingMetricsInterceptor,
@@ -236,6 +242,12 @@ async def create_worker(
| dict(zip(EVALS_LATENCY_HISTOGRAM_METRICS, itertools.repeat(EVALS_LATENCY_HISTOGRAM_BUCKETS)))
| dict(zip(SUMMARIZATION_LATENCY_HISTOGRAM_METRICS, itertools.repeat(SUMMARIZATION_LATENCY_HISTOGRAM_BUCKETS)))
| dict(zip(CLUSTERING_LATENCY_HISTOGRAM_METRICS, itertools.repeat(CLUSTERING_LATENCY_HISTOGRAM_BUCKETS)))
+ | dict(
+ zip(
+ MCPA_CLUSTERING_LATENCY_HISTOGRAM_METRICS,
+ itertools.repeat(MCPA_CLUSTERING_LATENCY_HISTOGRAM_BUCKETS),
+ )
+ )
| dict(zip(TASKS_LATENCY_HISTOGRAM_METRICS, itertools.repeat(TASKS_LATENCY_HISTOGRAM_BUCKETS)))
| dict(zip(SENTIMENT_LATENCY_HISTOGRAM_METRICS, itertools.repeat(SENTIMENT_LATENCY_HISTOGRAM_BUCKETS)))
| dict(
diff --git a/posthog/temporal/mcp_analytics/intent_clustering/activities.py b/posthog/temporal/mcp_analytics/intent_clustering/activities.py
index 0d08051ed2ad..65a20660903f 100644
--- a/posthog/temporal/mcp_analytics/intent_clustering/activities.py
+++ b/posthog/temporal/mcp_analytics/intent_clustering/activities.py
@@ -33,6 +33,7 @@ from posthog.models.scoping import team_scope
from posthog.models.team.team import Team
from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat import Heartbeater
+from posthog.temporal.mcp_analytics.intent_clustering.metrics import record_clusters_generated, record_intents_analyzed
from posthog.temporal.mcp_analytics.intent_clustering.models import (
IntentClusteringResult,
IntentClusteringWorkflowInputs,
@@ -161,6 +162,8 @@ async def compute_intent_clusters_activity(inputs: IntentClusteringWorkflowInput
await _persist_clusters(snapshot, clusters_blob)
n_clusters = len(clusters_blob.get("clusters", []))
+ record_intents_analyzed(len(aligned_records))
+ record_clusters_generated(n_clusters)
logger.info(
"mcpa.intent_clustering.computed",
team_id=inputs.team_id,
diff --git a/posthog/temporal/mcp_analytics/intent_clustering/constants.py b/posthog/temporal/mcp_analytics/intent_clustering/constants.py
index d3a3b1a2219a..0c6830761102 100644
--- a/posthog/temporal/mcp_analytics/intent_clustering/constants.py
+++ b/posthog/temporal/mcp_analytics/intent_clustering/constants.py
@@ -1,6 +1,6 @@
"""Configuration constants for the MCP analytics intent clustering workflow.
-Timeouts and retry policies mirror ``posthog/temporal/llm_analytics/trace_clustering/constants.py``
+Timeouts and retry policies mirror ``posthog/temporal/ai_observability/trace_clustering/constants.py``
— the workloads have the same shape (CPU-bound compute → external embedding
worker → ClickHouse-backed aggregates → ClickHouse write). Diverging numbers
without a real reason creates two competing reference points; reuse keeps
diff --git a/posthog/temporal/mcp_analytics/intent_clustering/metrics.py b/posthog/temporal/mcp_analytics/intent_clustering/metrics.py
new file mode 100644
index 000000000000..766743152260
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/intent_clustering/metrics.py
@@ -0,0 +1,160 @@
+"""Prometheus metrics for the MCP analytics intent clustering workflow.
+
+Pattern lifted from
+``posthog/temporal/ai_observability/trace_clustering/metrics.py`` — same
+shape of counters (started/finished/errors, items/clusters analysed) and
+histograms (workflow execution latency, activity execution latency,
+schedule-to-start latency).
+
+Metrics are emitted by ``ClusteringMetricsInterceptor`` automatically for
+the workflow/activity types listed below; helper functions are also
+exposed so the activity can record domain-specific counters from inside
+its body.
+"""
+
+import typing
+
+from django.conf import settings
+
+from temporalio import activity, workflow
+from temporalio.worker import (
+ ActivityInboundInterceptor,
+ ExecuteActivityInput,
+ ExecuteWorkflowInput,
+ Interceptor,
+ WorkflowInboundInterceptor,
+ WorkflowInterceptorClassInput,
+)
+
+from posthog.temporal.ai_observability.metrics import ExecutionTimeRecorder, get_metric_meter
+from posthog.temporal.mcp_analytics.intent_clustering.constants import COORDINATOR_WORKFLOW_NAME, WORKFLOW_NAME
+
+# Histograms registered into PrometheusConfig via common/worker.py.
+MCPA_CLUSTERING_LATENCY_HISTOGRAM_METRICS = (
+ "mcpa_clustering_activity_execution_latency",
+ "mcpa_clustering_activity_schedule_to_start_latency",
+ "mcpa_clustering_workflow_execution_latency",
+)
+MCPA_CLUSTERING_LATENCY_HISTOGRAM_BUCKETS = [
+ 1_000.0, # 1s
+ 5_000.0, # 5s
+ 10_000.0, # 10s
+ 30_000.0, # 30s
+ 60_000.0, # 1m
+ 120_000.0, # 2m
+ 300_000.0, # 5m
+ 600_000.0, # 10m
+ 900_000.0, # 15m
+ 1_800_000.0, # 30m
+]
+
+# Activity / workflow type sets the interceptor recognises.
+MCPA_CLUSTERING_ACTIVITY_TYPES = {
+ "compute_intent_clusters_activity",
+ "get_team_ids_for_mcp_analytics",
+}
+
+MCPA_CLUSTERING_WORKFLOW_TYPES = {
+ WORKFLOW_NAME,
+ COORDINATOR_WORKFLOW_NAME,
+}
+
+
+# Counter helpers ---------------------------------------------------------
+
+
+def increment_workflow_started(workflow_type: str) -> None:
+ meter = get_metric_meter({"workflow_type": workflow_type})
+ meter.create_counter("mcpa_clustering_workflow_started", "Intent clustering workflows started").add(1)
+
+
+def increment_workflow_finished(status: str, workflow_type: str) -> None:
+ meter = get_metric_meter({"status": status, "workflow_type": workflow_type})
+ meter.create_counter("mcpa_clustering_workflow_finished", "Intent clustering workflows finished").add(1)
+
+
+def record_intents_analyzed(count: int) -> None:
+ meter = get_metric_meter()
+ meter.create_counter("mcpa_clustering_intents_analyzed", "Intents fed into clustering").add(count)
+
+
+def record_clusters_generated(count: int) -> None:
+ meter = get_metric_meter()
+ meter.create_counter("mcpa_clustering_clusters_generated", "Clusters produced").add(count)
+
+
+def increment_errors(error_type: str) -> None:
+ # Only safe to call inside a worker context.
+ if not activity.in_activity() and not workflow.in_workflow():
+ return
+ meter = get_metric_meter({"error_type": error_type})
+ meter.create_counter("mcpa_clustering_errors", "Errors by exception type").add(1)
+
+
+# Interceptor -------------------------------------------------------------
+
+
+class MCPAClusteringMetricsInterceptor(Interceptor):
+ """Intercepts MCPA clustering workflows + activities to emit Prometheus metrics."""
+
+ task_queue = settings.MCPA_TASK_QUEUE
+
+ def intercept_activity(self, next: ActivityInboundInterceptor) -> ActivityInboundInterceptor:
+ return _MCPAClusteringActivityInterceptor(super().intercept_activity(next))
+
+ def workflow_interceptor_class(
+ self, input: WorkflowInterceptorClassInput
+ ) -> type[WorkflowInboundInterceptor] | None:
+ return _MCPAClusteringWorkflowInterceptor
+
+
+class _MCPAClusteringActivityInterceptor(ActivityInboundInterceptor):
+ async def execute_activity(self, input: ExecuteActivityInput) -> typing.Any:
+ activity_info = activity.info()
+ activity_type = activity_info.activity_type
+
+ if activity_type not in MCPA_CLUSTERING_ACTIVITY_TYPES:
+ return await super().execute_activity(input)
+
+ # Schedule-to-start latency (queue depth indicator).
+ scheduled = activity_info.scheduled_time
+ started = activity_info.started_time
+ if scheduled and started:
+ meter = get_metric_meter({"activity_type": activity_type})
+ meter.create_histogram_timedelta(
+ name="mcpa_clustering_activity_schedule_to_start_latency",
+ description="Time between activity scheduling and start",
+ unit="ms",
+ ).record(started - scheduled)
+
+ with ExecutionTimeRecorder(
+ "mcpa_clustering_activity_execution_latency",
+ description="Execution latency for MCPA clustering activities",
+ histogram_attributes={"activity_type": activity_type},
+ ):
+ # Don't increment_errors here — the same exception propagates to the
+ # workflow interceptor and would double-count. Matches the
+ # trace_clustering precedent (error tracking at workflow scope only).
+ return await super().execute_activity(input)
+
+
+class _MCPAClusteringWorkflowInterceptor(WorkflowInboundInterceptor):
+ async def execute_workflow(self, input: ExecuteWorkflowInput) -> typing.Any:
+ info = workflow.info()
+ if info.workflow_type not in MCPA_CLUSTERING_WORKFLOW_TYPES:
+ return await super().execute_workflow(input)
+
+ increment_workflow_started(info.workflow_type)
+ with ExecutionTimeRecorder(
+ "mcpa_clustering_workflow_execution_latency",
+ description="End-to-end workflow execution latency for MCPA clustering",
+ histogram_attributes={"workflow_type": info.workflow_type},
+ ):
+ try:
+ result = await super().execute_workflow(input)
+ increment_workflow_finished("completed", info.workflow_type)
+ return result
+ except Exception as e:
+ increment_errors(type(e).__name__)
+ increment_workflow_finished("failed", info.workflow_type)
+ raise
diff --git a/posthog/temporal/mcp_analytics/intent_clustering/tests/test_metrics.py b/posthog/temporal/mcp_analytics/intent_clustering/tests/test_metrics.py
new file mode 100644
index 000000000000..7f32ac6b1884
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/intent_clustering/tests/test_metrics.py
@@ -0,0 +1,54 @@
+"""Unit tests for the MCPA clustering metrics interceptor surface.
+
+These tests assert the configuration shape (workflow/activity types,
+histogram metric names) rather than end-to-end metric emission — Prometheus
+output is exercised by the worker's own integration tests.
+"""
+
+import pytest
+
+from posthog.temporal.mcp_analytics.intent_clustering.constants import COORDINATOR_WORKFLOW_NAME, WORKFLOW_NAME
+from posthog.temporal.mcp_analytics.intent_clustering.metrics import (
+ MCPA_CLUSTERING_ACTIVITY_TYPES,
+ MCPA_CLUSTERING_LATENCY_HISTOGRAM_BUCKETS,
+ MCPA_CLUSTERING_LATENCY_HISTOGRAM_METRICS,
+ MCPA_CLUSTERING_WORKFLOW_TYPES,
+ MCPAClusteringMetricsInterceptor,
+)
+
+
+class TestInterceptorConfig:
+ def test_task_queue_targets_mcpa(self) -> None:
+ from django.conf import settings
+
+ assert MCPAClusteringMetricsInterceptor.task_queue == settings.MCPA_TASK_QUEUE
+
+ @pytest.mark.parametrize(
+ "activity_name",
+ [
+ "compute_intent_clusters_activity",
+ "get_team_ids_for_mcp_analytics",
+ ],
+ )
+ def test_activity_types_include_required_names(self, activity_name: str) -> None:
+ assert activity_name in MCPA_CLUSTERING_ACTIVITY_TYPES
+
+ @pytest.mark.parametrize(
+ "workflow_name",
+ [WORKFLOW_NAME, COORDINATOR_WORKFLOW_NAME],
+ )
+ def test_workflow_types_include_required_names(self, workflow_name: str) -> None:
+ assert workflow_name in MCPA_CLUSTERING_WORKFLOW_TYPES
+
+ @pytest.mark.parametrize("metric_name", MCPA_CLUSTERING_LATENCY_HISTOGRAM_METRICS)
+ def test_histogram_metric_name_is_prefixed(self, metric_name: str) -> None:
+ # Prefix is load-bearing for Grafana dashboards — if anyone renames
+ # the prefix, the dashboards stop working silently.
+ assert metric_name.startswith("mcpa_clustering_"), metric_name
+
+ def test_histogram_buckets_cover_workflow_and_activity_ranges(self) -> None:
+ # Workflows can run up to 30 min (WORKFLOW_EXECUTION_TIMEOUT in
+ # constants); the bucket list needs an upper bucket >= that timeout.
+ assert max(MCPA_CLUSTERING_LATENCY_HISTOGRAM_BUCKETS) >= 30 * 60 * 1_000
+ # Sub-second buckets matter for the per-stage heartbeats.
+ assert min(MCPA_CLUSTERING_LATENCY_HISTOGRAM_BUCKETS) <= 1_000