: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(mcp-analytics): route intent cluster recompute through temporal (#67545)
Daniel Visca20e349c7b3dc
diff --git a/products/mcp_analytics/backend/facade/api.py b/products/mcp_analytics/backend/facade/api.pyindex f72881c2d9cd..9c096397c651 100644--- a/products/mcp_analytics/backend/facade/api.py+++ b/products/mcp_analytics/backend/facade/api.py@@ -1,5 +1,7 @@from datetime import datetime+from django.utils import timezone+from posthog.models.team.team import Teamfrom posthog.models.user import User@@ -84,17 +86,27 @@ def get_intent_cluster_snapshot(team: Team) -> contracts.IntentClusterSnapshot:def trigger_intent_cluster_recompute(team: Team, user: User | None) -> None:- """Kick off the intent cluster recompute Celery task.+ """Kick off the intent cluster recompute Temporal workflow.- Returns immediately. Use ``get_intent_cluster_snapshot`` to poll status.+ Returns immediately. Use ``get_intent_cluster_snapshot`` to poll status —+ the workflow's compute activity writes the snapshot status (COMPUTING →+ IDLE/ERROR) as it runs."""- # Imports here to avoid loading Celery at module import time.+ import time+ import uuid+ import asyncio++ from django.conf import settings++ 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.models import IntentClusteringWorkflowInputs+from products.mcp_analytics.backend.models import MCPIntentClusterSnapshot- from products.mcp_analytics.backend.tasks.tasks import compute_intent_clusters- # Flip to COMPUTING before enqueuing so the 202 response and any- # immediate poll see consistent state. The task re-asserts COMPUTING- # on pickup; both writes are idempotent.+ # 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={@@ -103,4 +115,32 @@ def trigger_intent_cluster_recompute(team: Team, user: User | None) -> None:"last_computed_by": user,},)- compute_intent_clusters.delay(team.id, user.id if user else None)++ workflow_id = f"{CHILD_WORKFLOW_ID_PREFIX}-{team.id}-adhoc-{int(time.time() * 1000)}-{uuid.uuid4().hex[:8]}"++ # Create + use the Temporal client inside one event loop. sync_connect()+ # would build the client in asgiref's managed loop and then asyncio.run()+ # would call start_workflow in a different loop; the temporalio Rust+ # bridge is currently loop-agnostic but the inconsistency is fragile.+ # Matches the cluster_mcp_intents management command pattern.+ async def _start() -> None:+ client = await async_connect()+ 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,+ )++ try:+ asyncio.run(_start())+ except Exception:+ # Dispatch failed, so no activity will ever flip the status — revert+ # the optimistic COMPUTING write instead of leaving the snapshot stuck+ # until the stale-COMPUTING sweep in get_intent_cluster_snapshot.+ MCPIntentClusterSnapshot.objects.filter(team=team).update(+ status=MCPIntentClusterSnapshot.Status.ERROR,+ error_message="Failed to start the intent clustering workflow",+ updated_at=timezone.now(),+ )+ raisediff --git a/products/mcp_analytics/backend/management/commands/cluster_mcp_intents.py b/products/mcp_analytics/backend/management/commands/cluster_mcp_intents.pyindex e1a6c6fdcf0b..227fd2faa496 100644--- a/products/mcp_analytics/backend/management/commands/cluster_mcp_intents.py+++ b/products/mcp_analytics/backend/management/commands/cluster_mcp_intents.py@@ -1,19 +1,26 @@"""Manual end-to-end validation for the intent clustering pipeline.-Runs the same Celery task that powers the API, synchronously, against a-real team's ClickHouse data, and pretty-prints the resulting snapshot.+Starts a one-off ``DailyIntentClusteringWorkflow`` execution and waits for+it, then pretty-prints the resulting snapshot. Requires a running Temporal+worker on ``settings.MCPA_TASK_QUEUE`` (provided locally by ``hogli start``)."""import json+import time+import uuid+import asynciofrom typing import Any+from django.conf import settingsfrom django.core.management.base import BaseCommand, CommandParserfrom posthog.models.scoping import team_scopefrom posthog.models.team.team import Team+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.models import IntentClusteringWorkflowInputsfrom products.mcp_analytics.backend.models import MCPIntentClusterSnapshot-from products.mcp_analytics.backend.tasks.tasks import compute_intent_clustersclass Command(BaseCommand):@@ -45,8 +52,30 @@ class Command(BaseCommand):returnwindow_label = f"{lookback_days} day(s)" if lookback_days is not None else "default window"- self.stdout.write(f"Running intent clustering for team {team_id} ({window_label})...")- compute_intent_clusters.apply(args=[team_id, None, lookback_days]).get()+ self.stdout.write(+ f"Running intent clustering for team {team_id} ({window_label}) via Temporal "+ f"on {settings.MCPA_TASK_QUEUE}..."+ )++ workflow_inputs = IntentClusteringWorkflowInputs(+ team_id=team_id,+ **({"lookback_days": lookback_days} if lookback_days is not None else {}),+ )+ workflow_id = f"{CHILD_WORKFLOW_ID_PREFIX}-{team_id}-cli-{int(time.time() * 1000)}-{uuid.uuid4().hex[:8]}"++ async def _run() -> None:+ # async_connect() must be used here — we're already inside+ # an event loop via asyncio.run(_run()), and sync_connect()+ # wraps async_to_sync which can't nest event loops.+ client = await async_connect()+ await client.execute_workflow(+ WORKFLOW_NAME,+ workflow_inputs,+ id=workflow_id,+ task_queue=settings.MCPA_TASK_QUEUE,+ )++ asyncio.run(_run())with team_scope(team_id):snapshot = MCPIntentClusterSnapshot.objects.filter(team_id=team_id).first()diff --git a/products/mcp_analytics/backend/tasks/__init__.py b/products/mcp_analytics/backend/tasks/__init__.pydeleted file mode 100644index 31aea54bd54b..000000000000--- a/products/mcp_analytics/backend/tasks/__init__.py+++ /dev/null@@ -1,7 +0,0 @@-# Re-export tasks for Celery autodiscover. autodiscover_tasks() imports the-# `tasks` package (this __init__.py), not its submodules, so any @shared_task-# defined inside `tasks/tasks.py` needs to be re-exported here to be visible-# to the worker.-from products.mcp_analytics.backend.tasks.tasks import compute_intent_clusters--__all__ = ["compute_intent_clusters"]diff --git a/products/mcp_analytics/backend/tasks/schedules.py b/products/mcp_analytics/backend/tasks/schedules.pydeleted file mode 100644index c6207083c228..000000000000--- a/products/mcp_analytics/backend/tasks/schedules.py+++ /dev/null@@ -1,2 +0,0 @@-"""Celery beat schedules for mcp_analytics."""-# Define periodic task schedules herediff --git a/products/mcp_analytics/backend/tasks/tasks.py b/products/mcp_analytics/backend/tasks/tasks.pydeleted file mode 100644index 68fa2f9e3b2b..000000000000--- a/products/mcp_analytics/backend/tasks/tasks.py+++ /dev/null@@ -1,149 +0,0 @@-"""Celery tasks for mcp_analytics.--Async entrypoints that orchestrate the intent clustering pipeline. Task-functions stay thin: they coordinate state transitions and call into the pure-clustering module.-"""--import asyncio-from typing import Any--from django.db import transaction-from django.utils import timezone--import structlog-from celery import shared_task--from posthog.models.scoping import with_team_scope--logger = structlog.get_logger(__name__)---@shared_task(- name="products.mcp_analytics.backend.tasks.compute_intent_clusters",- bind=True,- ignore_result=True,- acks_late=True,- max_retries=2,-)-@with_team_scope()-def compute_intent_clusters(- self: Any, team_id: int, user_id: int | None = None, lookback_days: int | None = None-) -> None:- """Recompute the intent cluster snapshot for a team.-- Flow:- 1. Mark the snapshot as ``computing`` (creates a row on first run).- 2. Fetch the intent corpus, embed it, cluster it, build the snapshot.- 3. Persist the snapshot atomically and mark ``idle``.- 4. On failure, mark ``error`` with the message; rely on Celery retry.-- ``lookback_days`` overrides the default window used by both the Postgres- session query and the joined ClickHouse query. ``None`` keeps the default.- """- # Imports inside the task so Celery autoimport doesn't pull heavy deps- # (numpy/sklearn/httpx) at worker startup.- from posthog.models.team.team import Team-- from products.mcp_analytics.backend import intent_clustering- from products.mcp_analytics.backend.models import MCPIntentClusterSnapshot-- try:- team = Team.objects.get(pk=team_id)- except Team.DoesNotExist:- logger.warning("mcp_analytics.intent_clusters.team_not_found", team_id=team_id)- return-- user = None- if user_id is not None:- from posthog.models.user import User-- user = User.objects.filter(pk=user_id).first()-- snapshot, _ = MCPIntentClusterSnapshot.objects.update_or_create(- team=team,- defaults={- "status": MCPIntentClusterSnapshot.Status.COMPUTING,- "error_message": "",- "last_computed_by": user,- },- )-- corpus_kwargs: dict[str, int] = {}- if lookback_days is not None:- corpus_kwargs["lookback_days"] = lookback_days-- try:- records, intent_by_session = intent_clustering.fetch_intent_corpus(team, **corpus_kwargs)- if not records:- _save_empty_snapshot(snapshot)- logger.info("mcp_analytics.intent_clusters.no_intents_found", team_id=team_id)- return-- embeddings, valid_indices = asyncio.run(- intent_clustering.embed_intents_async(team, [r.intent_text for r in records])- )- if len(valid_indices) == 0:- raise RuntimeError("All embedding requests failed")-- aligned_records = [records[i] for i in valid_indices]- labels = intent_clustering.cluster_embeddings(embeddings)-- # Fetch ordered tool-call sequences for every session and aggregate- # them per cluster so the UI can render a Sankey of agent journeys.- session_journeys = intent_clustering.fetch_session_journeys(- team, list(intent_by_session.keys()), **corpus_kwargs- )- intent_to_sessions: dict[str, list[str]] = {}- for sid, intent_text in intent_by_session.items():- intent_to_sessions.setdefault(intent_text, []).append(sid)- journeys_by_cluster = intent_clustering.aggregate_journeys_per_cluster(- aligned_records, labels, session_journeys, intent_to_sessions- )-- clusters_blob = intent_clustering.build_snapshot(- aligned_records, labels, embeddings, journeys_by_cluster=journeys_by_cluster- )-- with transaction.atomic():- snapshot.clusters = clusters_blob- snapshot.status = MCPIntentClusterSnapshot.Status.IDLE- snapshot.error_message = ""- snapshot.last_computed_at = timezone.now()- snapshot.save(update_fields=["clusters", "status", "error_message", "last_computed_at", "updated_at"])-- logger.info(- "mcp_analytics.intent_clusters.computed",- team_id=team_id,- n_intents=len(aligned_records),- n_clusters=len(clusters_blob.get("clusters", [])),- )-- except Exception as exc:- logger.exception("mcp_analytics.intent_clusters.failed", team_id=team_id, error=str(exc))- snapshot.status = MCPIntentClusterSnapshot.Status.ERROR- snapshot.error_message = str(exc)[:5000]- snapshot.save(update_fields=["status", "error_message", "updated_at"])- if self.request.retries < self.max_retries:- raise self.retry(exc=exc, countdown=60)- raise---def _save_empty_snapshot(snapshot: Any) -> None:- # Importing the module avoids a circular import at worker startup.- from products.mcp_analytics.backend.intent_clustering import DEFAULT_DISTANCE_THRESHOLD, EMBEDDING_MODEL- from products.mcp_analytics.backend.models import MCPIntentClusterSnapshot-- snapshot.clusters = {- "clusters": [],- "computed_with": {- "distance_threshold": DEFAULT_DISTANCE_THRESHOLD,- "embedding_model": EMBEDDING_MODEL,- "n_intents": 0,- "n_clusters": 0,- },- }- snapshot.status = MCPIntentClusterSnapshot.Status.IDLE- snapshot.error_message = ""- snapshot.last_computed_at = timezone.now()- snapshot.save(update_fields=["clusters", "status", "error_message", "last_computed_at", "updated_at"])diff --git a/products/mcp_analytics/backend/tests/test_presentation.py b/products/mcp_analytics/backend/tests/test_presentation.pyindex 45f11433a5ef..b4069c6811db 100644--- a/products/mcp_analytics/backend/tests/test_presentation.py+++ b/products/mcp_analytics/backend/tests/test_presentation.py@@ -1,7 +1,7 @@from datetime import UTC, datetime, timedeltafrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event-from unittest.mock import patch+from unittest.mock import AsyncMock, MagicMock, patchfrom django.core.cache import cachefrom django.test import SimpleTestCase@@ -11,6 +11,7 @@ from rest_framework import statusfrom posthog.models import Organization, Teamfrom posthog.models.utils import uuid7+from posthog.temporal.mcp_analytics.intent_clustering.constants import CHILD_WORKFLOW_ID_PREFIX, WORKFLOW_NAMEfrom products.mcp_analytics.backend import intent_generationfrom products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshot, MCPSession@@ -197,12 +198,15 @@ class TestMCPAnalyticsPresentation(_MCPAnalyticsTeamScopedTestMixin, APIBaseTestassert data["clusters"][0]["label"] == "check feature flag rollout"assert data["computed_with"]["n_clusters"] == 1- def test_intent_clusters_recompute_enqueues_task_and_returns_computing(self) -> None:- # Mock only the Celery dispatch so the synchronous COMPUTING write- # still runs. The 202 body should reflect the new state, not the- # stale pre-trigger state.+ def test_intent_clusters_recompute_starts_workflow_and_returns_computing(self) -> None:+ # Mock async_connect to return a client whose start_workflow is an+ # AsyncMock — the facade awaits both inside asyncio.run. The+ # synchronous COMPUTING write still runs against the real DB so+ # the 202 body reflects the new state, not the stale pre-trigger one.+ mock_client = MagicMock()+ mock_client.start_workflow = AsyncMock(return_value=MagicMock())with (- patch("products.mcp_analytics.backend.tasks.tasks.compute_intent_clusters.delay") as mock_delay,+ patch("posthog.temporal.common.client.async_connect", new=AsyncMock(return_value=mock_client)),patch("posthoganalytics.feature_enabled", return_value=True),):response = self.client.post(@@ -211,10 +215,35 @@ class TestMCPAnalyticsPresentation(_MCPAnalyticsTeamScopedTestMixin, APIBaseTestassert response.status_code == status.HTTP_202_ACCEPTEDassert response.json()["status"] == "computing"- mock_delay.assert_called_once_with(self.team.id, self.user.id)snapshot = MCPIntentClusterSnapshot.objects.get(team=self.team)assert snapshot.status == MCPIntentClusterSnapshot.Status.COMPUTINGassert snapshot.last_computed_by_id == self.user.id+ mock_client.start_workflow.assert_awaited_once()+ call_args = mock_client.start_workflow.call_args+ assert call_args.args[0] == WORKFLOW_NAME+ assert call_args.args[1].team_id == self.team.id+ assert call_args.args[1].user_id == self.user.id+ assert call_args.kwargs["id"].startswith(f"{CHILD_WORKFLOW_ID_PREFIX}-{self.team.id}-adhoc-")++ def test_intent_clusters_recompute_dispatch_failure_reverts_to_error(self) -> None:+ # If the workflow never starts, no activity will flip the status —+ # the endpoint must revert its own COMPUTING write, not leave the+ # snapshot stuck until the stale-COMPUTING sweep.+ with (+ patch(+ "posthog.temporal.common.client.async_connect",+ new=AsyncMock(side_effect=RuntimeError("temporal unreachable")),+ ),+ patch("posthoganalytics.feature_enabled", return_value=True),+ ):+ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_analytics/intent_clusters/recompute/", {}, format="json"+ )++ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR+ snapshot = MCPIntentClusterSnapshot.objects.get(team=self.team)+ assert snapshot.status == MCPIntentClusterSnapshot.Status.ERROR+ assert snapshot.error_message == "Failed to start the intent clustering workflow"def test_feedback_list_is_team_scoped(self) -> None:MCPAnalyticsSubmission.objects.create(diff --git a/products/mcp_analytics/backend/tests/test_tasks.py b/products/mcp_analytics/backend/tests/test_tasks.pydeleted file mode 100644index 959aac86acd0..000000000000--- a/products/mcp_analytics/backend/tests/test_tasks.py+++ /dev/null@@ -1,81 +0,0 @@-from posthog.test.base import APIBaseTest-from unittest.mock import patch--import numpy as np--from products.mcp_analytics.backend import intent_clustering-from products.mcp_analytics.backend.models import MCPIntentClusterSnapshot-from products.mcp_analytics.backend.tasks import tasks-from products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixin---class TestComputeIntentClusters(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest):- def _stub_corpus(self) -> list[intent_clustering.IntentRecord]:- return [- intent_clustering.IntentRecord(- intent_text="check feature flag rollout",- frequency=10,- tool_counts={"feature_flag_get": 10},- error_counts={},- ),- intent_clustering.IntentRecord(- intent_text="look up feature flag status",- frequency=4,- tool_counts={"feature_flag_get": 4},- error_counts={},- ),- ]-- def _stub_embeddings(self) -> tuple[np.ndarray, list[int]]:- # Two near-identical unit vectors so they cluster together.- vectors = np.array(- [- [1.0, 0.0, 0.0],- [0.99, 0.05, 0.0],- ],- dtype=np.float32,- )- vectors = vectors / np.linalg.norm(vectors, axis=1, keepdims=True)- return vectors, [0, 1]-- def test_writes_snapshot_on_success(self) -> None:- with (- patch.object(intent_clustering, "fetch_intent_corpus", return_value=(self._stub_corpus(), {})),- patch.object(intent_clustering, "embed_intents_async") as mock_embed,- patch.object(intent_clustering, "fetch_session_journeys", return_value={}),- ):- # asyncio.run unwraps the coroutine; emulate the awaited result.- async def fake_embed(team, texts): # noqa: ARG001- return self._stub_embeddings()-- mock_embed.side_effect = fake_embed- tasks.compute_intent_clusters.apply(args=[self.team.id, self.user.id]).get()-- snapshot = MCPIntentClusterSnapshot.objects.get(team=self.team)- assert snapshot.status == MCPIntentClusterSnapshot.Status.IDLE- assert snapshot.error_message == ""- assert snapshot.last_computed_at is not None- assert snapshot.last_computed_by_id == self.user.id- assert len(snapshot.clusters["clusters"]) == 1- assert snapshot.clusters["clusters"][0]["call_count"] == 14-- def test_empty_corpus_writes_empty_snapshot(self) -> None:- with patch.object(intent_clustering, "fetch_intent_corpus", return_value=([], {})):- tasks.compute_intent_clusters.apply(args=[self.team.id, self.user.id]).get()-- snapshot = MCPIntentClusterSnapshot.objects.get(team=self.team)- assert snapshot.status == MCPIntentClusterSnapshot.Status.IDLE- assert snapshot.clusters["clusters"] == []- assert snapshot.clusters["computed_with"]["n_intents"] == 0-- def test_records_error_on_failure(self) -> None:- with patch.object(intent_clustering, "fetch_intent_corpus", side_effect=RuntimeError("boom")):- try:- tasks.compute_intent_clusters.apply(args=[self.team.id, self.user.id]).get()- except Exception:- # We expect the task to re-raise after marking error and exhausting retries.- pass-- snapshot = MCPIntentClusterSnapshot.objects.get(team=self.team)- assert snapshot.status == MCPIntentClusterSnapshot.Status.ERROR- assert "boom" in snapshot.error_message