: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(aio): stage dedicated AI ingestion endpoint rollout (#68917)
Carlos Marchalc2b6a582a395
diff --git a/ee/hogai/core/runner.py b/ee/hogai/core/runner.pyindex c49b334d6c8b..7c858afcc282 100644--- a/ee/hogai/core/runner.py+++ b/ee/hogai/core/runner.py@@ -37,6 +37,7 @@ from posthog.cloud_utils import is_cloudfrom posthog.event_usage import report_user_actionfrom posthog.models import Team, Userfrom posthog.ph_client import get_client+from posthog.settings.ingestion import DedicatedAIEndpointRolloutfrom posthog.sync import database_sync_to_asyncfrom posthog.utils import get_instance_region@@ -200,17 +201,23 @@ class BaseAgentRunner(ABC):# flush_at=1 flushes each event immediately so traces deliver before short runs end;# before_send truncates oversized AI blobs so they clear the SDK's per-event size drop.- client_kwargs = {"flush_at": 1, "before_send": ai_event_truncator}+ def make_client(region: str):+ return get_client(+ region,+ flush_at=1,+ before_send=ai_event_truncator,+ dedicated_ai_endpoint_stage=DedicatedAIEndpointRollout.RUNNER,+ )# Local deployment or hobbyif not is_cloud() and (local_client := posthoganalytics.default_client):self._callback_handlers.append(init_handler(local_client))elif region := get_instance_region():# Add regional client first- self._callback_handlers.append(init_handler(get_client(region, **client_kwargs)))+ self._callback_handlers.append(init_handler(make_client(region)))# If we're in EU, add the US client as well, so we can see US and EU tracesif region == "EU":- self._callback_handlers.append(init_handler(get_client("US", **client_kwargs)))+ self._callback_handlers.append(init_handler(make_client("US")))self._trace_id = trace_idself._parent_span_id = parent_span_iddiff --git a/ee/hogai/core/test/test_base_callback_handlers.py b/ee/hogai/core/test/test_base_callback_handlers.pyindex 27028173d5e1..37c6a2523756 100644--- a/ee/hogai/core/test/test_base_callback_handlers.py+++ b/ee/hogai/core/test/test_base_callback_handlers.py@@ -6,6 +6,8 @@ from unittest.mock import Mock, patchimport posthoganalyticsfrom posthoganalytics.ai.langchain.callbacks import CallbackHandler+from posthog.settings.ingestion import DedicatedAIEndpointRollout+from products.posthog_ai.backend.models.assistant import Conversationfrom ee.hogai.chat_agent.runner import ChatAgentRunner@@ -67,7 +69,12 @@ class TestBaseAgentRunnerCallbackHandlers(BaseTest):)self.assertEqual(len(runner._callback_handlers), 1)- mock_get_client.assert_called_once_with("US", flush_at=1, before_send=ai_event_truncator)+ mock_get_client.assert_called_once_with(+ "US",+ flush_at=1,+ before_send=ai_event_truncator,+ dedicated_ai_endpoint_stage=DedicatedAIEndpointRollout.RUNNER,+ )@patch("ee.hogai.core.runner.is_cloud")@patch("ee.hogai.core.runner.get_instance_region")@@ -96,8 +103,18 @@ class TestBaseAgentRunnerCallbackHandlers(BaseTest):self.assertEqual(len(runner._callback_handlers), 2)self.assertEqual(mock_get_client.call_count, 2)- mock_get_client.assert_any_call("EU", flush_at=1, before_send=ai_event_truncator)- mock_get_client.assert_any_call("US", flush_at=1, before_send=ai_event_truncator)+ mock_get_client.assert_any_call(+ "EU",+ flush_at=1,+ before_send=ai_event_truncator,+ dedicated_ai_endpoint_stage=DedicatedAIEndpointRollout.RUNNER,+ )+ mock_get_client.assert_any_call(+ "US",+ flush_at=1,+ before_send=ai_event_truncator,+ dedicated_ai_endpoint_stage=DedicatedAIEndpointRollout.RUNNER,+ )@patch("ee.hogai.core.runner.is_cloud")@patch("ee.hogai.core.runner.get_instance_region")diff --git a/posthog/ph_client.py b/posthog/ph_client.pyindex 814d41173ccb..239b5876fd5c 100644--- a/posthog/ph_client.py+++ b/posthog/ph_client.py@@ -4,10 +4,13 @@ from numbers import Numberfrom typing import Anyfrom uuid import UUID+from django.conf import settings+import structlogimport posthoganalyticsfrom posthog.cloud_utils import is_cloud+from posthog.settings.ingestion import DedicatedAIEndpointRolloutfrom posthog.utils import get_instance_regionPH_US_API_KEY = "sTMFPsFhdP1Ssg"@@ -18,6 +21,15 @@ PH_EU_HOST = "https://eu.i.posthog.com"logger = structlog.get_logger(__name__)+_DEDICATED_AI_ENDPOINT_STAGES = (DedicatedAIEndpointRollout.RUNNER, DedicatedAIEndpointRollout.ALL)+++def _use_dedicated_ai_endpoint(caller_stage: DedicatedAIEndpointRollout) -> bool:+ rollout = settings.POSTHOG_DEDICATED_AI_ENDPOINT_ROLLOUT+ if rollout is DedicatedAIEndpointRollout.OFF:+ return False+ return _DEDICATED_AI_ENDPOINT_STAGES.index(rollout) >= _DEDICATED_AI_ENDPOINT_STAGES.index(caller_stage)+def feature_enabled_or_false(key: str,@@ -84,7 +96,12 @@ def ph_scoped_capture():ph_client.shutdown()-def get_client(region: str = "US", **kwargs: Any):+def get_client(+ region: str = "US",+ *,+ dedicated_ai_endpoint_stage: DedicatedAIEndpointRollout = DedicatedAIEndpointRollout.ALL,+ **kwargs: Any,+):from posthoganalytics import Posthogapi_key = None@@ -98,4 +115,10 @@ def get_client(region: str = "US", **kwargs: Any):else:return- return Posthog(api_key, host=host, super_properties={"region": region}, **kwargs)+ return Posthog(+ api_key,+ host=host,+ super_properties={"region": region},+ _dedicated_ai_endpoint=_use_dedicated_ai_endpoint(dedicated_ai_endpoint_stage),+ **kwargs,+ )diff --git a/posthog/settings/ingestion.py b/posthog/settings/ingestion.pyindex 6bff349d7563..386d0dfd6a1e 100644--- a/posthog/settings/ingestion.py+++ b/posthog/settings/ingestion.py@@ -1,4 +1,5 @@import os+from enum import StrEnumimport structlog@@ -64,6 +65,29 @@ CAPTURE_INTERNAL_MAX_WORKERS = get_from_env("CAPTURE_INTERNAL_MAX_WORKERS", typeNEW_ANALYTICS_CAPTURE_ENDPOINT = os.getenv("NEW_CAPTURE_ENDPOINT", "/i/v0/e/")++# Cumulative rollout of the dedicated AI ingestion pipeline for our own `$ai_*` events: each stage+# also routes the stages before it. Chart-toggled so we can advance or roll back without a deploy.+class DedicatedAIEndpointRollout(StrEnum):+ OFF = "off"+ RUNNER = "runner"+ ALL = "all"+++def _parse_dedicated_ai_rollout(value: str) -> "DedicatedAIEndpointRollout":+ try:+ return DedicatedAIEndpointRollout(value.strip().lower())+ except ValueError:+ logger.warning("invalid_dedicated_ai_endpoint_rollout", value=value)+ return DedicatedAIEndpointRollout.OFF+++POSTHOG_DEDICATED_AI_ENDPOINT_ROLLOUT = get_from_env(+ "POSTHOG_DEDICATED_AI_ENDPOINT_ROLLOUT",+ DedicatedAIEndpointRollout.OFF,+ type_cast=_parse_dedicated_ai_rollout,+)+CAPTURE_V1_INTERNAL_ENDPOINT = os.getenv("CAPTURE_V1_INTERNAL_ENDPOINT", "/i/v1/analytics/events")CAPTURE_V1_INTERNAL_MAX_ATTEMPTS = get_from_env("CAPTURE_V1_INTERNAL_MAX_ATTEMPTS", type_cast=int, default=4)CAPTURE_V1_INTERNAL_RETRY_AFTER_CAP_SECONDS = get_from_env(diff --git a/posthog/test/test_ph_client.py b/posthog/test/test_ph_client.pynew file mode 100644index 000000000000..c905fba2f318--- /dev/null+++ b/posthog/test/test_ph_client.py@@ -0,0 +1,46 @@+from django.test import SimpleTestCase, override_settings++from parameterized import parameterized++from posthog.ph_client import get_client+from posthog.settings.ingestion import (+ DedicatedAIEndpointRollout as Rollout,+ _parse_dedicated_ai_rollout,+)+++class TestDedicatedAIEndpointRollout(SimpleTestCase):+ @parameterized.expand(+ [+ (Rollout.OFF, Rollout.RUNNER, False),+ (Rollout.OFF, Rollout.ALL, False),+ (Rollout.RUNNER, Rollout.RUNNER, True),+ (Rollout.RUNNER, Rollout.ALL, False),+ (Rollout.ALL, Rollout.RUNNER, True),+ (Rollout.ALL, Rollout.ALL, True),+ ]+ )+ def test_dedicated_ai_endpoint_gated_by_rollout_stage(self, rollout, caller_stage, expected):+ with override_settings(POSTHOG_DEDICATED_AI_ENDPOINT_ROLLOUT=rollout):+ client = get_client(+ "US", dedicated_ai_endpoint_stage=caller_stage, send=False, enable_local_evaluation=False+ )+ self.assertEqual(client._dedicated_ai_endpoint, expected)++ def test_general_callers_only_opt_in_at_full_rollout(self):+ with override_settings(POSTHOG_DEDICATED_AI_ENDPOINT_ROLLOUT=Rollout.RUNNER):+ self.assertFalse(get_client("US", send=False, enable_local_evaluation=False)._dedicated_ai_endpoint)+ with override_settings(POSTHOG_DEDICATED_AI_ENDPOINT_ROLLOUT=Rollout.ALL):+ self.assertTrue(get_client("US", send=False, enable_local_evaluation=False)._dedicated_ai_endpoint)++ @parameterized.expand(+ [+ ("off", Rollout.OFF),+ ("runner", Rollout.RUNNER),+ ("all", Rollout.ALL),+ (" RUNNER ", Rollout.RUNNER),+ ("bogus", Rollout.OFF),+ ]+ )+ def test_parse_rollout_falls_back_to_off_on_invalid(self, value, expected):+ self.assertEqual(_parse_dedicated_ai_rollout(value), expected)