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): add DailyIntentClusteringWorkflow (PR5/9) (#59688)

Daniel Visca4fc6498fdf0c
diff --git a/posthog/temporal/mcp_analytics/intent_clustering/__init__.py b/posthog/temporal/mcp_analytics/intent_clustering/__init__.py
index 07a490a6c8a3..b79b4ce3d7ba 100644
--- a/posthog/temporal/mcp_analytics/intent_clustering/__init__.py
+++ b/posthog/temporal/mcp_analytics/intent_clustering/__init__.py
@@ -1,10 +1,23 @@
"""MCP analytics intent clustering — Temporal workflow exports.
-This module is the registration seam for the ``mcp-analytics-task-queue``
-worker. Workflows and activities are added here as subsequent PRs land them;
-the empty lists below are intentional in PR #4 so the worker registers the
-queue without yet exposing any handlers.
+Registered against ``settings.MCPA_TASK_QUEUE`` by
+``posthog/management/commands/start_temporal_worker.py``.
"""
-MCP_ANALYTICS_INTENT_CLUSTERING_WORKFLOWS: list = []
-MCP_ANALYTICS_INTENT_CLUSTERING_ACTIVITIES: list = []
+from posthog.temporal.mcp_analytics.intent_clustering.activities import compute_intent_clusters_activity
+from posthog.temporal.mcp_analytics.intent_clustering.workflow import DailyIntentClusteringWorkflow
+
+MCP_ANALYTICS_INTENT_CLUSTERING_WORKFLOWS = [
+ DailyIntentClusteringWorkflow,
+]
+
+MCP_ANALYTICS_INTENT_CLUSTERING_ACTIVITIES = [
+ compute_intent_clusters_activity,
+]
+
+__all__ = [
+ "DailyIntentClusteringWorkflow",
+ "MCP_ANALYTICS_INTENT_CLUSTERING_ACTIVITIES",
+ "MCP_ANALYTICS_INTENT_CLUSTERING_WORKFLOWS",
+ "compute_intent_clusters_activity",
+]
diff --git a/posthog/temporal/mcp_analytics/intent_clustering/activities.py b/posthog/temporal/mcp_analytics/intent_clustering/activities.py
new file mode 100644
index 000000000000..0d08051ed2ad
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/intent_clustering/activities.py
@@ -0,0 +1,202 @@
+"""Temporal activities for the MCP analytics intent clustering pipeline.
+
+There is exactly one activity in v1: ``compute_intent_clusters_activity``.
+It wraps the same orchestration the Celery task performs today, but with
+Temporal-native heartbeats, retries, and replay determinism.
+
+Why a single activity (and not 4 like trace_clustering):
+
+1. **Payload limits.** A 500-intent corpus has embeddings of ~3 MB
+ (500 × 1536 × 4 bytes). Temporal's hard payload limit is ~2 MiB; even
+ compact serialisation would clip us. Keeping embeddings within one
+ activity sidesteps the boundary entirely.
+2. **Total runtime is small.** The full pipeline runs in ~30-60s with a warm
+ cache. Trace_clustering split because labeling alone is 600s — that
+ reasoning doesn't apply here.
+3. **No expensive recompute on retry.** Embeddings are cached (PR #3) and
+ ClickHouse fetches are idempotent. A retry costs O(seconds) of cache
+ lookups, not O(minutes) of work.
+
+If clustering grows (HDBSCAN/UMAP at higher cardinality, LLM labelling),
+the activity boundary can be split later. Today it's single-activity.
+"""
+
+import asyncio
+
+from django.db import transaction
+from django.utils import timezone
+
+import structlog
+from temporalio import activity
+
+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.models import (
+ IntentClusteringResult,
+ IntentClusteringWorkflowInputs,
+)
+
+from products.mcp_analytics.backend import intent_clustering
+from products.mcp_analytics.backend.models import MCPIntentClusterSnapshot
+
+logger = structlog.get_logger(__name__)
+
+
+@database_sync_to_async
+def _resolve_team_and_user(team_id: int, user_id: int | None):
+ """Look up the team (must exist) and the optional originating user."""
+ from posthog.models.user import User
+
+ team = Team.objects.get(pk=team_id)
+ user = User.objects.filter(pk=user_id).first() if user_id is not None else None
+ return team, user
+
+
+@database_sync_to_async
+def _resolve_canonical_team_id(team_id: int) -> int:
+ """Resolve canonical team_id in a thread; team_scope() resolution is sync."""
+ from posthog.models.scoping.manager import resolve_effective_team_id
+
+ return resolve_effective_team_id(team_id)
+
+
+@database_sync_to_async
+def _mark_computing(team: Team, user) -> MCPIntentClusterSnapshot:
+ snapshot, _ = MCPIntentClusterSnapshot.objects.update_or_create(
+ team=team,
+ defaults={
+ "status": MCPIntentClusterSnapshot.Status.COMPUTING,
+ "error_message": "",
+ "last_computed_by": user,
+ },
+ )
+ return snapshot
+
+
+@database_sync_to_async
+def _persist_clusters(snapshot: MCPIntentClusterSnapshot, clusters_blob: dict) -> None:
+ 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"])
+
+
+@database_sync_to_async
+def _mark_error(snapshot: MCPIntentClusterSnapshot, message: str) -> None:
+ snapshot.status = MCPIntentClusterSnapshot.Status.ERROR
+ snapshot.error_message = message[:5000]
+ snapshot.save(update_fields=["status", "error_message", "updated_at"])
+
+
+async def compute_intent_clusters_activity(inputs: IntentClusteringWorkflowInputs) -> IntentClusteringResult:
+ """Run the full intent clustering pipeline for one team.
+
+ Mirrors the Celery task body, but uses Temporal-native primitives:
+ heartbeats keep the worker liveness signal up to date during long
+ operations, and the snapshot status machine is updated at each stage
+ transition so the UI's poll continues to work.
+ """
+ canonical_team_id = await _resolve_canonical_team_id(inputs.team_id)
+ with team_scope(canonical_team_id, canonical=True):
+ async with Heartbeater():
+ team, user = await _resolve_team_and_user(inputs.team_id, inputs.user_id)
+ snapshot = await _mark_computing(team, user)
+
+ try:
+ records, intent_by_session = await database_sync_to_async(intent_clustering.fetch_intent_corpus)(
+ team, lookback_days=inputs.lookback_days, top_n=inputs.top_n
+ )
+ activity.heartbeat("fetched corpus")
+
+ if not records:
+ await database_sync_to_async(_save_empty_blob)(snapshot)
+ logger.info(
+ "mcpa.intent_clustering.no_intents_found",
+ team_id=inputs.team_id,
+ workflow_id=activity.info().workflow_id,
+ )
+ return IntentClusteringResult(
+ team_id=inputs.team_id, n_intents=0, n_clusters=0, computed_at=timezone.now().isoformat()
+ )
+
+ embeddings, valid_indices = await intent_clustering.embed_intents_async(
+ team, [r.intent_text for r in records]
+ )
+ if len(valid_indices) == 0:
+ raise RuntimeError("All embedding requests failed")
+ activity.heartbeat("embedded")
+
+ aligned_records = [records[i] for i in valid_indices]
+ # sklearn AgglomerativeClustering builds an O(n²) distance matrix
+ # in pure-Python/numpy — offload so the asyncio loop stays
+ # responsive to heartbeats and other activities on this worker.
+ labels = await asyncio.to_thread(intent_clustering.cluster_embeddings, embeddings)
+ activity.heartbeat("clustered")
+
+ session_journeys = await database_sync_to_async(intent_clustering.fetch_session_journeys)(
+ team, list(intent_by_session.keys()), lookback_days=inputs.lookback_days
+ )
+ 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
+ )
+ activity.heartbeat("journeys")
+
+ # Same blocking-loop concern as cluster_embeddings — pure-numpy
+ # aggregation over the labelled corpus.
+ clusters_blob = await asyncio.to_thread(
+ intent_clustering.build_snapshot,
+ aligned_records,
+ labels,
+ embeddings,
+ journeys_by_cluster=journeys_by_cluster,
+ )
+ await _persist_clusters(snapshot, clusters_blob)
+
+ n_clusters = len(clusters_blob.get("clusters", []))
+ logger.info(
+ "mcpa.intent_clustering.computed",
+ team_id=inputs.team_id,
+ n_intents=len(aligned_records),
+ n_clusters=n_clusters,
+ workflow_id=activity.info().workflow_id,
+ )
+ return IntentClusteringResult(
+ team_id=inputs.team_id,
+ n_intents=len(aligned_records),
+ n_clusters=n_clusters,
+ computed_at=timezone.now().isoformat(),
+ )
+
+ except Exception as exc:
+ logger.exception("mcpa.intent_clustering.failed", team_id=inputs.team_id, error=str(exc))
+ await _mark_error(snapshot, str(exc))
+ raise
+
+
+def _save_empty_blob(snapshot: MCPIntentClusterSnapshot) -> None:
+ """Synchronous helper to write an empty snapshot when the corpus is empty.
+
+ Lives outside the async activity body so ``database_sync_to_async`` can
+ wrap it without re-entrancy from inside an async context.
+ """
+ snapshot.clusters = {
+ "clusters": [],
+ "computed_with": {
+ "distance_threshold": intent_clustering.DEFAULT_DISTANCE_THRESHOLD,
+ "embedding_model": intent_clustering.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/posthog/temporal/mcp_analytics/intent_clustering/tests/__init__.py b/posthog/temporal/mcp_analytics/intent_clustering/tests/__init__.py
new file mode 100644
index 000000000000..12503f742828
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/intent_clustering/tests/__init__.py
@@ -0,0 +1 @@
+# Tests for intent clustering workflow
diff --git a/posthog/temporal/mcp_analytics/intent_clustering/tests/test_workflow.py b/posthog/temporal/mcp_analytics/intent_clustering/tests/test_workflow.py
new file mode 100644
index 000000000000..e23465e0faf0
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/intent_clustering/tests/test_workflow.py
@@ -0,0 +1,109 @@
+"""Tests for the DailyIntentClusteringWorkflow envelope.
+
+The pure pipeline (corpus fetch, embedding cache, clustering, snapshot
+shape) is covered in ``products/mcp_analytics/backend/tests/``. These
+tests assert the workflow forwards inputs to the activity and returns its
+result — the wiring, not the algorithm.
+"""
+
+import uuid
+
+import pytest
+
+from temporalio import activity
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+
+from posthog.temporal.mcp_analytics.intent_clustering.models import (
+ IntentClusteringResult,
+ IntentClusteringWorkflowInputs,
+)
+from posthog.temporal.mcp_analytics.intent_clustering.workflow import DailyIntentClusteringWorkflow
+
+
+async def _run_with_mock_activity(
+ inputs: IntentClusteringWorkflowInputs,
+ activity_result: IntentClusteringResult,
+) -> tuple[IntentClusteringResult, IntentClusteringWorkflowInputs]:
+ """Execute the workflow in a time-skipping environment with a stub activity.
+
+ Returns ``(workflow_result, activity_inputs_seen)`` so callers can assert
+ both ends of the contract.
+ """
+ captured: dict[str, IntentClusteringWorkflowInputs] = {}
+
+ @activity.defn(name="compute_intent_clusters_activity")
+ async def mock_activity(activity_inputs: IntentClusteringWorkflowInputs) -> IntentClusteringResult:
+ captured["inputs"] = activity_inputs
+ return activity_result
+
+ task_queue = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[DailyIntentClusteringWorkflow],
+ activities=[mock_activity],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ result = await env.client.execute_workflow(
+ DailyIntentClusteringWorkflow.run,
+ inputs,
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+
+ return result, captured["inputs"]
+
+
+class TestDailyIntentClusteringWorkflow:
+ @pytest.mark.asyncio
+ async def test_forwards_inputs_to_activity(self) -> None:
+ inputs = IntentClusteringWorkflowInputs(team_id=42, lookback_days=14, top_n=200, user_id=7)
+ expected = IntentClusteringResult(
+ team_id=42, n_intents=10, n_clusters=2, computed_at="2026-05-21T00:00:00+00:00"
+ )
+
+ result, activity_inputs = await _run_with_mock_activity(inputs, expected)
+
+ assert activity_inputs.team_id == 42
+ assert activity_inputs.lookback_days == 14
+ assert activity_inputs.top_n == 200
+ assert activity_inputs.user_id == 7
+ assert result == expected
+
+ @pytest.mark.asyncio
+ async def test_returns_activity_result_unchanged(self) -> None:
+ inputs = IntentClusteringWorkflowInputs(team_id=1)
+ expected = IntentClusteringResult(team_id=1, n_intents=0, n_clusters=0, computed_at="2026-05-21T00:00:00+00:00")
+
+ result, _ = await _run_with_mock_activity(inputs, expected)
+
+ assert result == expected
+
+
+class TestParseInputs:
+ @pytest.mark.parametrize(
+ "raw_payload, expected_team_id, expected_lookback_days, expected_top_n, expected_user_id",
+ [
+ # Empty input falls back to dataclass defaults.
+ ([], 0, 7, 500, None),
+ # Full JSON payload overrides every field.
+ (['{"team_id": 99, "lookback_days": 3, "top_n": 50, "user_id": 5}'], 99, 3, 50, 5),
+ # Partial payload preserves dataclass defaults for omitted fields.
+ (['{"team_id": 99}'], 99, 7, 500, None),
+ ],
+ )
+ def test_parse_inputs_cases(
+ self,
+ raw_payload: list[str],
+ expected_team_id: int,
+ expected_lookback_days: int,
+ expected_top_n: int,
+ expected_user_id: int | None,
+ ) -> None:
+ inputs = DailyIntentClusteringWorkflow.parse_inputs(raw_payload)
+ assert inputs.team_id == expected_team_id
+ assert inputs.lookback_days == expected_lookback_days
+ assert inputs.top_n == expected_top_n
+ assert inputs.user_id == expected_user_id
diff --git a/posthog/temporal/mcp_analytics/intent_clustering/workflow.py b/posthog/temporal/mcp_analytics/intent_clustering/workflow.py
new file mode 100644
index 000000000000..dc55be58979c
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/intent_clustering/workflow.py
@@ -0,0 +1,52 @@
+"""Daily intent clustering workflow.
+
+Thin wrapper over ``compute_intent_clusters_activity``. The single-activity
+design is justified in ``activities.py``; the workflow's job here is to
+provide retry semantics, the deterministic replay envelope, and a stable
+workflow-id namespace.
+"""
+
+import json
+
+from temporalio import workflow
+
+from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.mcp_analytics.intent_clustering.activities import compute_intent_clusters_activity
+from posthog.temporal.mcp_analytics.intent_clustering.constants import (
+ COMPUTE_ACTIVITY_RETRY_POLICY,
+ COMPUTE_ACTIVITY_TIMEOUT,
+ COMPUTE_HEARTBEAT_TIMEOUT,
+ COMPUTE_SCHEDULE_TO_CLOSE_TIMEOUT,
+ WORKFLOW_NAME,
+)
+from posthog.temporal.mcp_analytics.intent_clustering.models import (
+ IntentClusteringResult,
+ IntentClusteringWorkflowInputs,
+)
+
+
[email protected](name=WORKFLOW_NAME)
+class DailyIntentClusteringWorkflow(PostHogWorkflow):
+ """Recompute the intent cluster snapshot for one team."""
+
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> IntentClusteringWorkflowInputs:
+ """Parse workflow inputs from CLI arguments (JSON string).
+
+ Used by ``execute_temporal_workflow`` and similar entrypoints.
+ """
+ if inputs:
+ data = json.loads(inputs[0])
+ return IntentClusteringWorkflowInputs(**data)
+ return IntentClusteringWorkflowInputs(team_id=0)
+
+ @workflow.run
+ async def run(self, inputs: IntentClusteringWorkflowInputs) -> IntentClusteringResult:
+ return await workflow.execute_activity(
+ compute_intent_clusters_activity,
+ inputs,
+ start_to_close_timeout=COMPUTE_ACTIVITY_TIMEOUT,
+ schedule_to_close_timeout=COMPUTE_SCHEDULE_TO_CLOSE_TIMEOUT,
+ heartbeat_timeout=COMPUTE_HEARTBEAT_TIMEOUT,
+ retry_policy=COMPUTE_ACTIVITY_RETRY_POLICY,
+ )
diff --git a/tach.toml b/tach.toml
index d1e164abc5d0..d3d0697b92b0 100644
--- a/tach.toml
+++ b/tach.toml
@@ -689,13 +689,14 @@ from = [
]
# TODO: legacy leaks — posthog/temporal/mcp_analytics/* and the dashboard
-# integration import models / dashboard_templates directly. Move those into
-# the product (and through the facade) so this interface can shrink back to
-# the isolated default.
+# integration import models / dashboard_templates / intent_clustering directly.
+# Move those into the product (and through the facade) so this interface can
+# shrink back to the isolated default.
[[interfaces]]
expose = [
"backend\\.dashboard_templates.*",
+ "backend\\.intent_clustering.*",
"backend\\.models.*",
]
from = [