: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(preflight): restore kafka connectivity probe (#58743)
posthog[bot]8ba83d48f152
diff --git a/posthog/api/test/test_preflight.py b/posthog/api/test/test_preflight.pyindex 8cb2afcd0e41..1a01bc164b12 100644--- a/posthog/api/test/test_preflight.py+++ b/posthog/api/test/test_preflight.py@@ -9,6 +9,7 @@ from unittest.mock import patchfrom django.test import override_settingsfrom django.utils import timezone+from parameterized import parameterizedfrom rest_framework import statusfrom posthog.cloud_utils import TEST_clear_instance_license_cache@@ -317,6 +318,23 @@ class TestPreflight(APIBaseTest, QueryMatchingTest):assert response.json()["allow_dev_login"] is Trueassert is_dev_login_allowed()+ @parameterized.expand([(False,), (True,)])+ def test_preflight_kafka_reflects_probe_on_self_hosted(self, probe_result):+ # Regression for #54702: the kafka probe was removed, hardcoding the+ # response to False off-cloud and blocking self-hosted Live-mode setup.+ # Patch is_kafka_connected at the view's import site so the preflight+ # wiring is exercised directly; TEST=False also defeats the helper's own+ # DEBUG/TEST short-circuit as belt-and-braces.+ self.client.logout()+ with (+ self.is_cloud(False),+ self.settings(TEST=False, OBJECT_STORAGE_ENABLED=False),+ patch("posthog.views.is_kafka_connected", return_value=probe_result),+ ):+ response = self.client.get("/_preflight/")+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["kafka"] is probe_result+@override_settings(DEBUG=True, ALLOW_DEV_LOGIN=False)def test_preflight_omits_allow_dev_login_when_disabled(self):with self.is_cloud(False):diff --git a/posthog/health.py b/posthog/health.pyindex d8adebe92dea..721a2322daff 100644--- a/posthog/health.py+++ b/posthog/health.py@@ -28,10 +28,13 @@ from django.db import DEFAULT_DB_ALIAS, connectionsfrom django.db.migrations.executor import MigrationExecutorfrom django.http import HttpRequest, HttpResponse, JsonResponse+from confluent_kafka import Producer as ConfluentProducerfrom structlog import get_loggerfrom posthog.celery import appfrom posthog.database_healthcheck import DATABASE_FOR_FLAG_MATCHING+from posthog.kafka_client.profiles import KafkaClusterProfile+from posthog.kafka_client.routing import get_producerfrom posthog.security.outbound_proxy import internal_requestslogger = get_logger(__name__)@@ -237,6 +240,32 @@ def is_clickhouse_connected() -> bool:return True+def is_kafka_connected() -> bool:+ """+ Probe Kafka connectivity for the preflight check on self-hosted instances.++ Constructs a producer for the DEFAULT cluster profile (routing-aware) and+ asks for cluster metadata with a short timeout. If either step fails, the+ cluster is treated as unreachable.+ """+ if settings.DEBUG or settings.TEST:+ return True++ try:+ producer = get_producer(profile=KafkaClusterProfile.DEFAULT)+ # Outside TEST/DEBUG `_KafkaProducer` always wraps a real `ConfluentProducer`+ # (the test fake has no `list_topics`), but mypy can't see that from the+ # union type — cast to narrow it.+ cast(ConfluentProducer, producer.producer).list_topics(timeout=3)+ except Exception:+ # Surface at warning, not debug: this probe exists so a self-hosted operator+ # can see *why* /preflight blocks setup. Debug logs are off by default, which+ # would leave them with a red light and no reason.+ logger.warning("kafka_connection_failure", exc_info=True)+ return False+ return True++def is_celery_broker_connected() -> bool:"""Check we can connect to the celery broker.diff --git a/posthog/test/test_health.py b/posthog/test/test_health.pyindex 5b176cffe969..7262db3c6243 100644--- a/posthog/test/test_health.py+++ b/posthog/test/test_health.py@@ -24,7 +24,7 @@ import kombu.connectionimport kombu.exceptionsimport django_redis.exceptions-from posthog.health import logger+from posthog.health import is_kafka_connected, logger@pytest.mark.django_db@@ -372,6 +372,50 @@ def test_readyz_skips_prestop_check_when_setting_is_empty(client: Client):assert resp.status_code == 200[email protected]("debug,test", [(False, True), (True, False)])+def test_is_kafka_connected_short_circuits_under_debug_or_test(debug, test):+ # Either DEBUG or TEST avoids the live probe — keeps local dev and the test+ # suite from needing a real broker.+ with patch("posthog.health.settings.DEBUG", debug), patch("posthog.health.settings.TEST", test):+ assert is_kafka_connected() is True+++ "break_producer",+ [+ pytest.param(+ lambda m: setattr(m, "side_effect", Exception("producer build failed")),+ id="producer_build_raises",+ ),+ pytest.param(+ lambda m: setattr(m.return_value.producer.list_topics, "side_effect", Exception("broker unreachable")),+ id="list_topics_raises",+ ),+ ],+)+def test_is_kafka_connected_returns_false_when_probe_fails(break_producer):+ # Either step failing — building the producer or the metadata round-trip — is+ # treated as the broker being unreachable.+ with (+ patch("posthog.health.settings.DEBUG", False),+ patch("posthog.health.settings.TEST", False),+ patch("posthog.health.get_producer") as get_producer_mock,+ ):+ break_producer(get_producer_mock)+ assert is_kafka_connected() is False+++def test_is_kafka_connected_returns_true_when_metadata_succeeds():+ with (+ patch("posthog.health.settings.DEBUG", False),+ patch("posthog.health.settings.TEST", False),+ patch("posthog.health.get_producer") as get_producer_mock,+ ):+ get_producer_mock.return_value.producer.list_topics.return_value = mock.Mock()+ assert is_kafka_connected() is True+ get_producer_mock.return_value.producer.list_topics.assert_called_once_with(timeout=3)++@pytest.fixture(autouse=True)def debug_log_level():"""diff --git a/posthog/views.py b/posthog/views.pyindex 00bfcb40aedf..26645d77379d 100644--- a/posthog/views.py+++ b/posthog/views.py@@ -29,7 +29,7 @@ from posthog.auth import AUTH_BRAND_COOKIE, apply_auth_brand_cookie, normalize_afrom posthog.cloud_utils import is_cloudfrom posthog.email import is_email_availablefrom posthog.exceptions_capture import capture_exception-from posthog.health import is_clickhouse_connected+from posthog.health import is_clickhouse_connected, is_kafka_connectedfrom posthog.helpers.dev_login import is_dev_login_allowedfrom posthog.models import Organization, Userfrom posthog.models.activity_logging.activity_log import Detail, log_activity@@ -197,7 +197,7 @@ def preflight_check(request: HttpRequest) -> JsonResponse:"clickhouse": in_cloudor _traced("preflight.is_clickhouse_connected", is_clickhouse_connected)or settings.TEST,- "kafka": in_cloud or settings.TEST,+ "kafka": in_cloud or _traced("preflight.is_kafka_connected", is_kafka_connected),"db": in_cloud or _traced("preflight.is_postgres_alive", is_postgres_alive),"initiated": in_cloud or _traced("preflight.organization_exists", Organization.objects.exists),"cloud": in_cloud,