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.

chore(mcp-analytics): scaffold intent_clustering temporal package (PR4/9) (#59687)

Daniel Visca09dc8cfadef5
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.yml
index 7fef32b1aae5..1d15150243ab 100644
--- a/.github/workflows/container-images-cd.yml
+++ b/.github/workflows/container-images-cd.yml
@@ -628,6 +628,17 @@ jobs:
- 'posthog/clickhouse/migrations/**'
- pyproject.toml
- bin/temporal-django-worker
+ # Narrowed to intent_clustering only — backfill_sessions and
+ # summarize_session_intents run on GENERAL_PURPOSE_TASK_QUEUE, not
+ # MCPA_TASK_QUEUE, so changes there don't need to redeploy this worker.
+ mcpAnalytics:
+ - 'posthog/temporal/mcp_analytics/intent_clustering/**'
+ - 'products/mcp_analytics/backend/**'
+ - 'posthog/temporal/common/**'
+ - 'posthog/management/commands/start_temporal_worker.py'
+ - 'posthog/clickhouse/migrations/**'
+ - pyproject.toml
+ - bin/temporal-django-worker
- name: Trigger Health Check Temporal Worker Cloud deployment
if: steps.check_temporal_worker_changes.outputs.healthCheck == 'true'
@@ -704,6 +715,27 @@ jobs:
"timestamp": "${{ github.event.head_commit.timestamp }}"
}
+ - name: Trigger MCP Analytics Temporal Worker Cloud deployment
+ if: steps.check_temporal_worker_changes.outputs.mcpAnalytics == 'true'
+ uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v4.0.1
+ with:
+ token: ${{ steps.deployer.outputs.token }}
+ repository: PostHog/charts
+ event-type: commit_state_update
+ client-payload: |
+ {
+ "values": {
+ "image": {
+ "sha": "${{ github.sha }}@${{ steps.build.outputs.digest }}"
+ }
+ },
+ "release": "temporal-worker-mcp-analytics",
+ "commit": ${{ toJson(github.event.head_commit) }},
+ "repository": ${{ toJson(github.repository) }},
+ "labels": ${{ steps.labels.outputs.labels }},
+ "timestamp": "${{ github.event.head_commit.timestamp }}"
+ }
+
- name: Trigger Logs Alerting Temporal Worker Cloud deployment
if: steps.check_temporal_worker_changes.outputs.logsAlerting == 'true'
uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v4.0.1
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index ae0f65f3248b..cb5ff635f4bd 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -86,6 +86,10 @@ from posthog.temporal.ingestion_acceptance_test import (
ACTIVITIES as INGESTION_ACCEPTANCE_TEST_ACTIVITIES,
WORKFLOWS as INGESTION_ACCEPTANCE_TEST_WORKFLOWS,
)
+from posthog.temporal.mcp_analytics.intent_clustering import (
+ MCP_ANALYTICS_INTENT_CLUSTERING_ACTIVITIES,
+ MCP_ANALYTICS_INTENT_CLUSTERING_WORKFLOWS,
+)
from posthog.temporal.messaging import (
ACTIVITIES as MESSAGING_ACTIVITIES,
WORKFLOWS as MESSAGING_WORKFLOWS,
@@ -341,6 +345,16 @@ _task_queue_specs = [
LLM_ANALYTICS_WORKFLOWS,
LLM_ANALYTICS_ACTIVITIES,
),
+ (
+ # Dedicated queue for MCP analytics clustering — isolates the CPU
+ # burst (cluster compute) and external embedding worker calls from
+ # the general-purpose queue that hosts the rest of mcp_analytics.
+ # Workflow + activity lists are populated as the stack lands; an
+ # empty queue is harmless — the worker registers and idles.
+ settings.MCPA_TASK_QUEUE,
+ MCP_ANALYTICS_INTENT_CLUSTERING_WORKFLOWS,
+ MCP_ANALYTICS_INTENT_CLUSTERING_ACTIVITIES,
+ ),
(
settings.EVENT_SCREENSHOTS_TASK_QUEUE,
EVENT_SCREENSHOTS_WORKFLOWS,
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index a68cf8c5d2b3..9580987b54ad 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -117,6 +117,7 @@ WEEKLY_DIGEST_TASK_QUEUE = _set_temporal_task_queue("weekly-digest-task-queue")
LLMA_EVALS_TASK_QUEUE = _set_temporal_task_queue("llm-analytics-evals-task-queue")
LLMA_SENTIMENT_TASK_QUEUE = _set_temporal_task_queue("llm-analytics-sentiment-task-queue")
LLMA_TASK_QUEUE = _set_temporal_task_queue("llm-analytics-task-queue")
+MCPA_TASK_QUEUE = _set_temporal_task_queue("mcp-analytics-task-queue")
EVENT_SCREENSHOTS_TASK_QUEUE = _set_temporal_task_queue("event-screenshots-task-queue")
LOGS_ALERTING_TASK_QUEUE = _set_temporal_task_queue("logs-alerting-task-queue")
RASTERIZATION_TASK_QUEUE = "rasterization-task-queue" # Not collapsed in dev — separate Node.js worker process
diff --git a/posthog/temporal/mcp_analytics/intent_clustering/__init__.py b/posthog/temporal/mcp_analytics/intent_clustering/__init__.py
new file mode 100644
index 000000000000..07a490a6c8a3
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/intent_clustering/__init__.py
@@ -0,0 +1,10 @@
+"""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.
+"""
+
+MCP_ANALYTICS_INTENT_CLUSTERING_WORKFLOWS: list = []
+MCP_ANALYTICS_INTENT_CLUSTERING_ACTIVITIES: list = []
diff --git a/posthog/temporal/mcp_analytics/intent_clustering/constants.py b/posthog/temporal/mcp_analytics/intent_clustering/constants.py
new file mode 100644
index 000000000000..d3a3b1a2219a
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/intent_clustering/constants.py
@@ -0,0 +1,90 @@
+"""Configuration constants for the MCP analytics intent clustering workflow.
+
+Timeouts and retry policies mirror ``posthog/temporal/llm_analytics/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
+both pipelines comparable in Grafana.
+"""
+
+from datetime import timedelta
+
+from temporalio.common import RetryPolicy
+
+# Workflow identity --------------------------------------------------------
+
+WORKFLOW_NAME = "mcpa-intent-clustering"
+COORDINATOR_WORKFLOW_NAME = "mcpa-intent-clustering-coordinator"
+COORDINATOR_SCHEDULE_ID = "mcpa-intent-clustering-coordinator-schedule"
+CHILD_WORKFLOW_ID_PREFIX = "mcpa-intent-clustering-team"
+
+# Sampling ------------------------------------------------------------------
+
+DEFAULT_LOOKBACK_DAYS = 7
+DEFAULT_TOP_N_INTENTS = 500
+MIN_INTENTS_FOR_CLUSTERING = 2
+
+# Workflow + activity envelopes --------------------------------------------
+
+WORKFLOW_EXECUTION_TIMEOUT = timedelta(minutes=20)
+COORDINATOR_EXECUTION_TIMEOUT = timedelta(hours=12) # < daily schedule interval
+
+# Per-activity, per single attempt.
+COMPUTE_ACTIVITY_TIMEOUT = timedelta(seconds=180) # corpus fetch + embed + cluster
+JOURNEYS_ACTIVITY_TIMEOUT = timedelta(seconds=60) # HogQL journey aggregation
+SNAPSHOT_ACTIVITY_TIMEOUT = timedelta(seconds=30) # pure-CPU snapshot assembly
+PERSIST_ACTIVITY_TIMEOUT = timedelta(seconds=30) # Postgres write
+
+# Heartbeats let Temporal detect dead workers without waiting for the full
+# start-to-close to elapse. Activities heartbeat at least this often.
+COMPUTE_HEARTBEAT_TIMEOUT = timedelta(seconds=60)
+JOURNEYS_HEARTBEAT_TIMEOUT = timedelta(seconds=30)
+SNAPSHOT_HEARTBEAT_TIMEOUT = timedelta(seconds=30)
+PERSIST_HEARTBEAT_TIMEOUT = timedelta(seconds=30)
+
+# Schedule-to-close caps total time across retries + backoff + queue wait.
+# Each is sized as (max_attempts × start_to_close) + a backoff allowance.
+COMPUTE_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(seconds=400)
+JOURNEYS_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(seconds=200) # 3 × 60s + ~6s backoff allowance + buffer
+SNAPSHOT_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(seconds=90)
+PERSIST_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(seconds=90)
+
+# Compute activity — CPU bound, quick retries. ValueError/TypeError are
+# programming bugs that won't fix themselves on retry.
+COMPUTE_ACTIVITY_RETRY_POLICY = RetryPolicy(
+ maximum_attempts=2,
+ initial_interval=timedelta(seconds=1),
+ maximum_interval=timedelta(seconds=10),
+ backoff_coefficient=2.0,
+ non_retryable_error_types=["ValueError", "TypeError"],
+)
+
+# Journeys activity — ClickHouse-backed, may hit query limits. Retry once
+# with backoff to ride out transient cluster load.
+JOURNEYS_ACTIVITY_RETRY_POLICY = RetryPolicy(
+ maximum_attempts=3,
+ initial_interval=timedelta(seconds=2),
+ maximum_interval=timedelta(seconds=20),
+ backoff_coefficient=2.0,
+ non_retryable_error_types=["ValueError", "TypeError"],
+)
+
+# Snapshot activity — pure CPU. A failure here means a code bug — retrying
+# won't help.
+SNAPSHOT_ACTIVITY_RETRY_POLICY = RetryPolicy(
+ maximum_attempts=1,
+ non_retryable_error_types=["ValueError", "TypeError", "AssertionError"],
+)
+
+# Persist activity — Postgres write. Retry on transient connection errors.
+PERSIST_ACTIVITY_RETRY_POLICY = RetryPolicy(
+ maximum_attempts=3,
+ initial_interval=timedelta(seconds=1),
+ maximum_interval=timedelta(seconds=10),
+ backoff_coefficient=2.0,
+ non_retryable_error_types=["ValueError", "TypeError"],
+)
+
+# Coordinator — child-workflow failure shouldn't retry the whole coordinator.
+COORDINATOR_CHILD_WORKFLOW_RETRY_POLICY = RetryPolicy(maximum_attempts=1)
+COORDINATOR_DEFAULT_MAX_CONCURRENT_TEAMS = 4
diff --git a/posthog/temporal/mcp_analytics/intent_clustering/models.py b/posthog/temporal/mcp_analytics/intent_clustering/models.py
new file mode 100644
index 000000000000..f660b76a8de6
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/intent_clustering/models.py
@@ -0,0 +1,40 @@
+"""Data models for the MCP analytics intent clustering workflow.
+
+Kept intentionally small — the pure-function pipeline already lives in
+``products/mcp_analytics/backend/intent_clustering.py``; this module just
+declares the workflow/activity envelopes that wrap those functions.
+"""
+
+from dataclasses import dataclass
+from typing import Any
+
+from posthog.temporal.mcp_analytics.intent_clustering.constants import DEFAULT_LOOKBACK_DAYS, DEFAULT_TOP_N_INTENTS
+
+
+@dataclass
+class IntentClusteringWorkflowInputs:
+ """Inputs to ``DailyIntentClusteringWorkflow``.
+
+ All numeric knobs default to the same values the Celery task uses today.
+ ``user_id`` is preserved so adhoc recomputes can attribute the run in
+ ``MCPIntentClusterSnapshot.last_computed_by``.
+ """
+
+ team_id: int
+ lookback_days: int = DEFAULT_LOOKBACK_DAYS
+ top_n: int = DEFAULT_TOP_N_INTENTS
+ user_id: int | None = None
+
+ @property
+ def properties_to_log(self) -> dict[str, Any]:
+ return {"team_id": self.team_id}
+
+
+@dataclass
+class IntentClusteringResult:
+ """Result returned by ``DailyIntentClusteringWorkflow``."""
+
+ team_id: int
+ n_intents: int
+ n_clusters: int
+ computed_at: str # ISO format