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): register the daily clustering schedule behind a feature flag (PR7/9) (#59690)

Daniel Visca1295cf379480
diff --git a/posthog/temporal/mcp_analytics/intent_clustering/schedule.py b/posthog/temporal/mcp_analytics/intent_clustering/schedule.py
new file mode 100644
index 000000000000..c9fc2d989f59
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/intent_clustering/schedule.py
@@ -0,0 +1,131 @@
+"""Daily schedule for the MCP analytics intent clustering coordinator.
+
+Gated behind the ``mcp-analytics-clustering-schedule`` PostHog feature flag.
+This is a kill switch: the schedule isn't registered when the flag is off,
+which keeps the daily fan-out from kicking before the dedicated
+``mcp-analytics-task-queue`` worker exists in production. Flipping the
+flag off after a deploy also removes the schedule on next init, so we can
+disable the daily path without rolling back code.
+"""
+
+import asyncio
+from datetime import timedelta
+
+from django.conf import settings
+
+import structlog
+import posthoganalytics
+from temporalio.client import (
+ Client,
+ Schedule,
+ ScheduleActionStartWorkflow,
+ ScheduleIntervalSpec,
+ ScheduleOverlapPolicy,
+ SchedulePolicy,
+ ScheduleSpec,
+)
+
+from posthog.temporal.common.schedule import a_create_schedule, a_delete_schedule, a_schedule_exists, a_update_schedule
+from posthog.temporal.mcp_analytics.intent_clustering.constants import (
+ COORDINATOR_EXECUTION_TIMEOUT,
+ COORDINATOR_SCHEDULE_ID,
+ COORDINATOR_WORKFLOW_NAME,
+ DEFAULT_LOOKBACK_DAYS,
+ DEFAULT_TOP_N_INTENTS,
+)
+from posthog.temporal.mcp_analytics.intent_clustering.coordinator import IntentClusteringCoordinatorInputs
+
+logger = structlog.get_logger(__name__)
+
+FEATURE_FLAG_KEY = "mcp-analytics-clustering-schedule"
+# Stable distinct_id for the schedule registration check — the decision is
+# deployment-scoped, not user-scoped. Matches the LLMA team_discovery
+# convention (``internal_llma_team_discovery``).
+FEATURE_FLAG_DISTINCT_ID = "internal_mcpa_clustering_schedule"
+
+
+def _schedule_enabled() -> tuple[bool, bool]:
+ """Return ``(enabled, check_succeeded)``.
+
+ Three logical states the caller must distinguish:
+
+ * ``(True, True)`` — FF explicitly ON. Register / update the schedule.
+ * ``(False, True)`` — FF explicitly OFF. Delete any existing schedule
+ (kill switch).
+ * ``(False, False)`` — FF check raised. **Preserve current state.** Do
+ not register a new schedule (fail-closed on registration) and do not
+ delete an existing one (a transient PostHog API outage shouldn't tear
+ down a properly-enabled production schedule).
+ """
+ try:
+ enabled = posthoganalytics.feature_enabled(FEATURE_FLAG_KEY, FEATURE_FLAG_DISTINCT_ID)
+ return bool(enabled), True
+ except Exception:
+ logger.warning("mcpa.intent_clustering.schedule.feature_flag_check_failed_defaulting_off", exc_info=True)
+ return False, False
+
+
+async def create_intent_clustering_coordinator_schedule(client: Client) -> None:
+ """Register (or update) the daily intent clustering coordinator schedule.
+
+ When the feature flag is OFF, any existing schedule is deleted so flipping
+ the flag off cleanly disables the daily path. The schedule is created
+ with ``trigger_immediately=False`` to avoid stampeding a worker on first
+ deploy. If the FF check itself fails (transient PostHog API outage),
+ the current schedule state is preserved — we don't tear down a valid
+ production schedule on a blip.
+ """
+ # posthoganalytics.feature_enabled() is sync and can block on a network call,
+ # so offload to a thread to keep the asyncio loop responsive — matches the
+ # llm_analytics/team_discovery.py pattern.
+ enabled, check_succeeded = await asyncio.to_thread(_schedule_enabled)
+
+ if not enabled:
+ if not check_succeeded:
+ # FF check raised. Don't touch the existing schedule (if any) —
+ # transient PostHog outages must not silently disable production.
+ logger.info(
+ "mcpa.intent_clustering.schedule.feature_flag_check_failed_preserving_state",
+ schedule_id=COORDINATOR_SCHEDULE_ID,
+ )
+ return
+ if await a_schedule_exists(client, COORDINATOR_SCHEDULE_ID):
+ logger.info(
+ "mcpa.intent_clustering.schedule.disabled_removing_existing", schedule_id=COORDINATOR_SCHEDULE_ID
+ )
+ await a_delete_schedule(client, COORDINATOR_SCHEDULE_ID)
+ else:
+ logger.info("mcpa.intent_clustering.schedule.disabled_no_action", schedule_id=COORDINATOR_SCHEDULE_ID)
+ return
+
+ coordinator_schedule = Schedule(
+ action=ScheduleActionStartWorkflow(
+ COORDINATOR_WORKFLOW_NAME,
+ IntentClusteringCoordinatorInputs(
+ lookback_days=DEFAULT_LOOKBACK_DAYS,
+ top_n=DEFAULT_TOP_N_INTENTS,
+ ),
+ id=COORDINATOR_SCHEDULE_ID,
+ task_queue=settings.MCPA_TASK_QUEUE,
+ execution_timeout=COORDINATOR_EXECUTION_TIMEOUT,
+ ),
+ spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=timedelta(days=1))]),
+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
+ )
+
+ if await a_schedule_exists(client, COORDINATOR_SCHEDULE_ID):
+ logger.info("mcpa.intent_clustering.schedule.updating", schedule_id=COORDINATOR_SCHEDULE_ID)
+ await a_update_schedule(client, COORDINATOR_SCHEDULE_ID, coordinator_schedule)
+ else:
+ logger.info("mcpa.intent_clustering.schedule.creating", schedule_id=COORDINATOR_SCHEDULE_ID)
+ await a_create_schedule(
+ client,
+ COORDINATOR_SCHEDULE_ID,
+ coordinator_schedule,
+ trigger_immediately=False,
+ )
+
+
+async def delete_intent_clustering_coordinator_schedule(client: Client) -> None:
+ """Explicit-delete helper. Used by tests; not wired into init_schedules."""
+ await a_delete_schedule(client, COORDINATOR_SCHEDULE_ID)
diff --git a/posthog/temporal/mcp_analytics/intent_clustering/tests/test_schedule.py b/posthog/temporal/mcp_analytics/intent_clustering/tests/test_schedule.py
new file mode 100644
index 000000000000..0a2240b53329
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/intent_clustering/tests/test_schedule.py
@@ -0,0 +1,117 @@
+"""Tests for the intent clustering coordinator schedule.
+
+The schedule is gated on the ``mcp-analytics-clustering-schedule`` feature
+flag. These tests mock the FF and the Temporal client helpers; they don't
+exercise an actual Temporal server.
+"""
+
+import pytest
+from unittest.mock import AsyncMock, patch
+
+from posthog.temporal.mcp_analytics.intent_clustering.constants import COORDINATOR_SCHEDULE_ID
+from posthog.temporal.mcp_analytics.intent_clustering.schedule import (
+ FEATURE_FLAG_KEY,
+ create_intent_clustering_coordinator_schedule,
+)
+
+
+def schedule_helpers():
+ """Patch the four schedule helpers; yield the mocks for assertions."""
+ with (
+ patch(
+ "posthog.temporal.mcp_analytics.intent_clustering.schedule.a_create_schedule", new_callable=AsyncMock
+ ) as create,
+ patch(
+ "posthog.temporal.mcp_analytics.intent_clustering.schedule.a_update_schedule", new_callable=AsyncMock
+ ) as update,
+ patch(
+ "posthog.temporal.mcp_analytics.intent_clustering.schedule.a_delete_schedule", new_callable=AsyncMock
+ ) as delete,
+ patch(
+ "posthog.temporal.mcp_analytics.intent_clustering.schedule.a_schedule_exists", new_callable=AsyncMock
+ ) as exists,
+ ):
+ yield {"create": create, "update": update, "delete": delete, "exists": exists}
+
+
+def mock_client():
+ return object()
+
+
+class TestCreateIntentClusteringCoordinatorSchedule:
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "case_id, flag_enabled, exists_returns, expected_create, expected_update, expected_delete",
+ [
+ # Flag OFF + no schedule → no-op.
+ ("flag_off_no_existing", False, False, False, False, False),
+ # Flag OFF + existing schedule → delete (kill-switch).
+ ("flag_off_existing", False, True, False, False, True),
+ # Flag ON + no schedule → create (with trigger_immediately=False).
+ ("flag_on_no_existing", True, False, True, False, False),
+ # Flag ON + existing schedule → update.
+ ("flag_on_existing", True, True, False, True, False),
+ # FF check raises + no schedule exists → no-op. We don't register
+ # on an uncertain FF state.
+ # Sentinel value None means "raise from the FF SDK".
+ ("flag_check_raises_no_existing", None, False, False, False, False),
+ # FF check raises + schedule EXISTS → preserve state (no delete!).
+ # A transient PostHog API outage must not silently disable a
+ # properly-enabled production schedule. This is the regression
+ # test for the graphite-app P1 bug.
+ ("flag_check_raises_preserves_existing", None, True, False, False, False),
+ ],
+ )
+ async def test_create_intent_clustering_coordinator_schedule(
+ self,
+ mock_client,
+ schedule_helpers,
+ case_id: str,
+ flag_enabled: bool | None,
+ exists_returns: bool,
+ expected_create: bool,
+ expected_update: bool,
+ expected_delete: bool,
+ ) -> None:
+ schedule_helpers["exists"].return_value = exists_returns
+ # None sentinel = SDK raises. Otherwise return_value=flag_enabled.
+ if flag_enabled is None:
+ feature_enabled_patch = patch(
+ "posthog.temporal.mcp_analytics.intent_clustering.schedule.posthoganalytics.feature_enabled",
+ side_effect=RuntimeError("PostHog FF API down"),
+ )
+ else:
+ feature_enabled_patch = patch(
+ "posthog.temporal.mcp_analytics.intent_clustering.schedule.posthoganalytics.feature_enabled",
+ return_value=flag_enabled,
+ )
+
+ with feature_enabled_patch:
+ await create_intent_clustering_coordinator_schedule(mock_client)
+
+ if expected_create:
+ schedule_helpers["create"].assert_awaited_once()
+ # trigger_immediately=False so first-deploy doesn't dogpile the worker.
+ assert schedule_helpers["create"].call_args.kwargs.get("trigger_immediately") is False
+ else:
+ schedule_helpers["create"].assert_not_called()
+
+ if expected_update:
+ schedule_helpers["update"].assert_awaited_once()
+ else:
+ schedule_helpers["update"].assert_not_called()
+
+ if expected_delete:
+ schedule_helpers["delete"].assert_awaited_once_with(mock_client, COORDINATOR_SCHEDULE_ID)
+ else:
+ schedule_helpers["delete"].assert_not_called()
+
+
+class TestFeatureFlagKeyIsStable:
+ def test_flag_key_matches_documented_value(self) -> None:
+ # The feature flag must be created in PostHog with this exact key.
+ # Changing the key here without coordinating with the FF setup will
+ # silently leave the schedule off forever.
+ assert FEATURE_FLAG_KEY == "mcp-analytics-clustering-schedule"
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index 6b41e25ba4f5..8bafaa81e59b 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -57,6 +57,7 @@ from posthog.temporal.experiments.schedule import (
from posthog.temporal.health_checks.schedule import create_health_check_schedules
from posthog.temporal.ingestion_acceptance_test.schedule import create_ingestion_acceptance_test_schedule
from posthog.temporal.logs_alerting.schedule import create_logs_alert_check_schedule
+from posthog.temporal.mcp_analytics.intent_clustering.schedule import create_intent_clustering_coordinator_schedule
from posthog.temporal.messaging.schedule import create_all_realtime_cohort_calculation_schedules
from posthog.temporal.product_analytics.upgrade_queries_workflow import UpgradeQueriesWorkflowInputs
from posthog.temporal.quota_limiting.run_quota_limiting import RunQuotaLimitingInputs
@@ -591,6 +592,7 @@ schedules = [
create_batch_generation_summarization_schedule,
create_trace_clustering_coordinator_schedule,
create_generation_clustering_coordinator_schedule,
+ create_intent_clustering_coordinator_schedule,
create_eval_reports_schedule,
create_count_trigger_schedule,
create_evaluation_sampler_schedule,