: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): add intent clustering coordinator + team discovery (PR6/9) (#59689)
Daniel Visca076d51b64790
diff --git a/posthog/temporal/mcp_analytics/intent_clustering/__init__.py b/posthog/temporal/mcp_analytics/intent_clustering/__init__.pyindex b79b4ce3d7ba..19b20bf3dbd6 100644--- a/posthog/temporal/mcp_analytics/intent_clustering/__init__.py+++ b/posthog/temporal/mcp_analytics/intent_clustering/__init__.py@@ -5,19 +5,25 @@ Registered against ``settings.MCPA_TASK_QUEUE`` by"""from posthog.temporal.mcp_analytics.intent_clustering.activities import compute_intent_clusters_activity+from posthog.temporal.mcp_analytics.intent_clustering.coordinator import IntentClusteringCoordinatorWorkflow+from posthog.temporal.mcp_analytics.intent_clustering.team_discovery import get_team_ids_for_mcp_analyticsfrom posthog.temporal.mcp_analytics.intent_clustering.workflow import DailyIntentClusteringWorkflowMCP_ANALYTICS_INTENT_CLUSTERING_WORKFLOWS = [DailyIntentClusteringWorkflow,+ IntentClusteringCoordinatorWorkflow,]MCP_ANALYTICS_INTENT_CLUSTERING_ACTIVITIES = [compute_intent_clusters_activity,+ get_team_ids_for_mcp_analytics,]__all__ = ["DailyIntentClusteringWorkflow",+ "IntentClusteringCoordinatorWorkflow","MCP_ANALYTICS_INTENT_CLUSTERING_ACTIVITIES","MCP_ANALYTICS_INTENT_CLUSTERING_WORKFLOWS","compute_intent_clusters_activity",+ "get_team_ids_for_mcp_analytics",]diff --git a/posthog/temporal/mcp_analytics/intent_clustering/coordinator.py b/posthog/temporal/mcp_analytics/intent_clustering/coordinator.pynew file mode 100644index 000000000000..d72924253d9d--- /dev/null+++ b/posthog/temporal/mcp_analytics/intent_clustering/coordinator.py@@ -0,0 +1,191 @@+"""Coordinator workflow for daily MCP analytics intent clustering.++Discovers teams via ``get_team_ids_for_mcp_analytics`` and fans out one+``DailyIntentClusteringWorkflow`` per team. Per-team failures are isolated+so one slow or broken team can't block the rest.++Uses ``continue_as_new`` when Temporal suggests it so the workflow history+stays under the 50k event cap when discovery grows.+"""++import dataclasses+from typing import Any++import structlog+import temporalio+from temporalio.workflow import ChildWorkflowHandle++from posthog.temporal.common.base import PostHogWorkflow+from posthog.temporal.mcp_analytics.intent_clustering.constants import (+ CHILD_WORKFLOW_ID_PREFIX,+ COORDINATOR_CHILD_WORKFLOW_RETRY_POLICY,+ COORDINATOR_DEFAULT_MAX_CONCURRENT_TEAMS,+ COORDINATOR_WORKFLOW_NAME,+ DEFAULT_LOOKBACK_DAYS,+ DEFAULT_TOP_N_INTENTS,+ WORKFLOW_EXECUTION_TIMEOUT,+)+from posthog.temporal.mcp_analytics.intent_clustering.models import (+ IntentClusteringResult,+ IntentClusteringWorkflowInputs,+)+from posthog.temporal.mcp_analytics.intent_clustering.workflow import DailyIntentClusteringWorkflow++with temporalio.workflow.unsafe.imports_passed_through():+ from posthog.temporal.mcp_analytics.intent_clustering.team_discovery import (+ DISCOVERY_ACTIVITY_RETRY_POLICY,+ DISCOVERY_ACTIVITY_TIMEOUT,+ GUARANTEED_TEAM_IDS,+ TeamDiscoveryInput,+ get_team_ids_for_mcp_analytics,+ )++logger = structlog.get_logger(__name__)+++def _empty_results() -> dict[str, Any]:+ return {+ "teams_succeeded": 0,+ "teams_failed": 0,+ "failed_team_ids": [],+ "total_intents": 0,+ "total_clusters": 0,+ }+++class IntentClusteringCoordinatorInputs:+ """Inputs for the coordinator workflow.++ ``remaining_team_ids`` and ``results_so_far`` are only set on the+ continue-as-new leg — they carry partial progress across continuations+ so team discovery isn't re-run.+ """++ lookback_days: int = DEFAULT_LOOKBACK_DAYS+ top_n: int = DEFAULT_TOP_N_INTENTS+ max_concurrent_teams: int = COORDINATOR_DEFAULT_MAX_CONCURRENT_TEAMS+ remaining_team_ids: list[int] | None = None+ results_so_far: dict[str, Any] | None = None++[email protected](name=COORDINATOR_WORKFLOW_NAME)+class IntentClusteringCoordinatorWorkflow(PostHogWorkflow):+ """Fan-out coordinator. Spawns one DailyIntentClusteringWorkflow per team."""++ @staticmethod+ def parse_inputs(inputs: list[str]) -> IntentClusteringCoordinatorInputs:+ return IntentClusteringCoordinatorInputs(+ lookback_days=int(inputs[0]) if len(inputs) > 0 else DEFAULT_LOOKBACK_DAYS,+ top_n=int(inputs[1]) if len(inputs) > 1 else DEFAULT_TOP_N_INTENTS,+ max_concurrent_teams=(int(inputs[2]) if len(inputs) > 2 else COORDINATOR_DEFAULT_MAX_CONCURRENT_TEAMS),+ )++ @temporalio.workflow.run+ async def run(self, inputs: IntentClusteringCoordinatorInputs) -> dict[str, Any]:+ # Phase A: resolve teams. Skip discovery on continuation legs.+ if inputs.remaining_team_ids is not None:+ team_ids = inputs.remaining_team_ids+ results_so_far = inputs.results_so_far or _empty_results()+ logger.info(+ "mcpa.intent_clustering.coordinator.resumed",+ remaining_teams=len(team_ids),+ teams_succeeded_so_far=results_so_far["teams_succeeded"],+ )+ else:+ logger.info(+ "mcpa.intent_clustering.coordinator.started",+ lookback_days=inputs.lookback_days,+ top_n=inputs.top_n,+ )+ try:+ team_ids = await temporalio.workflow.execute_activity(+ get_team_ids_for_mcp_analytics,+ TeamDiscoveryInput(),+ start_to_close_timeout=DISCOVERY_ACTIVITY_TIMEOUT,+ retry_policy=DISCOVERY_ACTIVITY_RETRY_POLICY,+ )+ except Exception:+ logger.warning(+ "mcpa.intent_clustering.coordinator.discovery_failed_using_fallback",+ exc_info=True,+ )+ team_ids = sorted(GUARANTEED_TEAM_IDS)++ results_so_far = _empty_results()+ logger.info(+ "mcpa.intent_clustering.coordinator.teams_resolved",+ team_count=len(team_ids),+ team_ids=team_ids,+ )++ # Phase B: process teams in batches.+ max_concurrent = inputs.max_concurrent_teams+ for batch_start in range(0, len(team_ids), max_concurrent):+ batch = team_ids[batch_start : batch_start + max_concurrent]+ handles: list[tuple[int, ChildWorkflowHandle[DailyIntentClusteringWorkflow, IntentClusteringResult]]] = []+ for team_id in batch:+ handle = await temporalio.workflow.start_child_workflow(+ DailyIntentClusteringWorkflow.run,+ IntentClusteringWorkflowInputs(+ team_id=team_id, lookback_days=inputs.lookback_days, top_n=inputs.top_n+ ),+ id=(f"{CHILD_WORKFLOW_ID_PREFIX}-{team_id}-{temporalio.workflow.now().isoformat()}"),+ execution_timeout=WORKFLOW_EXECUTION_TIMEOUT,+ retry_policy=COORDINATOR_CHILD_WORKFLOW_RETRY_POLICY,+ parent_close_policy=temporalio.workflow.ParentClosePolicy.TERMINATE,+ )+ handles.append((team_id, handle))++ for team_id, handle in handles:+ try:+ child_result: IntentClusteringResult = await handle+ results_so_far["total_intents"] += child_result.n_intents+ results_so_far["total_clusters"] += child_result.n_clusters+ results_so_far["teams_succeeded"] += 1+ logger.info(+ "mcpa.intent_clustering.coordinator.team_completed",+ team_id=team_id,+ n_intents=child_result.n_intents,+ n_clusters=child_result.n_clusters,+ )+ except Exception:+ logger.exception("mcpa.intent_clustering.coordinator.team_failed", team_id=team_id)+ results_so_far["failed_team_ids"].append(team_id)+ results_so_far["teams_failed"] += 1++ # If Temporal suggests continue-as-new and we have more teams, carry state forward.+ remaining = team_ids[batch_start + max_concurrent :]+ if remaining and temporalio.workflow.info().is_continue_as_new_suggested():+ logger.info(+ "mcpa.intent_clustering.coordinator.continuing_as_new",+ teams_remaining=len(remaining),+ )+ temporalio.workflow.continue_as_new(+ IntentClusteringCoordinatorInputs(+ lookback_days=inputs.lookback_days,+ top_n=inputs.top_n,+ max_concurrent_teams=inputs.max_concurrent_teams,+ remaining_team_ids=remaining,+ results_so_far=results_so_far,+ )+ )++ total = results_so_far["teams_succeeded"] + results_so_far["teams_failed"]+ logger.info(+ "mcpa.intent_clustering.coordinator.finished",+ teams_processed=total,+ teams_succeeded=results_so_far["teams_succeeded"],+ teams_failed=results_so_far["teams_failed"],+ total_intents=results_so_far["total_intents"],+ total_clusters=results_so_far["total_clusters"],+ )++ return {+ "teams_processed": total,+ "teams_succeeded": results_so_far["teams_succeeded"],+ "teams_failed": results_so_far["teams_failed"],+ "failed_team_ids": results_so_far["failed_team_ids"],+ "total_intents": results_so_far["total_intents"],+ "total_clusters": results_so_far["total_clusters"],+ }diff --git a/posthog/temporal/mcp_analytics/intent_clustering/team_discovery.py b/posthog/temporal/mcp_analytics/intent_clustering/team_discovery.pynew file mode 100644index 000000000000..ac00b77ace60--- /dev/null+++ b/posthog/temporal/mcp_analytics/intent_clustering/team_discovery.py@@ -0,0 +1,54 @@+"""Team discovery for the MCP analytics intent clustering coordinator.++v1 returns a hard-coded ``GUARANTEED_TEAM_IDS`` list — there's no sampling+of teams-with-mcp-events yet. The activity exists so the coordinator's+fan-out shape matches the LLMA precedent and so a future PR can swap in a+ClickHouse sample query without touching the workflow wiring.++Why no sampling in v1:++- MCP analytics is small; the dogfooding cohort is one team.+- The coordinator and worker deployment are themselves new — narrow the+ blast radius until we've validated the daily path on {team 2} for a week.+- Adding sampling later is a constants change, not an architectural one.+"""++import dataclasses+from datetime import timedelta++import structlog+from temporalio import activity+from temporalio.common import RetryPolicy++from posthog.temporal.common.heartbeat import Heartbeater++logger = structlog.get_logger(__name__)+++# Teams that always get a daily run regardless of sampling decisions.+# 2 = PostHog Cloud US — the project this repo dogfoods against.+GUARANTEED_TEAM_IDS: list[int] = [2]++# Activity envelope — generous timeout in case we add the ClickHouse sample+# query later. Two retry attempts cover transient cluster blips.+DISCOVERY_ACTIVITY_TIMEOUT = timedelta(minutes=5)+DISCOVERY_ACTIVITY_RETRY_POLICY = RetryPolicy(maximum_attempts=2)+++class TeamDiscoveryInput:+ """Reserved for future use (sample_percentage, lookback_days). Empty in v1."""+++async def get_team_ids_for_mcp_analytics(inputs: TeamDiscoveryInput) -> list[int]:+ """Return the deterministic list of teams to cluster intents for.++ v1: returns ``GUARANTEED_TEAM_IDS`` sorted. A future PR will optionally+ union with a ClickHouse-sampled set of teams that have ``mcp_tool_call``+ events in the configured window.+ """+ async with Heartbeater():+ team_ids = sorted(GUARANTEED_TEAM_IDS)+ logger.info("mcpa.intent_clustering.team_discovery", count=len(team_ids), team_ids=team_ids)+ return team_idsdiff --git a/posthog/temporal/mcp_analytics/intent_clustering/tests/test_coordinator.py b/posthog/temporal/mcp_analytics/intent_clustering/tests/test_coordinator.pynew file mode 100644index 000000000000..fdabbc6fb945--- /dev/null+++ b/posthog/temporal/mcp_analytics/intent_clustering/tests/test_coordinator.py@@ -0,0 +1,190 @@+"""Tests for the IntentClusteringCoordinatorWorkflow."""++import uuid+from typing import Any++import pytest++from temporalio import activity, workflow+from temporalio.exceptions import ApplicationError+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from posthog.temporal.mcp_analytics.intent_clustering.coordinator import (+ IntentClusteringCoordinatorInputs,+ IntentClusteringCoordinatorWorkflow,+)+from posthog.temporal.mcp_analytics.intent_clustering.models import (+ IntentClusteringResult,+ IntentClusteringWorkflowInputs,+)+from posthog.temporal.mcp_analytics.intent_clustering.team_discovery import GUARANTEED_TEAM_IDS, TeamDiscoveryInput++# Module-level mock child workflow. Temporal sandbox forbids local-class+# @workflow.defn, and per-test workflow classes with the same name collide+# anyway — share one class and toggle behaviour via a module-level set the+# test populates before running.+_FAILING_TEAM_IDS: set[int] = set()++[email protected](name="mcpa-intent-clustering")+class StubDailyWorkflow:+ @workflow.run+ async def run(self, inputs: IntentClusteringWorkflowInputs) -> IntentClusteringResult:+ if inputs.team_id in _FAILING_TEAM_IDS:+ # ApplicationError fails the *execution*, not the workflow task —+ # a plain RuntimeError makes Temporal retry the task indefinitely+ # against the execution timeout, which hangs time-skipping tests.+ raise ApplicationError(f"team {inputs.team_id} blew up", non_retryable=True)+ # n_intents is tied to team_id so each child's contribution is+ # identifiable in aggregate-result assertions.+ return IntentClusteringResult(+ team_id=inputs.team_id,+ n_intents=inputs.team_id * 10,+ n_clusters=inputs.team_id,+ computed_at="2026-05-21T00:00:00+00:00",+ )+++async def _run_coordinator(+ team_ids: list[int],+ coordinator_inputs: IntentClusteringCoordinatorInputs,+ *,+ failing_team_id: int | None = None,+) -> dict[str, Any]:+ """Drive the coordinator with mocked discovery + child workflow."""++ @activity.defn(name="get_team_ids_for_mcp_analytics")+ async def mock_discovery(_: TeamDiscoveryInput) -> list[int]:+ return team_ids++ _FAILING_TEAM_IDS.clear()+ if failing_team_id is not None:+ _FAILING_TEAM_IDS.add(failing_team_id)++ task_queue = str(uuid.uuid4())+ try:+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[IntentClusteringCoordinatorWorkflow, StubDailyWorkflow],+ activities=[mock_discovery],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ return await env.client.execute_workflow(+ IntentClusteringCoordinatorWorkflow.run,+ coordinator_inputs,+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )+ finally:+ _FAILING_TEAM_IDS.clear()+++class TestIntentClusteringCoordinator:+ @pytest.mark.asyncio+ async def test_runs_one_child_per_discovered_team(self) -> None:+ result = await _run_coordinator(+ team_ids=[2, 7, 9],+ coordinator_inputs=IntentClusteringCoordinatorInputs(),+ )+ assert result["teams_processed"] == 3+ assert result["teams_succeeded"] == 3+ assert result["teams_failed"] == 0+ assert result["failed_team_ids"] == []+ assert result["total_intents"] == 20 + 70 + 90+ assert result["total_clusters"] == 2 + 7 + 9++ @pytest.mark.asyncio+ async def test_per_team_failure_does_not_block_others(self) -> None:+ result = await _run_coordinator(+ team_ids=[2, 7],+ coordinator_inputs=IntentClusteringCoordinatorInputs(),+ failing_team_id=7,+ )+ assert result["teams_succeeded"] == 1+ assert result["teams_failed"] == 1+ assert result["failed_team_ids"] == [7]+ # Only the successful team's intents counted.+ assert result["total_intents"] == 20+ assert result["total_clusters"] == 2++ @pytest.mark.asyncio+ async def test_no_teams_yields_zero_results(self) -> None:+ result = await _run_coordinator(+ team_ids=[],+ coordinator_inputs=IntentClusteringCoordinatorInputs(),+ )+ assert result["teams_processed"] == 0+ assert result["teams_succeeded"] == 0+ assert result["teams_failed"] == 0+ assert result["total_intents"] == 0+++class TestCoordinatorParseInputs:+ @pytest.mark.parametrize(+ "args, expected_lookback, expected_top_n, expected_max_concurrent",+ [+ ([], 7, 500, 4),+ (["14", "200", "2"], 14, 200, 2),+ ],+ )+ def test_parse_inputs(+ self,+ args: list[str],+ expected_lookback: int,+ expected_top_n: int,+ expected_max_concurrent: int,+ ) -> None:+ inputs = IntentClusteringCoordinatorWorkflow.parse_inputs(args)+ assert inputs.lookback_days == expected_lookback+ assert inputs.top_n == expected_top_n+ assert inputs.max_concurrent_teams == expected_max_concurrent+++class TestCoordinatorContinuation:+ """Covers the continue-as-new state-carry branch.++ ``is_continue_as_new_suggested()`` doesn't fire in the time-skipping+ environment for small team sets, so we simulate the continuation leg by+ passing pre-loaded ``remaining_team_ids`` + ``results_so_far`` directly+ into ``IntentClusteringCoordinatorInputs``. That hits the ``if+ inputs.remaining_team_ids is not None`` branch in ``run()`` and proves the+ carry-over logic is correct end-to-end.+ """++ @pytest.mark.asyncio+ async def test_continuation_skips_discovery_and_merges_prior_results(self) -> None:+ prior_results = {+ "teams_processed": 1,+ "teams_succeeded": 1,+ "teams_failed": 0,+ "failed_team_ids": [],+ "total_intents": 999,+ "total_clusters": 5,+ }+ # team_ids passed via mock_discovery would only be used on the fresh+ # path; continuation reads from remaining_team_ids instead.+ result = await _run_coordinator(+ team_ids=[], # should be ignored on the continuation leg+ coordinator_inputs=IntentClusteringCoordinatorInputs(+ remaining_team_ids=[2, 7],+ results_so_far=prior_results,+ ),+ )++ # Prior teams_processed (1) + current batch (2) = 3.+ assert result["teams_processed"] == 3+ assert result["teams_succeeded"] == 3+ assert result["teams_failed"] == 0+ # Prior total_intents (999) preserved; new intents add on top.+ assert result["total_intents"] == 999 + 20 + 70+ assert result["total_clusters"] == 5 + 2 + 7+++class TestGuaranteedTeamIds:+ def test_includes_internal_team(self) -> None:+ # If this changes, double-check the coordinator schedule isn't sending+ # daily traffic to an unexpected team.+ assert 2 in GUARANTEED_TEAM_IDS