: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(llm-gateway): mirror captures to a configurable secondary instance (#60416)
Vojta Bartošafd86bac2481
diff --git a/services/llm-gateway/src/llm_gateway/callbacks/__init__.py b/services/llm-gateway/src/llm_gateway/callbacks/__init__.pyindex 0a1e84af5270..4a23b2f06f81 100644--- a/services/llm-gateway/src/llm_gateway/callbacks/__init__.py+++ b/services/llm-gateway/src/llm_gateway/callbacks/__init__.py@@ -16,10 +16,14 @@ def init_callbacks() -> None:PostHogCallback(api_key=settings.posthog_project_token,host=settings.posthog_host,+ # Reuses the plan-resolver URL — same per-region value.+ region_url=settings.posthog_api_base_url,+ secondary_api_key=settings.posthog_secondary_project_token,+ secondary_host=settings.posthog_secondary_host,))callbacks.append(RateLimitCallback())callbacks.append(PrometheusCallback())- litellm.callbacks = callbacks+ litellm.callbacks = callbacks # ty: ignore[invalid-assignment]diff --git a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py b/services/llm-gateway/src/llm_gateway/callbacks/posthog.pyindex 3a77cb28a40f..7b303823ceb8 100644--- a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py+++ b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py@@ -113,10 +113,30 @@ class PostHogCallback(InstrumentedCallback):callback_name = "posthog"- def __init__(self, api_key: str, host: str):+ def __init__(+ self,+ api_key: str,+ host: str,+ region_url: str = "https://us.posthog.com",+ secondary_api_key: str | None = None,+ secondary_host: str | None = None,+ ):super().__init__()self._api_key = api_keyself._host = host+ # Customer-origin region URL stamped on every captured event via the+ # `instance` group. The PHAI usage report filters on $group_<N> where+ # N is the destination project's `instance` group_type_index, so the+ # value must be the customer's region URL — not the capture host's.+ # That keeps EU events tagged as EU even when the secondary capture+ # mirrors them to the US instance for engineer visibility.+ self._region_url = region_url+ # Optional second capture target. When set, each captured event is+ # mirrored to this host with the same payload, mirroring the+ # `ee/hogai/core/runner.py:201-206` pattern that lets EU traffic also+ # surface on the US dashboard. Set on the EU gateway deployment only.+ self._secondary_api_key = secondary_api_key+ self._secondary_host = secondary_hostasync def _on_success(self, kwargs: dict[str, Any], response_obj: Any, start_time: float, end_time: float, end_user_id: str | None@@ -159,6 +179,11 @@ class PostHogCallback(InstrumentedCallback):"$ai_span_id": str(uuid4()),"ai_product": product,"$ai_billable": _is_product_billable(product),+ # Stamped explicitly to bypass the SDK's group_type_index lookup.+ # The AI usage report hardcodes `$group_1` (posthog/tasks/usage_report.py)+ # so the gateway must guarantee that slot regardless of how the+ # destination team's group types are registered.+ "$group_1": self._region_url,}# Cache and reasoning token breakdowns are reported by LiteLLM in the@@ -210,9 +235,8 @@ class PostHogCallback(InstrumentedCallback):"distinct_id": distinct_id,"event": "$ai_generation","properties": properties,+ "groups": self._build_groups(team_id),}- if team_id:- capture_kwargs["groups"] = {"project": team_id}logger.debug("PostHog capturing event",@@ -256,6 +280,7 @@ class PostHogCallback(InstrumentedCallback):"$ai_error": standard_logging_object.get("error_str", ""),"ai_product": product,"$ai_billable": _is_product_billable(product),+ "$group_1": self._region_url,}posthog_properties = get_posthog_properties() or {}@@ -275,9 +300,8 @@ class PostHogCallback(InstrumentedCallback):"distinct_id": distinct_id,"event": "$ai_generation","properties": properties,+ "groups": self._build_groups(team_id),}- if team_id:- capture_kwargs["groups"] = {"project": team_id}logger.debug("PostHog capturing error event",@@ -288,6 +312,19 @@ class PostHogCallback(InstrumentedCallback):)self._capture_fire_and_forget(**capture_kwargs)+ def _build_groups(self, team_id: int | None) -> dict[str, Any]:+ """Build the `groups` dict for a captured event.++ Billing region attribution comes from the hardcoded `$group_1`+ property; the `instance` group here keeps LLM Analytics group+ breakdowns working naturally. `project` is included when an+ authenticated team is known.+ """+ groups: dict[str, Any] = {"instance": self._region_url}+ if team_id:+ groups["project"] = team_id+ return groups+def _capture_fire_and_forget(self, **capture_kwargs: Any) -> None:"""Initializes a separate client for the capture operation to avoid payload bloat.@@ -297,9 +334,36 @@ class PostHogCallback(InstrumentedCallback):loop.run_in_executor(None, partial(self._capture_sync, **capture_kwargs))def _capture_sync(self, **capture_kwargs: Any) -> None:+ # No outer try/except: the destinations feed regional billing+ # aggregations, so we want them to succeed or fail together. If the+ # primary raises, the secondary intentionally does not run so the two+ # PostHog instances stay in sync rather than diverging on billing state.+ self._capture_to_destination(self._api_key, self._host, **capture_kwargs)+ if self._secondary_api_key and self._secondary_host:+ self._capture_to_destination(+ self._secondary_api_key,+ self._secondary_host,+ **capture_kwargs,+ )++ def _capture_to_destination(self, api_key: str, host: str, **capture_kwargs: Any) -> None:+ """Fire a single capture against one PostHog instance.++ Each call uses a fresh client so a slow shutdown on one destination+ doesn't pin a pooled client and to avoid cross-destination state+ bleed in the SDK. Mutable `properties` / `groups` dicts are+ shallow-copied per destination so an in-place mutation by the SDK+ (adding `$lib`, `$lib_version`, distinct-id resolution, etc.) on+ one capture cannot bleed into the other.+ """+ capture_kwargs = dict(capture_kwargs)+ if "properties" in capture_kwargs:+ capture_kwargs["properties"] = dict(capture_kwargs["properties"])+ if "groups" in capture_kwargs:+ capture_kwargs["groups"] = dict(capture_kwargs["groups"])client = Posthog(- self._api_key,- host=self._host,+ api_key,+ host=host,sync_mode=True,enable_local_evaluation=False,)@@ -307,7 +371,7 @@ class PostHogCallback(InstrumentedCallback):client.capture(**capture_kwargs)except Exception as e:client.capture_exception(e, **capture_kwargs)- logger.exception("posthog_capture_failed", error=str(e))+ logger.exception("posthog_capture_failed", host=host, error=str(e))finally:client.shutdown()diff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.pyindex f279164f9197..34ef2e055bb6 100644--- a/services/llm-gateway/src/llm_gateway/config.py+++ b/services/llm-gateway/src/llm_gateway/config.py@@ -142,6 +142,13 @@ class Settings(BaseSettings):posthog_project_token: str | None = Noneposthog_host: str = "https://us.i.posthog.com"+ # Optional secondary capture target. When set, every $ai_generation event+ # is mirrored to this PostHog instance after the primary capture, so the+ # EU deployment can land EU customer events on EU PostHog (team_id=1)+ # for the regional billing usage_report to attribute them.+ posthog_secondary_project_token: str | None = None+ posthog_secondary_host: str | None = None+metrics_enabled: bool = True# ~600 bytes per entry (key + AuthenticatedUser + LRU overhead), 10000 entries ≈ 6 MBdiff --git a/services/llm-gateway/tests/callbacks/test_posthog.py b/services/llm-gateway/tests/callbacks/test_posthog.pyindex 53e3743f0dd2..c2ea64d319e1 100644--- a/services/llm-gateway/tests/callbacks/test_posthog.py+++ b/services/llm-gateway/tests/callbacks/test_posthog.py@@ -96,7 +96,7 @@ class TestPostHogCallback:assert call_kwargs["distinct_id"] == "user-distinct-id-123"assert call_kwargs["event"] == "$ai_generation"- assert call_kwargs["groups"] == {"project": 456}+ assert call_kwargs["groups"] == {"instance": "https://us.posthog.com", "project": 456}props = call_kwargs["properties"]assert props["$ai_model"] == "claude-3-opus"@@ -127,8 +127,11 @@ class TestPostHogCallback:await callback._on_success(kwargs, None, 0.0, 1.0, end_user_id=None)call_kwargs = mock_client.capture.call_args.kwargs- # distinct_id should be a UUID string since no auth user- assert "groups" not in call_kwargs # No team_id means no groups+ # distinct_id should be a UUID string since no auth user.+ # The instance group is always set so the destination project can+ # resolve $group_<N> for the region URL filter in the usage report,+ # even when no authenticated team is known.+ assert call_kwargs["groups"] == {"instance": "https://us.posthog.com"}@pytest.mark.asyncioasync def test_on_success_uses_end_user_id_for_distinct_id(@@ -498,7 +501,7 @@ class TestPostHogCallback:call_kwargs = mock_client.capture.call_args.kwargsassert call_kwargs["distinct_id"] == "openai-end-user-456"- assert call_kwargs["groups"] == {"project": 456}+ assert call_kwargs["groups"] == {"instance": "https://us.posthog.com", "project": 456}props = call_kwargs["properties"]assert props["$ai_trace_id"] == _normalize_trace_id("metadata-user-id")@@ -529,6 +532,140 @@ class TestPostHogCallback:assert call_kwargs["properties"]["$ai_trace_id"] == _normalize_trace_id("trace-id-from-metadata")assert _is_uuid(call_kwargs["properties"]["$ai_trace_id"])+ @pytest.mark.asyncio+ async def test_on_success_uses_configured_region_url_in_groups(+ self,+ auth_user: AuthenticatedUser,+ standard_logging_object: dict,+ mock_posthog_client: tuple,+ ) -> None:+ _, mock_client = mock_posthog_client+ callback = PostHogCallback(+ api_key="eu-key",+ host="https://eu.i.posthog.com",+ region_url="https://eu.posthog.com",+ )+ kwargs = {"standard_logging_object": standard_logging_object, "litellm_params": {}}++ with (+ patch("llm_gateway.callbacks.posthog.get_auth_user", return_value=auth_user),+ patch("llm_gateway.callbacks.posthog.get_product", return_value="slack_app"),+ ):+ await callback._on_success(kwargs, None, 0.0, 1.0, end_user_id=None)++ call_kwargs = mock_client.capture.call_args.kwargs+ assert call_kwargs["groups"] == {"instance": "https://eu.posthog.com", "project": 456}+ # $group_1 is stamped explicitly so the usage-report query's hardcoded+ # filter matches regardless of how the destination team registers+ # `instance` in GroupTypeMapping.+ assert call_kwargs["properties"]["$group_1"] == "https://eu.posthog.com"++ @pytest.mark.asyncio+ async def test_on_success_mirrors_to_secondary_destination_when_configured(+ self,+ auth_user: AuthenticatedUser,+ standard_logging_object: dict,+ ) -> None:+ mock_client = MagicMock()+ with patch("llm_gateway.callbacks.posthog.Posthog", return_value=mock_client) as mock_cls:+ callback = PostHogCallback(+ api_key="eu-key",+ host="https://eu.i.posthog.com",+ region_url="https://eu.posthog.com",+ secondary_api_key="us-key",+ secondary_host="https://us.i.posthog.com",+ )+ kwargs = {"standard_logging_object": standard_logging_object, "litellm_params": {}}++ with (+ patch("llm_gateway.callbacks.posthog.get_auth_user", return_value=auth_user),+ patch("llm_gateway.callbacks.posthog.get_product", return_value="slack_app"),+ ):+ await callback._on_success(kwargs, None, 0.0, 1.0, end_user_id=None)++ # One Posthog client constructed per destination, each captured once.+ primary_call, secondary_call = mock_cls.call_args_list+ assert primary_call.args == ("eu-key",)+ assert primary_call.kwargs["host"] == "https://eu.i.posthog.com"+ assert secondary_call.args == ("us-key",)+ assert secondary_call.kwargs["host"] == "https://us.i.posthog.com"+ assert mock_client.capture.call_count == 2++ # Both copies carry the EU origin region — via the SDK `groups` arg+ # and via an explicit $group_1 property — so the US-region usage+ # report filter ($group_1 = 'https://us.posthog.com') excludes the+ # mirrored copy and does not double-count.+ for capture_call in mock_client.capture.call_args_list:+ assert capture_call.kwargs["groups"] == {+ "instance": "https://eu.posthog.com",+ "project": 456,+ }+ assert capture_call.kwargs["properties"]["$group_1"] == "https://eu.posthog.com"++ @pytest.mark.asyncio+ async def test_on_success_skips_secondary_destination_when_unconfigured(+ self,+ callback: PostHogCallback,+ auth_user: AuthenticatedUser,+ standard_logging_object: dict,+ mock_posthog_client: tuple,+ ) -> None:+ mock_cls, mock_client = mock_posthog_client+ kwargs = {"standard_logging_object": standard_logging_object, "litellm_params": {}}++ with (+ patch("llm_gateway.callbacks.posthog.get_auth_user", return_value=auth_user),+ patch("llm_gateway.callbacks.posthog.get_product", return_value="slack_app"),+ ):+ await callback._on_success(kwargs, None, 0.0, 1.0, end_user_id=None)++ assert mock_cls.call_count == 1+ assert mock_client.capture.call_count == 1++ @pytest.mark.asyncio+ async def test_on_failure_mirrors_to_secondary_destination_when_configured(+ self,+ auth_user: AuthenticatedUser,+ ) -> None:+ mock_client = MagicMock()+ with patch("llm_gateway.callbacks.posthog.Posthog", return_value=mock_client) as mock_cls:+ callback = PostHogCallback(+ api_key="eu-key",+ host="https://eu.i.posthog.com",+ region_url="https://eu.posthog.com",+ secondary_api_key="us-key",+ secondary_host="https://us.i.posthog.com",+ )+ kwargs = {+ "standard_logging_object": {+ "model": "claude-sonnet-4-6",+ "custom_llm_provider": "anthropic",+ "error_str": "boom",+ },+ "litellm_params": {},+ }++ with (+ patch("llm_gateway.callbacks.posthog.get_auth_user", return_value=auth_user),+ patch("llm_gateway.callbacks.posthog.get_product", return_value="slack_app"),+ ):+ await callback._on_failure(kwargs, None, 0.0, 1.0, end_user_id=None)++ primary_call, secondary_call = mock_cls.call_args_list+ assert primary_call.args == ("eu-key",)+ assert primary_call.kwargs["host"] == "https://eu.i.posthog.com"+ assert secondary_call.args == ("us-key",)+ assert secondary_call.kwargs["host"] == "https://us.i.posthog.com"+ assert mock_client.capture.call_count == 2++ for capture_call in mock_client.capture.call_args_list:+ assert capture_call.kwargs["groups"] == {+ "instance": "https://eu.posthog.com",+ "project": 456,+ }+ assert capture_call.kwargs["properties"]["$group_1"] == "https://eu.posthog.com"+ assert capture_call.kwargs["properties"]["$ai_is_error"] is True+class TestNormalizeTraceId:def test_returns_fresh_uuid_when_value_is_falsy(self) -> None: