: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
fix(mcp-analytics): fix intent clustering truncation and dispatch (#73566)
Daniel Viscaaa9d5ccbfcce
diff --git a/products/mcp_analytics/backend/facade/api.py b/products/mcp_analytics/backend/facade/api.pyindex 11c592ae6e70..8e7d5f0772c7 100644--- a/products/mcp_analytics/backend/facade/api.py+++ b/products/mcp_analytics/backend/facade/api.py@@ -1,5 +1,6 @@from datetime import datetime+from django.db import transactionfrom django.utils import timezonefrom posthog.models.team.team import Team@@ -116,31 +117,57 @@ def trigger_intent_cluster_recompute(team: Team, user: User | None) -> None:the workflow's compute activity writes the snapshot status (COMPUTING →IDLE/ERROR) as it runs."""- import time- import uuidimport asynciofrom django.conf import settings+ from temporalio.exceptions import WorkflowAlreadyStartedError+from posthog.temporal.common.client import async_connect- from posthog.temporal.mcp_analytics.intent_clustering.constants import CHILD_WORKFLOW_ID_PREFIX, WORKFLOW_NAME+ from posthog.temporal.mcp_analytics.intent_clustering.constants import (+ CHILD_WORKFLOW_ID_PREFIX,+ WORKFLOW_EXECUTION_TIMEOUT,+ WORKFLOW_NAME,+ )from posthog.temporal.mcp_analytics.intent_clustering.models import IntentClusteringWorkflowInputsfrom products.mcp_analytics.backend.models import MCPIntentClusterSnapshot- # Flip to COMPUTING before dispatching so the 202 response and any- # immediate poll see consistent state. The workflow's activity- # re-asserts COMPUTING on pickup; both writes are idempotent.- MCPIntentClusterSnapshot.objects.update_or_create(- team=team,- defaults={- "status": MCPIntentClusterSnapshot.Status.COMPUTING,- "error_message": "",- "last_computed_by": user,- },- )-- workflow_id = f"{CHILD_WORKFLOW_ID_PREFIX}-{team.id}-adhoc-{int(time.time() * 1000)}-{uuid.uuid4().hex[:8]}"+ # One run at a time per team: while a fresh run holds the snapshot in+ # COMPUTING, another dispatch would only stack a duplicate workflow on the+ # queue behind it. A run stuck past STALE_COMPUTING_THRESHOLD is presumed+ # dead (same rule as the sweep in get_intent_cluster_snapshot), so a+ # retry is allowed through. The row lock serialises concurrent triggers so+ # they can't all pass the freshness check before any of them claims the+ # snapshot; the Temporal dispatch stays outside the transaction.+ # Claiming COMPUTING before dispatching also means the 202 response and+ # any immediate poll see consistent state — the workflow's activity+ # re-asserts COMPUTING on pickup, and both writes are idempotent.+ with transaction.atomic():+ snapshot, created = MCPIntentClusterSnapshot.objects.select_for_update().get_or_create(+ team=team,+ defaults={+ "status": MCPIntentClusterSnapshot.Status.COMPUTING,+ "error_message": "",+ "last_computed_by": user,+ },+ )+ if not created:+ if (+ snapshot.status == MCPIntentClusterSnapshot.Status.COMPUTING+ and snapshot.updated_at >= timezone.now() - logic.STALE_COMPUTING_THRESHOLD+ ):+ return+ snapshot.status = MCPIntentClusterSnapshot.Status.COMPUTING+ snapshot.error_message = ""+ snapshot.last_computed_by = user+ snapshot.save(update_fields=["status", "error_message", "last_computed_by", "updated_at"])++ # Deterministic per team: Temporal refuses a second start while a run with+ # this id is live, so even a run that outlives STALE_COMPUTING_THRESHOLD+ # (which is shorter than the 20-minute execution timeout) can't be+ # overlapped by a retry — the id frees up once the previous run closes.+ workflow_id = f"{CHILD_WORKFLOW_ID_PREFIX}-{team.id}-adhoc"# Create + use the Temporal client inside one event loop. sync_connect()# would build the client in asgiref's managed loop and then asyncio.run()@@ -149,15 +176,24 @@ def trigger_intent_cluster_recompute(team: Team, user: User | None) -> None:# Matches the cluster_mcp_intents management command pattern.async def _start() -> None:client = await async_connect()+ # execution_timeout bounds the whole run *including* queue wait: with+ # no worker polling the task queue, an unbounded workflow sits pending+ # forever and every recompute click stacks another one behind it.await client.start_workflow(WORKFLOW_NAME,IntentClusteringWorkflowInputs(team_id=team.id, user_id=user.id if user else None),id=workflow_id,task_queue=settings.MCPA_TASK_QUEUE,+ execution_timeout=WORKFLOW_EXECUTION_TIMEOUT,)try:asyncio.run(_start())+ except WorkflowAlreadyStartedError:+ # The previous run outlived the stale threshold but is genuinely still+ # running — leave the snapshot in COMPUTING; the live run flips the+ # status when it finishes.+ returnexcept Exception:# Dispatch failed, so no activity will ever flip the status — revert# the optimistic COMPUTING write instead of leaving the snapshot stuckdiff --git a/products/mcp_analytics/backend/intent_clustering.py b/products/mcp_analytics/backend/intent_clustering.pyindex 33afce8361c1..35a35eee4b74 100644--- a/products/mcp_analytics/backend/intent_clustering.py+++ b/products/mcp_analytics/backend/intent_clustering.py@@ -1,8 +1,9 @@"""Intent clustering pipeline for MCP analytics.Four pure functions, each independently testable, that together build a cluster-snapshot of MCP intents. The Celery task in ``tasks.py`` orchestrates them and-persists the result.+snapshot of MCP intents. The Temporal activity in+``posthog/temporal/mcp_analytics/intent_clustering/activities.py`` orchestrates+them and persists the result.Why pure functions: the algorithm is the riskiest part of this feature. Keepingeach stage as a pure function over numpy arrays / dataclasses makes the@@ -27,6 +28,7 @@ from typing import Anyfrom django.utils import timezoneimport numpy as np+import structlogfrom sklearn.cluster import AgglomerativeClusteringfrom posthog.hogql import ast@@ -41,6 +43,8 @@ from posthog.sync import database_sync_to_asyncfrom products.mcp_analytics.backend.constants import MCP_TOOL_CALL_EVENTfrom products.mcp_analytics.backend.models import MCPIntentEmbeddingCache, MCPSession+logger = structlog.get_logger(__name__)+# ConstantsEMBEDDING_MODEL = "text-embedding-3-small-1536"EMBEDDING_PREFIX = "User intent: "@@ -86,6 +90,12 @@ class IntentRecord:# DEFAULT_TOP_N_INTENTS=500 a larger sample only adds long-tail singletons.MAX_CORPUS_SESSIONS = 2000+# execute_hogql_query injects LIMIT 100 into any query without an explicit+# LIMIT — far below what the per-session stats and journey queries return at+# production scale (one-plus rows per corpus session). Cap explicitly at the+# HogQL per-query maximum so results are never silently truncated.+MAX_QUERY_ROWS = 50_000+# Event-sourced intents are free text written by the calling agent — clip them# so one oversized value can't blow up embedding requests (the worker's model# has a token ceiling) or bloat the snapshot blob. Real intents are one or two@@ -132,6 +142,7 @@ WHERE event = {event}AND properties.$mcp_tool_name != ''AND timestamp >= now() - INTERVAL {lookback_days} DAYGROUP BY session_id, tool_name+LIMIT {max_rows}"""# Per-session ordered tool sequence + whether any call errored. arrayMap +@@ -154,6 +165,7 @@ WHERE event = {event}AND properties.$mcp_tool_name != ''AND timestamp >= now() - INTERVAL {lookback_days} DAYGROUP BY session_id+LIMIT {max_rows}"""@@ -224,6 +236,7 @@ def fetch_intent_corpus("event": ast.Constant(value=MCP_TOOL_CALL_EVENT),"session_ids": ast.Tuple(exprs=[ast.Constant(value=sid) for sid in session_ids]),"lookback_days": ast.Constant(value=lookback_days),+ "max_rows": ast.Constant(value=MAX_QUERY_ROWS),},)with tags_context(product=Product.MCP, feature=Feature.QUERY, team_id=team.id):@@ -292,6 +305,7 @@ def fetch_session_journeys("event": ast.Constant(value=MCP_TOOL_CALL_EVENT),"session_ids": ast.Tuple(exprs=[ast.Constant(value=sid) for sid in session_ids]),"lookback_days": ast.Constant(value=lookback_days),+ "max_rows": ast.Constant(value=MAX_QUERY_ROWS),},)with tags_context(product=Product.MCP, feature=Feature.QUERY, team_id=team.id):@@ -470,6 +484,18 @@ async def embed_intents_async(team: Team, texts: list[str]) -> tuple[np.ndarray,vectors.append(vector)valid_indices.append(i)+ failed_count = len(texts) - len(valid_indices)+ if failed_count:+ # Failures are swallowed per text so one bad request can't sink the+ # batch — surface the aggregate so a degraded embedding worker is+ # visible instead of silently shrinking the corpus.+ logger.warning(+ "mcpa.intent_clustering.embedding_failures",+ team_id=team.id,+ failed=failed_count,+ total=len(texts),+ )+if not vectors:return np.zeros((0, 0), dtype=np.float32), []diff --git a/products/mcp_analytics/backend/tests/test_intent_clustering.py b/products/mcp_analytics/backend/tests/test_intent_clustering.pyindex cd118b628634..7a2815c59093 100644--- a/products/mcp_analytics/backend/tests/test_intent_clustering.py+++ b/products/mcp_analytics/backend/tests/test_intent_clustering.py@@ -9,6 +9,7 @@ import mathimport uuidimport asynciofrom datetime import UTC, datetime, timedelta+from types import SimpleNamespacefrom typing import Anyimport pytest@@ -18,6 +19,8 @@ from unittest.mock import patchimport numpy as npfrom parameterized import parameterized+from posthog.hogql.constants import DEFAULT_RETURNED_ROWS+from posthog.api.embedding_worker import EmbeddingResponsefrom products.mcp_analytics.backend import intent_clustering@@ -36,6 +39,7 @@ from products.mcp_analytics.backend.intent_clustering import (cluster_embeddings,embed_intents_async,fetch_intent_corpus,+ fetch_session_journeys,)from products.mcp_analytics.backend.models import MCPIntentEmbeddingCache, MCPSessionfrom products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixin@@ -433,6 +437,25 @@ class TestFetchIntentCorpus(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixiassert [r.intent_text for r in records] == ["look up feature flag rollout"]assert intent_by_session == {"real": "look up feature flag rollout"}+ def test_tool_stats_and_journeys_are_not_truncated_at_the_default_hogql_limit(self) -> None:+ # execute_hogql_query injects LIMIT 100 into any query without an explicit+ # LIMIT. The per-session tool-stats and journey queries return one-plus rows+ # per corpus session, so a corpus above 100 sessions silently lost tool+ # counts and journeys for everything past the first 100 rows.+ n_sessions = DEFAULT_RETURNED_ROWS + 20+ for i in range(n_sessions):+ self._seed_tool_call(f"session-{i}", "execute_sql", intent=f"unique intent {i}")+ flush_persons_and_events()++ records, intent_by_session = fetch_intent_corpus(self.team)++ assert len(intent_by_session) == n_sessions+ assert len(records) == n_sessions+ assert all(r.tool_counts == {"execute_sql": 1} for r in records)++ journeys = fetch_session_journeys(self.team, list(intent_by_session.keys()))+ assert len(journeys) == n_sessions+# Embedding helpers -----------------------------------------------------@@ -484,7 +507,9 @@ class TestEmbedIntentsAsyncCacheLogic:patch.object(intent_clustering, "_persist_embedding", side_effect=_persist),patch.object(intent_clustering, "async_generate_embedding", side_effect=worker),):- return asyncio.run(embed_intents_async(object(), texts)) # type: ignore[arg-type]+ # A stub with an `id` stands in for Team — the failure-path log+ # reads team.id, and the cache IO that needs a real team is mocked.+ return asyncio.run(embed_intents_async(SimpleNamespace(id=0), texts)) # type: ignore[arg-type]def test_first_run_populates_cache(self) -> None:cached: dict[str, np.ndarray] = {}diff --git a/products/mcp_analytics/backend/tests/test_presentation.py b/products/mcp_analytics/backend/tests/test_presentation.pyindex f7adfcca56c6..bd8dbb51782d 100644--- a/products/mcp_analytics/backend/tests/test_presentation.py+++ b/products/mcp_analytics/backend/tests/test_presentation.py@@ -8,10 +8,15 @@ from django.test import SimpleTestCasefrom parameterized import parameterizedfrom rest_framework import status+from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.models import Organization, Teamfrom posthog.models.utils import uuid7-from posthog.temporal.mcp_analytics.intent_clustering.constants import CHILD_WORKFLOW_ID_PREFIX, WORKFLOW_NAME+from posthog.temporal.mcp_analytics.intent_clustering.constants import (+ CHILD_WORKFLOW_ID_PREFIX,+ WORKFLOW_EXECUTION_TIMEOUT,+ WORKFLOW_NAME,+)from products.mcp_analytics.backend import intent_generationfrom products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshot, MCPSession@@ -226,7 +231,60 @@ class TestMCPAnalyticsPresentation(_MCPAnalyticsTeamScopedTestMixin, APIBaseTestassert call_args.args[0] == WORKFLOW_NAMEassert call_args.args[1].team_id == self.team.idassert call_args.args[1].user_id == self.user.id- assert call_args.kwargs["id"].startswith(f"{CHILD_WORKFLOW_ID_PREFIX}-{self.team.id}-adhoc-")+ # Deterministic per team so Temporal itself dedupes concurrent runs.+ assert call_args.kwargs["id"] == f"{CHILD_WORKFLOW_ID_PREFIX}-{self.team.id}-adhoc"+ # Without a bound, a dispatch onto a queue with no live worker sits+ # pending forever and repeat clicks stack workflows behind it.+ assert call_args.kwargs["execution_timeout"] == WORKFLOW_EXECUTION_TIMEOUT++ def test_intent_clusters_recompute_already_running_workflow_is_not_an_error(self) -> None:+ # A snapshot stale-swept past STALE_COMPUTING_THRESHOLD can belong to a+ # workflow that is still live (the execution timeout is longer) —+ # Temporal refuses the duplicate id. That is "already running", not a+ # dispatch failure: the generic revert below it must not mark ERROR.+ mock_client = MagicMock()+ mock_client.start_workflow = AsyncMock(+ side_effect=WorkflowAlreadyStartedError(f"{CHILD_WORKFLOW_ID_PREFIX}-1-adhoc", WORKFLOW_NAME)+ )+ with patch("posthog.temporal.common.client.async_connect", new=AsyncMock(return_value=mock_client)):+ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_analytics/intent_clusters/recompute/", {}, format="json"+ )++ assert response.status_code == status.HTTP_202_ACCEPTED+ assert response.json()["status"] == "computing"+ snapshot = MCPIntentClusterSnapshot.objects.get(team=self.team)+ assert snapshot.status == MCPIntentClusterSnapshot.Status.COMPUTING+ assert snapshot.error_message == ""++ @parameterized.expand(+ [+ # A fresh COMPUTING run owns the snapshot: don't stack a duplicate workflow.+ ("fresh_computing_skips_dispatch", timedelta(minutes=1), 0),+ # A run stuck past the stale threshold is presumed dead: allow the retry through.+ ("stale_computing_dispatches_again", timedelta(minutes=11), 1),+ ]+ )+ def test_intent_clusters_recompute_throttles_while_computing(+ self, _name: str, computing_age: timedelta, expected_dispatches: int+ ) -> None:+ MCPIntentClusterSnapshot.objects.update_or_create(+ team=self.team,+ defaults={"status": MCPIntentClusterSnapshot.Status.COMPUTING},+ )+ # updated_at is auto_now — backdate it directly to position the run's age.+ MCPIntentClusterSnapshot.objects.filter(team=self.team).update(updated_at=datetime.now(tz=UTC) - computing_age)++ mock_client = MagicMock()+ mock_client.start_workflow = AsyncMock(return_value=MagicMock())+ with patch("posthog.temporal.common.client.async_connect", new=AsyncMock(return_value=mock_client)):+ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_analytics/intent_clusters/recompute/", {}, format="json"+ )++ assert response.status_code == status.HTTP_202_ACCEPTED+ assert response.json()["status"] == "computing"+ assert mock_client.start_workflow.await_count == expected_dispatchesdef test_intent_clusters_recompute_dispatch_failure_reverts_to_error(self) -> None:# If the workflow never starts, no activity will flip the status —