: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
fix(aio): stop non-cloud instances running AI clustering schedules (#89317)
posthog[bot]9f437b1bf527
diff --git a/posthog/temporal/ai_observability/llm_endpoint.py b/posthog/temporal/ai_observability/llm_endpoint.pyindex 68b6e4ef4de3..415faad71a8f 100644--- a/posthog/temporal/ai_observability/llm_endpoint.py+++ b/posthog/temporal/ai_observability/llm_endpoint.py@@ -16,10 +16,16 @@ import posthoganalyticsfrom langchain_core.callbacks import BaseCallbackHandlerfrom langchain_openai import ChatOpenAIfrom posthoganalytics.ai.langchain.callbacks import CallbackHandler+from temporalio.exceptions import ApplicationErrorfrom posthog.cloud_utils import is_cloudfrom posthog.llm.gateway_client import ai_gateway_headers, resolve_ai_gateway_config+# On a non-cloud, non-DEBUG deployment there is no AI gateway, so this guard fails identically+# every run. The interceptor in posthog/temporal/common/posthog_client.py keeps this error type+# out of error tracking. Raised non-retryably so a stray execution stops on the first attempt.+AI_FEATURES_CLOUD_ONLY_ERROR_TYPE = "AIFeaturesCloudOnly"+def build_langchain_chat_client(model: str,@@ -39,7 +45,11 @@ def build_langchain_chat_client(model call in one agent invocation."""if not settings.DEBUG and not is_cloud():- raise Exception("AI features are only available in PostHog Cloud")+ raise ApplicationError(+ "AI features are only available in PostHog Cloud",+ type=AI_FEATURES_CLOUD_ONLY_ERROR_TYPE,+ non_retryable=True,+ )gateway = resolve_ai_gateway_config()if gateway:diff --git a/posthog/temporal/ai_observability/tests/test_llm_endpoint.py b/posthog/temporal/ai_observability/tests/test_llm_endpoint.pyindex 41ce5bfeb307..5ae7ba411895 100644--- a/posthog/temporal/ai_observability/tests/test_llm_endpoint.py+++ b/posthog/temporal/ai_observability/tests/test_llm_endpoint.py@@ -7,13 +7,32 @@ from unittest.mock import patchfrom django.test import override_settings-from posthog.temporal.ai_observability.llm_endpoint import build_langchain_callbacks, build_langchain_chat_client+from temporalio.exceptions import ApplicationError++from posthog.temporal.ai_observability.llm_endpoint import (+ AI_FEATURES_CLOUD_ONLY_ERROR_TYPE,+ build_langchain_callbacks,+ build_langchain_chat_client,+)+from posthog.temporal.common.posthog_client import EXPECTED_CONTROL_FLOW_ERROR_TYPESGATEWAY_URL = "https://gateway.example/v1"GATEWAY_KEY = "phs_project_secret"class TestBuildOpenAIChatClient:+ @override_settings(DEBUG=False)+ @patch("posthog.temporal.ai_observability.llm_endpoint.is_cloud", return_value=False)+ def test_non_cloud_guard_raises_non_retryable_non_reportable_error(self, _mock_is_cloud):+ # A non-cloud, non-DEBUG deployment has no AI gateway, so the guard must stop the activity+ # without a retry and without filing an error tracking issue.+ with pytest.raises(ApplicationError) as exc_info:+ build_langchain_chat_client("gpt-5.4", 600.0)++ assert exc_info.value.non_retryable is True+ assert exc_info.value.type == AI_FEATURES_CLOUD_ONLY_ERROR_TYPE+ assert AI_FEATURES_CLOUD_ONLY_ERROR_TYPE in EXPECTED_CONTROL_FLOW_ERROR_TYPES+@pytest.mark.parametrize("gateway_url,gateway_key,expected_base,expected_key,custom_http_client",[diff --git a/posthog/temporal/common/posthog_client.py b/posthog/temporal/common/posthog_client.pyindex 56c92c001949..ae478d6ab4e8 100644--- a/posthog/temporal/common/posthog_client.py+++ b/posthog/temporal/common/posthog_client.py@@ -31,8 +31,10 @@ logger = get_write_only_logger()# constant EMBEDDING_SERVICE_UNAVAILABLE_ERROR_TYPE — this shared Temporal module must not# depend on a product. The error-tracking issue-created workflow fails open on it, so it is# expected control flow, not a defect.+# "AIFeaturesCloudOnly" is raised by the AI observability guard on non-cloud deployments (see+# posthog/temporal/ai_observability/llm_endpoint.py). It reflects the deployment, not a defect.EXPECTED_CONTROL_FLOW_ERROR_TYPES = frozenset(- {"trace_not_settled", "TransientRepartitionError", "EmbeddingServiceUnavailable"}+ {"trace_not_settled", "TransientRepartitionError", "EmbeddingServiceUnavailable", "AIFeaturesCloudOnly"})diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex add425c81a48..927e0289b1f3 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -20,6 +20,7 @@ from temporalio.client import (ScheduleSpec,)+from posthog.cloud_utils import is_cloudfrom posthog.slo.types import SloArea, SloConfig, SloOperationfrom posthog.temporal.ai.checkpoint_compaction.schedule import (create_checkpoint_compaction_schedule,@@ -33,10 +34,12 @@ from posthog.temporal.ai_observability.evaluation_clustering.schedule import (create_evaluation_clustering_schedule,create_evaluation_sampler_schedule,)+from posthog.temporal.ai_observability.trace_clustering import constants as trace_clustering_constantsfrom posthog.temporal.ai_observability.trace_clustering.schedule import (create_generation_clustering_coordinator_schedule,create_trace_clustering_coordinator_schedule,)+from posthog.temporal.ai_observability.trace_summarization import constants as trace_summarization_constantsfrom posthog.temporal.ai_observability.trace_summarization.schedule import (create_batch_generation_summarization_schedule,create_batch_trace_summarization_schedule,@@ -691,6 +694,30 @@ async def cleanup_cohort_calculation_schedules(client: Client):await a_delete_schedule(client, schedule_id)+async def cleanup_non_cloud_ai_observability_schedules(client: Client):+ """Reap the AI observability clustering and summarization schedules on non-cloud deployments.++ These coordinators reach the cloud-only guard in+ ``posthog.temporal.ai_observability.llm_endpoint``, so they register only where that guard lets+ them run: on cloud, or on a local DEBUG install. Temporal keeps a schedule until code deletes it,+ so dropping them from the registration list does not remove rows an earlier release already+ created. A self-hosted instance that deployed such a release keeps firing them every tick. Reap+ them so those instances converge. Where the coordinators do register this is a no-op, because+ the creators own these IDs.+ """+ if settings.DEBUG or is_cloud():+ return+ schedule_ids = [+ trace_summarization_constants.COORDINATOR_SCHEDULE_ID,+ trace_summarization_constants.GENERATION_COORDINATOR_SCHEDULE_ID,+ trace_clustering_constants.COORDINATOR_SCHEDULE_ID,+ trace_clustering_constants.GENERATION_COORDINATOR_SCHEDULE_ID,+ ]+ for schedule_id in schedule_ids:+ if await a_schedule_exists(client, schedule_id):+ await a_delete_schedule(client, schedule_id)++async def create_run_usage_reports_schedule(client: Client):"""Intraday usage report run every 30 minutes.@@ -864,10 +891,6 @@ schedules = [create_sync_events_retention_schedule,create_replay_count_metrics_schedule,create_weekly_digest_schedule,- create_batch_trace_summarization_schedule,- 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,@@ -883,6 +906,7 @@ schedules = [create_experiment_precompute_canary_schedule,create_experiment_precompute_enrollment_census_schedule,cleanup_cohort_calculation_schedules,+ cleanup_non_cloud_ai_observability_schedules,create_ingestion_acceptance_test_schedule,create_warehouse_sources_queue_partition_management_schedule,create_health_check_schedules,@@ -913,6 +937,16 @@ schedules = [create_cleanup_data_quality_check_runs_schedule,]+# AI observability summarization and clustering call the cloud-only guard in+# posthog/temporal/ai_observability/llm_endpoint.py, which permits cloud and local DEBUG installs.+# Anywhere else these coordinators discover teams, spawn the labeling activity, and fail on that+# guard every run, so gate registration on the condition the guard itself uses.+if settings.DEBUG or is_cloud():+ schedules.append(create_batch_trace_summarization_schedule)+ schedules.append(create_batch_generation_summarization_schedule)+ schedules.append(create_trace_clustering_coordinator_schedule)+ schedules.append(create_generation_clustering_coordinator_schedule)+if settings.CLOUD_DEPLOYMENT:# Gemini uploads only happen in cloud; each sweep reaps only the files tracked in this# deployment's own Redis index, so per-deployment scoping is inherent.diff --git a/posthog/temporal/tests/test_schedule.py b/posthog/temporal/tests/test_schedule.pyindex 8bfbf665d6a1..f290af8af95e 100644--- a/posthog/temporal/tests/test_schedule.py+++ b/posthog/temporal/tests/test_schedule.py@@ -6,7 +6,13 @@ from django.test import override_settingsfrom temporalio.client import Schedule, ScheduleActionStartWorkflow-from posthog.temporal.schedule import create_wa_digest_notification_schedule, create_wa_weekly_digest_schedule+from posthog.temporal.ai_observability.trace_clustering import constants as trace_clustering_constants+from posthog.temporal.ai_observability.trace_summarization import constants as trace_summarization_constants+from posthog.temporal.schedule import (+ cleanup_non_cloud_ai_observability_schedules,+ create_wa_digest_notification_schedule,+ create_wa_weekly_digest_schedule,+)# Both WA digest schedules pin their task queue, and the worker registers those workflows on@@ -36,3 +42,40 @@ async def test_wa_digest_schedules_target_the_weekly_digest_queue() -> None:task_queues.append(schedule.action.task_queue)assert task_queues == [settings.WEEKLY_DIGEST_TASK_QUEUE] * 2+++# The reaper converges self-hosted instances that still hold clustering/summarization schedule rows a+# prior release created. It must delete all four there, and nothing where the coordinators still+# register, which is cloud and a local DEBUG install.+ "cloud_deployment,debug,expected_deleted",+ [+ (+ None,+ False,+ [+ trace_summarization_constants.COORDINATOR_SCHEDULE_ID,+ trace_summarization_constants.GENERATION_COORDINATOR_SCHEDULE_ID,+ trace_clustering_constants.COORDINATOR_SCHEDULE_ID,+ trace_clustering_constants.GENERATION_COORDINATOR_SCHEDULE_ID,+ ],+ ),+ ("US", False, []),+ (None, True, []),+ ],+)+async def test_cleanup_non_cloud_ai_observability_schedules(cloud_deployment, debug, expected_deleted) -> None:+ deleted: list[str] = []++ with (+ override_settings(CLOUD_DEPLOYMENT=cloud_deployment, DEBUG=debug),+ mock.patch("posthog.temporal.schedule.a_schedule_exists", new=mock.AsyncMock(return_value=True)),+ mock.patch(+ "posthog.temporal.schedule.a_delete_schedule",+ new=mock.AsyncMock(side_effect=lambda client, schedule_id: deleted.append(schedule_id)),+ ),+ ):+ await cleanup_non_cloud_ai_observability_schedules(mock.MagicMock())++ assert deleted == expected_deleted