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(capture): add feature-flag-gated routing to capture_v1_internal (#62252)

Eli Reismanbbf43909cbf5
diff --git a/ee/clickhouse/views/groups.py b/ee/clickhouse/views/groups.py
index 7a1ed0ae6889..2caa5a794b11 100644
--- a/ee/clickhouse/views/groups.py
+++ b/ee/clickhouse/views/groups.py
@@ -13,13 +13,12 @@ from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter
from loginas.utils import is_impersonated_session
from opentelemetry import trace
-from requests import HTTPError
from rest_framework import mixins, request, response, serializers, status, viewsets
from rest_framework.exceptions import NotFound, ValidationError
from posthog.schema import ProductKey
-from posthog.api.capture import capture_internal
+from posthog.api.capture_dispatch import CaptureRoutedError, capture_internal_routed
from posthog.api.documentation import extend_schema
from posthog.api.property_value_metrics import PROPERTY_VALUES_DURATION
from posthog.api.routing import TeamAndOrgViewSetMixin
@@ -281,7 +280,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
"$group_set": group_properties or group.group_properties,
}
try:
- capture_internal(
+ result = capture_internal_routed(
token=self.team.api_token,
event_name="$groupidentify",
event_source="ee_ch_views_groups",
@@ -289,15 +288,16 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
timestamp=timezone.now(),
properties=properties,
process_person_profile=False,
- ).raise_for_status()
- except HTTPError as error:
+ )
+ result.raise_for_status()
+ except CaptureRoutedError as error:
raise TriggerGroupIdentifyException(
exception_data={
"code": f"Failed to submit {operation} event.",
"detail": "capture_http_error",
"type": "capture_http_error",
},
- status_code=error.response.status_code,
+ status_code=error.status_code or 502,
)
except Exception:
raise TriggerGroupIdentifyException(
@@ -629,18 +629,18 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
}
try:
- resp = capture_internal(
+ routed_result = capture_internal_routed(
token=self.team.api_token,
event_name=event_name,
event_source="ee_ch_views_groups",
distinct_id=team_uuid_as_distinct_id,
timestamp=timestamp,
properties=properties,
- process_person_profile=False, # don't process person profile
+ process_person_profile=False,
)
- resp.raise_for_status()
+ routed_result.raise_for_status()
- except HTTPError as e:
+ except CaptureRoutedError as e:
return response.Response(
{
"attr": "$unset",
@@ -648,7 +648,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
"detail": "capture_http_error",
"type": "capture_http_error",
},
- status=e.response.status_code,
+ status=e.status_code or 502,
)
except Exception:
return response.Response(
diff --git a/ee/clickhouse/views/test/test_clickhouse_groups.py b/ee/clickhouse/views/test/test_clickhouse_groups.py
index d54dfff9c1ea..b36cf4a3e2c2 100644
--- a/ee/clickhouse/views/test/test_clickhouse_groups.py
+++ b/ee/clickhouse/views/test/test_clickhouse_groups.py
@@ -304,7 +304,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(message["event"], "Group notebook creation failed")
@freeze_time("2021-05-02")
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")
def test_create_group_missing_group_properties(self, mock_capture):
group_type_mapping = create_group_type_mapping_without_created_at(
team=self.team,
@@ -336,7 +336,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
mock_capture.assert_called_once()
@freeze_time("2021-05-02")
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")
@pytest.mark.flaky(reruns=2)
def test_create_group(self, mock_capture):
group_type_mapping = create_group_type_mapping_without_created_at(
@@ -424,7 +424,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
prop_name = result["detail"]["name"]
self.assertEqual(result["detail"]["changes"][0]["after"], group_properties[prop_name])
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")
def test_create_group_duplicated_group_key(self, mock_capture):
group_type_mapping = create_group_type_mapping_without_created_at(
team=self.team,
@@ -461,7 +461,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
)
mock_capture.assert_not_called()
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")
def test_create_group_missing_group_key(self, mock_capture):
group_type_mapping = create_group_type_mapping_without_created_at(
team=self.team,
@@ -491,7 +491,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
)
mock_capture.assert_not_called()
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")
def test_create_group_missing_group_type_index(self, mock_capture):
response = self.client.post(
f"/api/projects/{self.team.id}/groups",
@@ -515,7 +515,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
mock_capture.assert_not_called()
@freeze_time("2021-05-02")
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")
@pytest.mark.flaky(reruns=2)
def test_group_property_crud_add_success(self, mock_capture):
group_type_mapping = create_group_type_mapping_without_created_at(
@@ -600,7 +600,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.json()["results"][0]["detail"]["changes"][0]["after"], "technology")
@freeze_time("2021-05-02")
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")
@pytest.mark.flaky(reruns=2)
def test_group_property_crud_update_success(self, mock_capture):
group_type_mapping = create_group_type_mapping_without_created_at(
@@ -724,7 +724,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, 404)
@freeze_time("2021-05-02")
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")
@pytest.mark.flaky(reruns=2)
def test_group_property_crud_delete_success(self, mock_capture):
group_type_mapping = create_group_type_mapping_without_created_at(
@@ -859,7 +859,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, 400)
@freeze_time("2021-05-02")
- @patch("ee.clickhouse.views.groups.capture_internal")
+ @patch("ee.clickhouse.views.groups.capture_internal_routed")
def test_delete_property_nonexistent_property(self, mock_capture):
mock_capture.return_value = mock.MagicMock(status_code=200)
create_group_type_mapping_without_created_at(
@@ -904,7 +904,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, 400)
@freeze_time("2021-05-02")
- @patch("ee.clickhouse.views.groups.capture_internal")
+ @patch("ee.clickhouse.views.groups.capture_internal_routed")
def test_get_group_activities_success(self, mock_capture):
# Mock the response to return a 200 OK
mock_capture.return_value = mock.MagicMock(status_code=200)
@@ -944,7 +944,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.json()["results"][0]["detail"]["changes"][0]["action"], "changed")
@freeze_time("2021-05-02")
- @patch("ee.clickhouse.views.groups.capture_internal")
+ @patch("ee.clickhouse.views.groups.capture_internal_routed")
def test_get_group_activities_invalid_group(self, mock_capture):
# Mock the response to return a 200 OK
mock_capture.return_value = mock.MagicMock(status_code=200)
@@ -2098,7 +2098,7 @@ class GroupPropertyDefinitionsTestCase(ClickhouseTestMixin, APIBaseTest):
self.group_key = "test_company"
self.base_url = f"/api/projects/{self.team.id}/groups/"
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")
def test_create_group_creates_property_definitions(self, mock_capture):
data = {
"group_type_index": self.group_type_index,
@@ -2132,7 +2132,7 @@ class GroupPropertyDefinitionsTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(revenue_prop.property_type, "Numeric")
self.assertTrue(revenue_prop.is_numerical)
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")
def test_update_property_creates_property_definition(self, mock_capture):
create_group(
team_id=self.team.pk,
@@ -2162,7 +2162,7 @@ class GroupPropertyDefinitionsTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(prop_def.property_type, "String")
self.assertFalse(prop_def.is_numerical)
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")
def test_update_property_with_different_types(self, mock_capture):
create_group(
team_id=self.team.pk, group_type_index=self.group_type_index, group_key=self.group_key, properties={}
@@ -2199,7 +2199,7 @@ class GroupPropertyDefinitionsTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(prop_def.property_type, expected_type)
self.assertEqual(prop_def.is_numerical, expected_numerical)
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")
def test_update_existing_property_definition(self, mock_capture):
create_group(
team_id=self.team.pk, group_type_index=self.group_type_index, group_key=self.group_key, properties={}
@@ -2227,7 +2227,7 @@ class GroupPropertyDefinitionsTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(prop_def.property_type, "Numeric")
self.assertTrue(prop_def.is_numerical)
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")
def test_update_property_missing_key(self, mock_capture):
mock_capture.return_value = mock.MagicMock(status_code=200)
create_group(
@@ -2241,7 +2241,7 @@ class GroupPropertyDefinitionsTestCase(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(response.status_code, 400)
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")
def test_update_property_empty_key(self, mock_capture):
mock_capture.return_value = mock.MagicMock(status_code=200)
create_group(
@@ -2255,7 +2255,7 @@ class GroupPropertyDefinitionsTestCase(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(response.status_code, 400)
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")
def test_property_definitions_have_correct_group_type_index(self, mock_capture):
self.group_type_mapping = create_group_type_mapping_without_created_at(
team=self.team,
diff --git a/posthog/api/capture.py b/posthog/api/capture.py
index 3385daada5bf..3df61ac4d63e 100644
--- a/posthog/api/capture.py
+++ b/posthog/api/capture.py
@@ -6,6 +6,7 @@ import structlog
from prometheus_client import Counter
from requests import Response
from requests.adapters import HTTPAdapter, Retry
+from requests.exceptions import RequestException
from posthog.logging.timing import timed
from posthog.security.outbound_proxy import internal_requests_session
@@ -31,6 +32,11 @@ CAPTURE_INTERNAL_EVENT_SUBMITTED_COUNTER = Counter(
"Events received by capture_internal, tagged by source.",
labelnames=["event_source"], # which internal codepath submitted this event
)
+CAPTURE_INTERNAL_REQUEST_FAILED = Counter(
+ "capture_internal_request_failed",
+ "Failures from legacy capture_internal, tagged by source and status.",
+ labelnames=["event_source", "status_code"],
+)
class CaptureInternalError(Exception):
@@ -112,11 +118,20 @@ def capture_internal(
)
CAPTURE_INTERNAL_EVENT_SUBMITTED_COUNTER.labels(event_source=event_source).inc()
- return s.post(
- resolved_capture_url,
- json=event_payload,
- timeout=2,
- )
+ try:
+ resp = s.post(
+ resolved_capture_url,
+ json=event_payload,
+ timeout=2,
+ )
+ except RequestException:
+ CAPTURE_INTERNAL_REQUEST_FAILED.labels(event_source=event_source, status_code="transport").inc()
+ raise
+
+ if resp.status_code >= 400:
+ CAPTURE_INTERNAL_REQUEST_FAILED.labels(event_source=event_source, status_code=str(resp.status_code)).inc()
+
+ return resp
def capture_batch_internal(
diff --git a/posthog/api/capture_dispatch.py b/posthog/api/capture_dispatch.py
new file mode 100644
index 000000000000..96e36587a432
--- /dev/null
+++ b/posthog/api/capture_dispatch.py
@@ -0,0 +1,398 @@
+"""Feature-flag-gated dispatch between legacy capture_internal and capture_v1_internal.
+
+Temporary scaffolding for the legacy -> v1 capture transition. Each production
+call site routes through ``capture_internal_routed`` (or ``capture_batch_internal_routed``
+for the CSP batch path), gated by a per-``event_source`` boolean feature flag.
+
+Teardown
+--------
+Once a source is fully cut over (flag at 100 % after bake period):
+
+1. Repoint that call site to call ``capture_v1_internal`` directly and adopt its
+ native ``CaptureV1Result`` / ``CaptureV1InternalError`` handling.
+2. Delete the source's flag from PostHog and from ``EVENT_SOURCE_TO_FLAG``.
+
+When all 9 sources are migrated, delete this module, ``CaptureRoutedError``,
+``RoutedCaptureResult``, and the 9 flags in a single PR. Legacy
+``capture_internal`` is removed only after no source references it.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Literal, Optional
+
+import structlog
+import posthoganalytics
+from prometheus_client import Counter
+from requests import HTTPError
+
+from posthog.api.capture import (
+ SESSION_RECORDING_EVENT_NAMES,
+ CaptureInternalError,
+ capture_batch_internal,
+ capture_internal,
+)
+from posthog.api.capture_v1 import CaptureV1InternalError, capture_v1_batch_internal, capture_v1_internal
+
+logger = structlog.get_logger(__name__)
+
+# --------------------------------------------------------------------------- #
+# Flag registry — one boolean flag per event_source tag
+# --------------------------------------------------------------------------- #
+
+EVENT_SOURCE_TO_FLAG: dict[str, str] = {
+ "get_csp_report": "capture-v1-get-csp-report",
+ "person_viewset": "capture-v1-person-viewset",
+ "ee_ch_views_groups": "capture-v1-ee-ch-views-groups",
+ "llm_analytics_evaluation": "capture-v1-llm-analytics-evaluation",
+ "llm_analytics_tagger": "capture-v1-llm-analytics-tagger",
+ "replay_vision": "capture-v1-replay-vision",
+ "session_summary_events": "capture-v1-session-summary-events",
+ "conversations_events": "capture-v1-conversations-events",
+ "llm_prompt_management": "capture-v1-llm-prompt-management",
+}
+
+# --------------------------------------------------------------------------- #
+# Metrics
+# --------------------------------------------------------------------------- #
+
+CAPTURE_INTERNAL_ROUTED = Counter(
+ "capture_internal_routed",
+ "Dispatch decisions between legacy and v1 capture implementations.",
+ labelnames=["event_source", "impl"],
+)
+
+CAPTURE_ROUTED_ERROR = Counter(
+ "capture_internal_routed_error",
+ "Errors from the routed capture path.",
+ labelnames=["event_source", "impl", "error_type"],
+)
+
+# --------------------------------------------------------------------------- #
+# Normalized error type
+# --------------------------------------------------------------------------- #
+
+
+class CaptureRoutedError(CaptureInternalError):
+ """Normalized error raised by ``RoutedCaptureResult.raise_for_status()``.
+
+ Carries a ``.status_code`` so call sites that previously read
+ ``he.response.status_code`` from ``requests.HTTPError`` can use
+ ``err.status_code`` instead.
+ """
+
+ def __init__(self, message: str, *, status_code: int = 0) -> None:
+ super().__init__(message)
+ self.status_code = status_code
+
+
+# --------------------------------------------------------------------------- #
+# Normalized result type
+# --------------------------------------------------------------------------- #
+
+
+class RoutedCaptureResult:
+ """Unified result from either legacy or v1 capture path."""
+
+ __slots__ = ("status_code", "impl", "_error_message")
+
+ def __init__(
+ self,
+ *,
+ status_code: int,
+ impl: Literal["legacy", "v1"],
+ error_message: Optional[str] = None,
+ ) -> None:
+ self.status_code = status_code
+ self.impl: Literal["legacy", "v1"] = impl
+ self._error_message = error_message
+
+ def raise_for_status(self) -> None:
+ if self._error_message is not None:
+ raise CaptureRoutedError(self._error_message, status_code=self.status_code)
+
+
+# --------------------------------------------------------------------------- #
+# Flag evaluation — fail-closed to legacy
+# --------------------------------------------------------------------------- #
+
+
+def _capture_v1_enabled(event_source: str, *, token: Optional[str] = None) -> bool:
+ """Check whether v1 capture is enabled for this event_source.
+
+ Uses ``only_evaluate_locally=True`` (backed by HyperCacheFlagProvider in
+ Redis) to avoid a ``/decide`` network call per captured event.
+ Falls back to legacy on any exception or missing flag definition.
+ """
+ flag_key = EVENT_SOURCE_TO_FLAG.get(event_source)
+ if not flag_key:
+ return False
+
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ flag_key,
+ token or "",
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ logger.debug(
+ "capture_v1_flag_eval_failed",
+ event_source=event_source,
+ flag_key=flag_key,
+ )
+ return False
+
+
+# --------------------------------------------------------------------------- #
+# Single-event dispatch
+# --------------------------------------------------------------------------- #
+
+
+def capture_internal_routed(
+ *,
+ event_source: str,
+ token: str,
+ event_name: str,
+ distinct_id: str,
+ timestamp: Any = None,
+ properties: dict[str, Any],
+ sent_at: Any = None,
+ process_person_profile: bool = False,
+ event_uuid: Optional[str] = None,
+) -> RoutedCaptureResult:
+ """Dispatch a single event to legacy or v1 capture based on feature flag.
+
+ Signature-compatible with ``capture_internal``.
+
+ Note: ``sent_at`` is forwarded on the legacy path only.
+ ``capture_v1_internal`` does not accept ``sent_at`` (skew correction is
+ handled server-side). No current call site passes it.
+ """
+ # Replay events are unsupported by v1 — always use legacy.
+ use_v1 = event_name not in SESSION_RECORDING_EVENT_NAMES and _capture_v1_enabled(event_source, token=token)
+
+ impl: Literal["legacy", "v1"] = "v1" if use_v1 else "legacy"
+ CAPTURE_INTERNAL_ROUTED.labels(event_source=event_source, impl=impl).inc()
+
+ if use_v1:
+ return _route_v1_single(
+ event_source=event_source,
+ token=token,
+ event_name=event_name,
+ distinct_id=distinct_id,
+ timestamp=timestamp,
+ properties=properties,
+ process_person_profile=process_person_profile,
+ event_uuid=event_uuid,
+ )
+
+ return _route_legacy_single(
+ event_source=event_source,
+ token=token,
+ event_name=event_name,
+ distinct_id=distinct_id,
+ timestamp=timestamp,
+ properties=properties,
+ sent_at=sent_at,
+ process_person_profile=process_person_profile,
+ event_uuid=event_uuid,
+ )
+
+
+def _route_legacy_single(
+ *,
+ event_source: str,
+ token: str,
+ event_name: str,
+ distinct_id: str,
+ timestamp: Any,
+ properties: dict[str, Any],
+ sent_at: Any,
+ process_person_profile: bool,
+ event_uuid: Optional[str],
+) -> RoutedCaptureResult:
+ try:
+ resp = capture_internal(
+ token=token,
+ event_name=event_name,
+ event_source=event_source,
+ distinct_id=distinct_id,
+ timestamp=timestamp,
+ properties=properties,
+ sent_at=sent_at,
+ process_person_profile=process_person_profile,
+ event_uuid=event_uuid,
+ )
+ resp.raise_for_status()
+ return RoutedCaptureResult(status_code=resp.status_code, impl="legacy")
+ except HTTPError as exc:
+ status = exc.response.status_code if exc.response is not None else 0
+ CAPTURE_ROUTED_ERROR.labels(event_source=event_source, impl="legacy", error_type="http").inc()
+ return RoutedCaptureResult(
+ status_code=status,
+ impl="legacy",
+ error_message=f"capture_internal HTTP error ({status}): {exc}",
+ )
+ except CaptureInternalError:
+ raise
+ except Exception as exc:
+ CAPTURE_ROUTED_ERROR.labels(event_source=event_source, impl="legacy", error_type="transport").inc()
+ return RoutedCaptureResult(
+ status_code=0,
+ impl="legacy",
+ error_message=f"capture_internal transport error: {exc}",
+ )
+
+
+def _route_v1_single(
+ *,
+ event_source: str,
+ token: str,
+ event_name: str,
+ distinct_id: str,
+ timestamp: Any,
+ properties: dict[str, Any],
+ process_person_profile: bool,
+ event_uuid: Optional[str],
+) -> RoutedCaptureResult:
+ try:
+ result = capture_v1_internal(
+ token=token,
+ event_name=event_name,
+ event_source=event_source,
+ distinct_id=distinct_id,
+ timestamp=timestamp,
+ properties=properties,
+ process_person_profile=process_person_profile,
+ event_uuid=event_uuid,
+ )
+ result.raise_for_status()
+ return RoutedCaptureResult(status_code=result.status_code, impl="v1")
+ except CaptureV1InternalError as exc:
+ CAPTURE_ROUTED_ERROR.labels(event_source=event_source, impl="v1", error_type="v1_error").inc()
+ return RoutedCaptureResult(
+ status_code=getattr(exc, "status_code", 0),
+ impl="v1",
+ error_message=str(exc),
+ )
+ except CaptureInternalError:
+ raise
+ except Exception as exc:
+ CAPTURE_ROUTED_ERROR.labels(event_source=event_source, impl="v1", error_type="transport").inc()
+ return RoutedCaptureResult(
+ status_code=0,
+ impl="v1",
+ error_message=f"capture_v1_internal transport error: {exc}",
+ )
+
+
+# --------------------------------------------------------------------------- #
+# Batch dispatch (CSP report only)
+# --------------------------------------------------------------------------- #
+
+
+def capture_batch_internal_routed(
+ *,
+ events: list[dict[str, Any]],
+ event_source: str,
+ token: str,
+ process_person_profile: bool = False,
+) -> RoutedCaptureResult:
+ """Dispatch a batch to legacy or v1 capture based on feature flag.
+
+ Normalizes both paths to a single ``RoutedCaptureResult`` that raises on
+ any per-event failure — matching the existing ``report.py`` semantics where
+ the first ``HTTPError`` from any future propagates.
+ """
+ use_v1 = _capture_v1_enabled(event_source, token=token)
+ impl: Literal["legacy", "v1"] = "v1" if use_v1 else "legacy"
+ CAPTURE_INTERNAL_ROUTED.labels(event_source=event_source, impl=impl).inc()
+
+ if use_v1:
+ return _route_v1_batch(
+ events=events,
+ event_source=event_source,
+ token=token,
+ process_person_profile=process_person_profile,
+ )
+
+ return _route_legacy_batch(
+ events=events,
+ event_source=event_source,
+ token=token,
+ process_person_profile=process_person_profile,
+ )
+
+
+def _route_legacy_batch(
+ *,
+ events: list[dict[str, Any]],
+ event_source: str,
+ token: str,
+ process_person_profile: bool,
+) -> RoutedCaptureResult:
+ try:
+ futures = capture_batch_internal(
+ events=events,
+ event_source=event_source,
+ token=token,
+ process_person_profile=process_person_profile,
+ )
+ for future in futures:
+ result = future.result()
+ result.raise_for_status()
+ return RoutedCaptureResult(status_code=204, impl="legacy")
+ except HTTPError as exc:
+ status = exc.response.status_code if exc.response is not None else 0
+ CAPTURE_ROUTED_ERROR.labels(event_source=event_source, impl="legacy", error_type="http").inc()
+ return RoutedCaptureResult(
+ status_code=status,
+ impl="legacy",
+ error_message=f"capture_batch_internal HTTP error ({status}): {exc}",
+ )
+ except CaptureInternalError:
+ raise
+ except Exception as exc:
+ CAPTURE_ROUTED_ERROR.labels(event_source=event_source, impl="legacy", error_type="transport").inc()
+ return RoutedCaptureResult(
+ status_code=0,
+ impl="legacy",
+ error_message=f"capture_batch_internal transport error: {exc}",
+ )
+
+
+def _route_v1_batch(
+ *,
+ events: list[dict[str, Any]],
+ event_source: str,
+ token: str,
+ process_person_profile: bool,
+) -> RoutedCaptureResult:
+ try:
+ result = capture_v1_batch_internal(
+ events=events,
+ event_source=event_source,
+ token=token,
+ process_person_profile=process_person_profile,
+ )
+ result.raise_for_status()
+ return RoutedCaptureResult(status_code=result.status_code, impl="v1")
+ except CaptureV1InternalError as exc:
+ CAPTURE_ROUTED_ERROR.labels(event_source=event_source, impl="v1", error_type="v1_error").inc()
+ return RoutedCaptureResult(
+ status_code=0,
+ impl="v1",
+ error_message=str(exc),
+ )
+ except CaptureInternalError:
+ raise
+ except Exception as exc:
+ CAPTURE_ROUTED_ERROR.labels(event_source=event_source, impl="v1", error_type="transport").inc()
+ return RoutedCaptureResult(
+ status_code=0,
+ impl="v1",
+ error_message=f"capture_v1_batch_internal transport error: {exc}",
+ )
diff --git a/posthog/api/llm_prompt.py b/posthog/api/llm_prompt.py
index 2060b1f1bfdb..bdc2c0ecc723 100644
--- a/posthog/api/llm_prompt.py
+++ b/posthog/api/llm_prompt.py
@@ -15,7 +15,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.serializers import BaseSerializer
-from posthog.api.capture import capture_internal
+from posthog.api.capture_dispatch import capture_internal_routed
from posthog.api.llm_prompt_serializers import (
LLMPromptDuplicateSerializer,
LLMPromptFetchQuerySerializer,
@@ -192,7 +192,7 @@ class LLMPromptViewSet(
def _track_prompt_fetch(self, prompt: dict[str, Any]) -> None:
if not settings.TEST:
try:
- capture_internal(
+ capture_internal_routed(
token=self.team.api_token,
event_name=PROMPT_FETCHED_EVENT,
event_source=PROMPT_FETCHED_EVENT_SOURCE,
diff --git a/posthog/api/person.py b/posthog/api/person.py
index 87b110ba5077..866358da13aa 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -19,7 +19,6 @@ from drf_spectacular.utils import (
from loginas.utils import is_impersonated_session
from opentelemetry import trace
from prometheus_client import Counter
-from requests import HTTPError
from rest_framework import request, response, serializers, viewsets
from rest_framework.exceptions import MethodNotAllowed, NotFound, ValidationError
from rest_framework.pagination import LimitOffsetPagination
@@ -33,7 +32,7 @@ from posthog.schema import ProductKey
from posthog.hogql.constants import CSV_EXPORT_LIMIT
-from posthog.api.capture import capture_internal
+from posthog.api.capture_dispatch import CaptureRoutedError, capture_internal_routed
from posthog.api.documentation import PersonPropertiesSerializer
from posthog.api.property_value_metrics import PROPERTY_VALUES_DURATION
from posthog.api.routing import TeamAndOrgViewSetMixin
@@ -962,7 +961,7 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
}
try:
- resp = capture_internal(
+ result = capture_internal_routed(
token=self.team.api_token,
event_name=event_name,
event_source="person_viewset",
@@ -971,26 +970,24 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
properties=properties,
process_person_profile=True,
)
- resp.raise_for_status()
+ result.raise_for_status()
- # HTTP error - if applicable, thrown after retires are exhausted
- except HTTPError as he:
+ except CaptureRoutedError as cre:
logger.warning(
"delete_person_property.capture_http_error",
team_id=self.team_id,
person_uuid=str(person.uuid),
property_key=request.data.get("$unset"),
- status_code=he.response.status_code,
+ status_code=cre.status_code,
)
return response.Response(
{
"success": False,
"detail": "Unable to delete property",
},
- status=he.response.status_code,
+ status=cre.status_code or 502,
)
- # catches event payload errors (CaptureInternalError) and misc. (timeout etc.)
except Exception:
logger.exception(
"delete_person_property.capture_error",
@@ -1135,7 +1132,7 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
}
try:
- resp = capture_internal(
+ result = capture_internal_routed(
token=self.team.api_token,
event_name=event_name,
event_source="person_viewset",
@@ -1144,7 +1141,7 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
properties=properties,
process_person_profile=True,
)
- resp.raise_for_status()
+ result.raise_for_status()
# Failures in this codepath (old and new) are ignored here
except Exception:
diff --git a/posthog/api/report.py b/posthog/api/report.py
index 3421b4a41328..ba96f9ec6069 100644
--- a/posthog/api/report.py
+++ b/posthog/api/report.py
@@ -2,10 +2,9 @@ from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
import structlog
-from requests import HTTPError
from rest_framework import status
-from posthog.api.capture import capture_batch_internal, capture_internal
+from posthog.api.capture_dispatch import CaptureRoutedError, capture_batch_internal_routed, capture_internal_routed
from posthog.api.csp import process_csp_report
from posthog.api.utils import get_token
from posthog.exceptions import generate_exception_response
@@ -60,14 +59,12 @@ def get_csp_event(request):
token = ""
if isinstance(csp_report, list):
- futures = capture_batch_internal(
+ result = capture_batch_internal_routed(
events=csp_report, event_source="get_csp_report", token=token, process_person_profile=False
)
- for future in futures:
- result = future.result()
- result.raise_for_status()
+ result.raise_for_status()
else:
- resp = capture_internal(
+ result = capture_internal_routed(
token=token,
event_name=csp_report.get("event", ""),
event_source="get_csp_report",
@@ -76,13 +73,13 @@ def get_csp_event(request):
properties=csp_report.get("properties", {}),
process_person_profile=False,
)
- resp.raise_for_status()
+ result.raise_for_status()
return cors_response(request, HttpResponse(status=status.HTTP_204_NO_CONTENT))
- except HTTPError as hte:
- capture_exception(hte, {"capture-http": "csp_report", "ph-team-token": token})
- logger.exception("csp_report_capture_http_error", exc_info=hte)
+ except CaptureRoutedError as cre:
+ capture_exception(cre, {"capture-http": "csp_report", "ph-team-token": token})
+ logger.exception("csp_report_capture_http_error", exc_info=cre)
return cors_response(
request,
generate_exception_response(
@@ -90,7 +87,7 @@ def get_csp_event(request):
f"Failed to submit CSP report",
code="capture_http_error",
type="capture_http_error",
- status_code=hte.response.status_code,
+ status_code=cre.status_code or status.HTTP_502_BAD_GATEWAY,
),
)
except Exception as e:
diff --git a/posthog/api/test/test_capture_dispatch.py b/posthog/api/test/test_capture_dispatch.py
new file mode 100644
index 000000000000..09be073baf98
--- /dev/null
+++ b/posthog/api/test/test_capture_dispatch.py
@@ -0,0 +1,258 @@
+from datetime import UTC, datetime
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.api.capture_dispatch import (
+ CAPTURE_INTERNAL_ROUTED,
+ CAPTURE_ROUTED_ERROR,
+ CaptureRoutedError,
+ RoutedCaptureResult,
+ _capture_v1_enabled,
+ capture_batch_internal_routed,
+ capture_internal_routed,
+)
+
+
+def _make_ok_result(status_code: int = 200) -> MagicMock:
+ result = MagicMock()
+ result.status_code = status_code
+ result.raise_for_status.return_value = None
+ return result
+
+
+COMMON_KWARGS: dict[str, Any] = {
+ "token": "phc_test",
+ "event_name": "test_event",
+ "distinct_id": "user-1",
+ "timestamp": datetime.now(UTC),
+ "properties": {"key": "value"},
+ "event_source": "person_viewset",
+}
+
+
+class TestRoutedCaptureResult(SimpleTestCase):
+ def test_success_no_raise(self) -> None:
+ r = RoutedCaptureResult(status_code=200, impl="legacy")
+ r.raise_for_status()
+
+ def test_error_raises_with_status(self) -> None:
+ r = RoutedCaptureResult(status_code=503, impl="legacy", error_message="server error")
+ with self.assertRaises(CaptureRoutedError) as ctx:
+ r.raise_for_status()
+ assert ctx.exception.status_code == 503
+ assert "server error" in str(ctx.exception)
+
+
+class TestCaptureRoutedError(SimpleTestCase):
+ def test_is_subclass_of_capture_internal_error(self) -> None:
+ from posthog.api.capture import CaptureInternalError
+
+ err = CaptureRoutedError("test", status_code=404)
+ assert isinstance(err, CaptureInternalError)
+ assert err.status_code == 404
+
+
+class TestCaptureV1Enabled(SimpleTestCase):
+ def test_unknown_event_source_returns_false(self) -> None:
+ assert _capture_v1_enabled("nonexistent_source", token="phc_test") is False
+
+ def test_no_token_returns_false(self) -> None:
+ assert _capture_v1_enabled("person_viewset") is False
+
+ @patch("posthog.api.capture_dispatch.posthoganalytics.feature_enabled", return_value=True)
+ def test_flag_enabled_returns_true(self, mock_flag: MagicMock) -> None:
+ assert _capture_v1_enabled("person_viewset", token="phc_test") is True
+ mock_flag.assert_called_once()
+ call_kwargs = mock_flag.call_args.kwargs
+ assert call_kwargs["only_evaluate_locally"] is True
+ assert call_kwargs["send_feature_flag_events"] is False
+
+ @patch("posthog.api.capture_dispatch.posthoganalytics.feature_enabled", return_value=False)
+ def test_flag_disabled_returns_false(self, mock_flag: MagicMock) -> None:
+ assert _capture_v1_enabled("person_viewset", token="phc_test") is False
+
+ @patch("posthog.api.capture_dispatch.posthoganalytics.feature_enabled", side_effect=Exception("boom"))
+ def test_exception_returns_false(self, mock_flag: MagicMock) -> None:
+ assert _capture_v1_enabled("person_viewset", token="phc_test") is False
+
+ @patch("posthog.api.capture_dispatch.posthoganalytics.feature_enabled", return_value=None)
+ def test_none_returns_false(self, mock_flag: MagicMock) -> None:
+ assert _capture_v1_enabled("person_viewset", token="phc_test") is False
+
+
+class TestCaptureInternalRouted(SimpleTestCase):
+ @patch("posthog.api.capture_dispatch._capture_v1_enabled", return_value=False)
+ @patch("posthog.api.capture_dispatch.capture_internal")
+ def test_flag_off_routes_to_legacy(self, mock_capture: MagicMock, mock_flag: MagicMock) -> None:
+ mock_capture.return_value = _make_ok_result()
+
+ result = capture_internal_routed(**COMMON_KWARGS)
+ assert result.impl == "legacy"
+ assert result.status_code == 200
+ result.raise_for_status()
+ mock_capture.assert_called_once()
+
+ @patch("posthog.api.capture_dispatch._capture_v1_enabled", return_value=True)
+ @patch("posthog.api.capture_dispatch.capture_v1_internal")
+ def test_flag_on_routes_to_v1(self, mock_v1: MagicMock, mock_flag: MagicMock) -> None:
+ mock_v1.return_value = _make_ok_result()
+
+ result = capture_internal_routed(**COMMON_KWARGS)
+ assert result.impl == "v1"
+ assert result.status_code == 200
+ result.raise_for_status()
+ mock_v1.assert_called_once()
+
+ @parameterized.expand([("$snapshot",), ("$performance_event",), ("$snapshot_items",)])
+ @patch("posthog.api.capture_dispatch._capture_v1_enabled", return_value=True)
+ @patch("posthog.api.capture_dispatch.capture_internal")
+ def test_all_replay_event_names_force_legacy(
+ self, event_name: str, mock_capture: MagicMock, mock_flag: MagicMock
+ ) -> None:
+ mock_capture.return_value = _make_ok_result()
+ kwargs = {**COMMON_KWARGS, "event_name": event_name}
+ result = capture_internal_routed(**kwargs)
+ assert result.impl == "legacy"
+
+ @patch("posthog.api.capture_dispatch._capture_v1_enabled", return_value=False)
+ @patch("posthog.api.capture_dispatch.capture_internal")
+ def test_legacy_http_error_normalized(self, mock_capture: MagicMock, mock_flag: MagicMock) -> None:
+ from requests import HTTPError
+
+ resp_mock = MagicMock()
+ resp_mock.status_code = 503
+ resp_mock.raise_for_status.side_effect = HTTPError(response=resp_mock)
+ mock_capture.return_value = resp_mock
+
+ result = capture_internal_routed(**COMMON_KWARGS)
+ assert result.impl == "legacy"
+ assert result.status_code == 503
+ with self.assertRaises(CaptureRoutedError) as ctx:
+ result.raise_for_status()
+ assert ctx.exception.status_code == 503
+
+ @patch("posthog.api.capture_dispatch._capture_v1_enabled", return_value=True)
+ @patch("posthog.api.capture_dispatch.capture_v1_internal")
+ def test_v1_error_normalized(self, mock_v1: MagicMock, mock_flag: MagicMock) -> None:
+ from posthog.api.capture_v1 import CaptureV1InternalError
+
+ v1_result = MagicMock()
+ v1_result.status_code = 200
+ v1_result.raise_for_status.side_effect = CaptureV1InternalError("partial failure")
+ mock_v1.return_value = v1_result
+
+ result = capture_internal_routed(**COMMON_KWARGS)
+ assert result.impl == "v1"
+ with self.assertRaises(CaptureRoutedError):
+ result.raise_for_status()
+
+ @patch("posthog.api.capture_dispatch._capture_v1_enabled", return_value=False)
+ @patch("posthog.api.capture_dispatch.capture_internal", side_effect=ConnectionError("refused"))
+ def test_legacy_transport_error_normalized(self, mock_capture: MagicMock, mock_flag: MagicMock) -> None:
+ result = capture_internal_routed(**COMMON_KWARGS)
+ assert result.impl == "legacy"
+ assert result.status_code == 0
+ with self.assertRaises(CaptureRoutedError):
+ result.raise_for_status()
+
+ def test_routing_metric_incremented(self) -> None:
+ before_legacy = CAPTURE_INTERNAL_ROUTED.labels(event_source="person_viewset", impl="legacy")._value.get()
+ with (
+ patch("posthog.api.capture_dispatch._capture_v1_enabled", return_value=False),
+ patch("posthog.api.capture_dispatch.capture_internal", return_value=_make_ok_result()),
+ ):
+ capture_internal_routed(**COMMON_KWARGS)
+ after_legacy = CAPTURE_INTERNAL_ROUTED.labels(event_source="person_viewset", impl="legacy")._value.get()
+ assert after_legacy == before_legacy + 1
+
+ def test_error_metric_incremented_on_failure(self) -> None:
+ from requests import HTTPError
+
+ before = CAPTURE_ROUTED_ERROR.labels(
+ event_source="person_viewset", impl="legacy", error_type="http"
+ )._value.get()
+ resp_mock = MagicMock()
+ resp_mock.status_code = 500
+ resp_mock.raise_for_status.side_effect = HTTPError(response=resp_mock)
+ with (
+ patch("posthog.api.capture_dispatch._capture_v1_enabled", return_value=False),
+ patch("posthog.api.capture_dispatch.capture_internal", return_value=resp_mock),
+ ):
+ capture_internal_routed(**COMMON_KWARGS)
+ after = CAPTURE_ROUTED_ERROR.labels(
+ event_source="person_viewset", impl="legacy", error_type="http"
+ )._value.get()
+ assert after == before + 1
+
+ @patch("posthog.api.capture_dispatch._capture_v1_enabled", return_value=False)
+ @patch("posthog.api.capture_dispatch.capture_internal")
+ def test_capture_internal_error_propagates_directly(self, mock_capture: MagicMock, mock_flag: MagicMock) -> None:
+ from posthog.api.capture import CaptureInternalError
+
+ mock_capture.side_effect = CaptureInternalError("bad token")
+ with self.assertRaises(CaptureInternalError):
+ capture_internal_routed(**COMMON_KWARGS)
+
+
+class TestCaptureBatchInternalRouted(SimpleTestCase):
+ BATCH_KWARGS: dict[str, Any] = {
+ "events": [{"event": "e1", "distinct_id": "u1", "properties": {}}],
+ "event_source": "get_csp_report",
+ "token": "phc_test",
+ }
+
+ @patch("posthog.api.capture_dispatch._capture_v1_enabled", return_value=False)
+ @patch("posthog.api.capture_dispatch.capture_batch_internal")
+ def test_flag_off_routes_to_legacy_batch(self, mock_batch: MagicMock, mock_flag: MagicMock) -> None:
+ future = MagicMock()
+ future.result.return_value = _make_ok_result()
+ mock_batch.return_value = [future]
+
+ result = capture_batch_internal_routed(**self.BATCH_KWARGS)
+ assert result.impl == "legacy"
+ result.raise_for_status()
+
+ @patch("posthog.api.capture_dispatch._capture_v1_enabled", return_value=True)
+ @patch("posthog.api.capture_dispatch.capture_v1_batch_internal")
+ def test_flag_on_routes_to_v1_batch(self, mock_v1: MagicMock, mock_flag: MagicMock) -> None:
+ mock_v1.return_value = _make_ok_result()
+
+ result = capture_batch_internal_routed(**self.BATCH_KWARGS)
+ assert result.impl == "v1"
+ result.raise_for_status()
+
+ @patch("posthog.api.capture_dispatch._capture_v1_enabled", return_value=False)
+ @patch("posthog.api.capture_dispatch.capture_batch_internal")
+ def test_legacy_batch_http_error(self, mock_batch: MagicMock, mock_flag: MagicMock) -> None:
+ from requests import HTTPError
+
+ resp_mock = MagicMock()
+ resp_mock.status_code = 500
+ resp_mock.raise_for_status.side_effect = HTTPError(response=resp_mock)
+ future = MagicMock()
+ future.result.return_value = resp_mock
+ mock_batch.return_value = [future]
+
+ result = capture_batch_internal_routed(**self.BATCH_KWARGS)
+ assert result.status_code == 500
+ with self.assertRaises(CaptureRoutedError):
+ result.raise_for_status()
+
+ @patch("posthog.api.capture_dispatch._capture_v1_enabled", return_value=True)
+ @patch("posthog.api.capture_dispatch.capture_v1_batch_internal")
+ def test_v1_batch_error(self, mock_v1: MagicMock, mock_flag: MagicMock) -> None:
+ from posthog.api.capture_v1 import CaptureV1InternalError
+
+ v1_result = MagicMock()
+ v1_result.raise_for_status.side_effect = CaptureV1InternalError("dropped")
+ mock_v1.return_value = v1_result
+
+ result = capture_batch_internal_routed(**self.BATCH_KWARGS)
+ assert result.impl == "v1"
+ with self.assertRaises(CaptureRoutedError):
+ result.raise_for_status()
diff --git a/posthog/api/test/test_capture_internal.py b/posthog/api/test/test_capture_internal.py
index e3463fabdd5f..97e5f9e91f22 100644
--- a/posthog/api/test/test_capture_internal.py
+++ b/posthog/api/test/test_capture_internal.py
@@ -5,7 +5,12 @@ from uuid import uuid4
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
-from posthog.api.capture import CaptureInternalError, capture_batch_internal, capture_internal
+from posthog.api.capture import (
+ CAPTURE_INTERNAL_REQUEST_FAILED,
+ CaptureInternalError,
+ capture_batch_internal,
+ capture_internal,
+)
from posthog.settings.ingestion import (
CAPTURE_INTERNAL_URL,
CAPTURE_REPLAY_INTERNAL_URL,
@@ -198,6 +203,10 @@ class TestCaptureInternal(BaseTest):
"some_custom_property": True,
}
+ before = CAPTURE_INTERNAL_REQUEST_FAILED.labels(
+ event_source="test_capture_internal_with_capture_post_server_error", status_code="503"
+ )._value.get()
+
InstallCapturePostSpy(mock_session_class, status_code=503)
response = capture_internal(
token=token,
@@ -208,7 +217,11 @@ class TestCaptureInternal(BaseTest):
properties=test_props,
)
assert response.status_code == 503
- # note: retry mechanism is disabled since we mocked requests.Session
+
+ after = CAPTURE_INTERNAL_REQUEST_FAILED.labels(
+ event_source="test_capture_internal_with_capture_post_server_error", status_code="503"
+ )._value.get()
+ assert after == before + 1
@patch("posthog.api.capture.internal_requests_session")
def test_capture_internal_replay(self, mock_session_class):
diff --git a/posthog/api/test/test_llm_prompt.py b/posthog/api/test/test_llm_prompt.py
index a9155d292524..f2e329be908e 100644
--- a/posthog/api/test/test_llm_prompt.py
+++ b/posthog/api/test/test_llm_prompt.py
@@ -783,7 +783,7 @@ class TestLLMPromptAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
@override_settings(TEST=False)
- @patch("posthog.api.llm_prompt.capture_internal")
+ @patch("posthog.api.llm_prompt.capture_internal_routed")
def test_fetch_prompt_by_name_emits_version_metadata(self, mock_capture_internal, mock_feature_enabled):
self.create_prompt_version(name="test-prompt", version=1, is_latest=False, prompt="v1")
latest = self.create_prompt_version(name="test-prompt", version=2, is_latest=True, prompt="v2")
diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.py
index 0236012f64b7..20c5a24cca40 100644
--- a/posthog/api/test/test_person.py
+++ b/posthog/api/test/test_person.py
@@ -1001,7 +1001,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.validation_error_response("required", "This field is required.", "properties"),
)
- @mock.patch("posthog.api.person.capture_internal")
+ @mock.patch("posthog.api.person.capture_internal_routed")
def test_new_update_single_person_property(self, mock_capture) -> None:
person = _create_person(
team=self.team,
@@ -1024,7 +1024,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
process_person_profile=True,
)
- @mock.patch("posthog.api.person.capture_internal")
+ @mock.patch("posthog.api.person.capture_internal_routed")
def test_new_delete_person_properties(self, mock_capture) -> None:
person = _create_person(
team=self.team,
@@ -1047,7 +1047,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
process_person_profile=True,
)
- @mock.patch("posthog.api.person.capture_internal")
+ @mock.patch("posthog.api.person.capture_internal_routed")
def test_update_person_property_by_numeric_id(self, mock_capture) -> None:
person = _create_person(
team=self.team,
@@ -1070,7 +1070,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
process_person_profile=True,
)
- @mock.patch("posthog.api.person.capture_internal")
+ @mock.patch("posthog.api.person.capture_internal_routed")
def test_delete_person_property_by_numeric_id(self, mock_capture) -> None:
person = _create_person(
team=self.team,
@@ -1093,7 +1093,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
process_person_profile=True,
)
- @mock.patch("posthog.api.person.capture_internal")
+ @mock.patch("posthog.api.person.capture_internal_routed")
def test_update_person_property_with_null_value(self, mock_capture) -> None:
person = _create_person(
team=self.team,
diff --git a/posthog/api/test/test_person_personhog.py b/posthog/api/test/test_person_personhog.py
index a5024c8d111c..691eec7eceb1 100644
--- a/posthog/api/test/test_person_personhog.py
+++ b/posthog/api/test/test_person_personhog.py
@@ -78,7 +78,7 @@ class TestRetrievePerson(PersonhogTestMixin, APIBaseTest):
@parameterized_class(("personhog",), [(False,), (True,)])
class TestUpdatePerson(PersonhogTestMixin, APIBaseTest):
- @mock.patch("posthog.api.person.capture_internal")
+ @mock.patch("posthog.api.person.capture_internal_routed")
def test_update_properties_by_uuid(self, mock_capture):
mock_capture.return_value = mock.MagicMock(status_code=200)
person = self._seed_person(
@@ -100,7 +100,7 @@ class TestUpdatePerson(PersonhogTestMixin, APIBaseTest):
assert call_kwargs["properties"] == {"$set": {"new_key": "new_value"}}
self._assert_personhog_called("get_person_by_uuid")
- @mock.patch("posthog.api.person.capture_internal")
+ @mock.patch("posthog.api.person.capture_internal_routed")
def test_update_properties_by_pk(self, mock_capture):
mock_capture.return_value = mock.MagicMock(status_code=200)
person = self._seed_person(
@@ -184,7 +184,7 @@ class TestCohortsByPerson(PersonhogTestMixin, APIBaseTest):
@parameterized_class(("personhog",), [(False,), (True,)])
class TestDeleteProperty(PersonhogTestMixin, APIBaseTest):
- @mock.patch("posthog.api.person.capture_internal")
+ @mock.patch("posthog.api.person.capture_internal_routed")
def test_uuid_lookup(self, mock_capture):
mock_capture.return_value = mock.MagicMock(status_code=200)
person = self._seed_person(
@@ -211,7 +211,7 @@ class TestDeleteProperty(PersonhogTestMixin, APIBaseTest):
self._assert_personhog_called("get_person_by_uuid")
self._assert_personhog_called("get_distinct_ids_for_person")
- @mock.patch("posthog.api.person.capture_internal")
+ @mock.patch("posthog.api.person.capture_internal_routed")
def test_integer_pk_lookup(self, mock_capture):
mock_capture.return_value = mock.MagicMock(status_code=200)
person = self._seed_person(
diff --git a/posthog/api/test/test_report.py b/posthog/api/test/test_report.py
index 952d664d2d0e..98486b3c1c34 100644
--- a/posthog/api/test/test_report.py
+++ b/posthog/api/test/test_report.py
@@ -20,7 +20,7 @@ class TestCspReport(BaseTest):
# it is really important to know that /capture is CSRF exempt. Enforce checking in the client
self.client = Client(enforce_csrf_checks=True)
- @patch("posthog.api.report.capture_internal")
+ @patch("posthog.api.report.capture_internal_routed")
def test_submit_csp_report_to_new_internal_capture(self, mock_capture) -> None:
payload = {
"csp-report": {
@@ -43,9 +43,9 @@ class TestCspReport(BaseTest):
assert resp.status_code == status.HTTP_204_NO_CONTENT
assert mock_capture.call_count == 1
- @patch("posthog.api.capture.capture_internal")
- def test_submit_csp_report_list_to_new_internal_capture(self, mock_capture) -> None:
- mock_capture.return_value = MagicMock(status_code=204)
+ @patch("posthog.api.report.capture_batch_internal_routed")
+ def test_submit_csp_report_list_to_new_internal_capture(self, mock_batch_capture) -> None:
+ mock_batch_capture.return_value = MagicMock(raise_for_status=MagicMock())
multiple_violations = [
{
@@ -100,9 +100,10 @@ class TestCspReport(BaseTest):
content_type="application/reports+json",
)
assert resp.status_code == status.HTTP_204_NO_CONTENT
- assert mock_capture.call_count == 3
+ mock_batch_capture.assert_called_once()
+ assert len(mock_batch_capture.call_args.kwargs["events"]) == 3
- @patch("posthog.api.report.capture_internal")
+ @patch("posthog.api.report.capture_internal_routed")
def test_capture_csp_violation(self, mock_capture):
mock_capture.return_value = MagicMock(status_code=204)
@@ -131,7 +132,7 @@ class TestCspReport(BaseTest):
assert status.HTTP_204_NO_CONTENT == response.status_code
assert mock_capture.call_count == 1
- @patch("posthog.api.report.capture_internal")
+ @patch("posthog.api.report.capture_internal_routed")
def test_capture_csp_no_trailing_slash(self, mock_capture):
mock_capture.return_value = MagicMock(status_code=204)
@@ -230,9 +231,9 @@ class TestCspReport(BaseTest):
assert response.json()["code"] == "invalid_payload"
assert "Failed to submit CSP report" in response.json()["detail"]
- @patch("posthog.api.capture.capture_internal")
+ @patch("posthog.api.report.capture_batch_internal_routed")
def test_integration_csp_report_with_report_to_format_returns_204(self, mock_capture):
- mock_capture.return_value = MagicMock(status_code=204, content=b"")
+ mock_capture.return_value = MagicMock(raise_for_status=MagicMock())
report_to_format = [
{
@@ -261,9 +262,9 @@ class TestCspReport(BaseTest):
assert response.content == b""
mock_capture.assert_called_once()
- @patch("posthog.api.capture.capture_internal")
+ @patch("posthog.api.report.capture_batch_internal_routed")
def test_capture_csp_report_to_violation(self, mock_capture):
- mock_capture.return_value = MagicMock(status_code=204)
+ mock_capture.return_value = MagicMock(raise_for_status=MagicMock())
report_to_format = [
{
@@ -312,10 +313,11 @@ class TestCspReport(BaseTest):
content_type="application/reports+json",
)
assert status.HTTP_204_NO_CONTENT == response.status_code
- # Verify we processed both events
- assert mock_capture.call_count == 2
+ # Both events go through a single batched dispatch call
+ mock_capture.assert_called_once()
+ assert len(mock_capture.call_args.kwargs["events"]) == 2
- @patch("posthog.api.report.capture_internal")
+ @patch("posthog.api.report.capture_internal_routed")
@patch("posthog.api.report.logger")
def test_csp_debug_logging_enabled(self, mock_logger, mock_capture):
mock_capture.return_value = MagicMock(status_code=204)
@@ -345,7 +347,7 @@ class TestCspReport(BaseTest):
assert call_args[1]["content_type"] == "application/csp-report"
assert "body" in call_args[1]
- @patch("posthog.api.report.capture_internal")
+ @patch("posthog.api.report.capture_internal_routed")
@patch("posthog.api.report.logger")
def test_csp_debug_logging_disabled(self, mock_logger, mock_capture):
mock_capture.return_value = MagicMock(status_code=204)
@@ -367,7 +369,7 @@ class TestCspReport(BaseTest):
mock_capture.assert_called_once()
mock_logger.exception.assert_not_called()
- @patch("posthog.api.report.capture_internal")
+ @patch("posthog.api.report.capture_internal_routed")
@patch("posthog.api.report.logger")
def test_csp_debug_logging_case_insensitive(self, mock_logger, mock_capture):
mock_capture.return_value = MagicMock(status_code=204)
@@ -439,7 +441,7 @@ class TestCspReport(BaseTest):
assert response.status_code == status.HTTP_204_NO_CONTENT
- @patch("posthog.api.report.capture_internal")
+ @patch("posthog.api.report.capture_internal_routed")
def test_safari_single_csp_violation_with_csp_report_content_type(self, mock_capture):
mock_capture.return_value = MagicMock(status_code=204)
diff --git a/posthog/temporal/ai_observability/run_evaluation.py b/posthog/temporal/ai_observability/run_evaluation.py
index 4080bf8313cb..5bd927e2b877 100644
--- a/posthog/temporal/ai_observability/run_evaluation.py
+++ b/posthog/temporal/ai_observability/run_evaluation.py
@@ -15,7 +15,7 @@ from structlog.contextvars import bind_contextvars
from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
from temporalio.exceptions import ApplicationError
-from posthog.api.capture import capture_internal
+from posthog.api.capture_dispatch import capture_internal_routed
from posthog.models.team import Team
from posthog.sync import database_sync_to_async
from posthog.temporal.ai_observability.message_utils import extract_text_from_messages, format_tool_definitions
@@ -1065,7 +1065,7 @@ async def emit_evaluation_event_activity(inputs: EmitEvaluationEventInputs) -> N
event_timestamp = datetime.now(UTC)
- resp = capture_internal(
+ capture_result = capture_internal_routed(
token=team.api_token,
event_name="$ai_evaluation",
event_source="llm_analytics_evaluation",
@@ -1074,7 +1074,7 @@ async def emit_evaluation_event_activity(inputs: EmitEvaluationEventInputs) -> N
properties=properties,
process_person_profile=True,
)
- resp.raise_for_status()
+ capture_result.raise_for_status()
try:
await database_sync_to_async(_emit, thread_sensitive=False)()
diff --git a/posthog/temporal/ai_observability/run_tagger.py b/posthog/temporal/ai_observability/run_tagger.py
index 6668df7ec0c8..650f47000908 100644
--- a/posthog/temporal/ai_observability/run_tagger.py
+++ b/posthog/temporal/ai_observability/run_tagger.py
@@ -10,7 +10,7 @@ from structlog.contextvars import bind_contextvars
from temporalio.common import RetryPolicy
from temporalio.exceptions import ApplicationError
-from posthog.api.capture import capture_internal
+from posthog.api.capture_dispatch import capture_internal_routed
from posthog.models.team import Team
from posthog.sync import database_sync_to_async
from posthog.temporal.ai_observability.message_utils import extract_text_from_messages
@@ -569,7 +569,7 @@ async def emit_tagger_event_activity(inputs: EmitTaggerEventInputs) -> None:
event_timestamp = datetime.now(UTC)
- resp = capture_internal(
+ routed_result = capture_internal_routed(
token=team.api_token,
event_name="$ai_tag",
event_source="llm_analytics_tagger",
@@ -578,7 +578,7 @@ async def emit_tagger_event_activity(inputs: EmitTaggerEventInputs) -> None:
properties=properties,
process_person_profile=True,
)
- resp.raise_for_status()
+ routed_result.raise_for_status()
await database_sync_to_async(_emit, thread_sensitive=False)()
diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.py
index 7e43efef8d65..90b2f2c69ccd 100644
--- a/posthog/temporal/ai_observability/test_run_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_evaluation.py
@@ -170,7 +170,7 @@ class TestRunEvaluationWorkflow:
}
with patch("posthog.temporal.ai_observability.run_evaluation.Team.objects.get") as mock_team_get:
- with patch("posthog.temporal.ai_observability.run_evaluation.capture_internal") as mock_capture:
+ with patch("posthog.temporal.ai_observability.run_evaluation.capture_internal_routed") as mock_capture:
mock_team_get.return_value = team
mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())
@@ -227,7 +227,7 @@ class TestRunEvaluationWorkflow:
}
with patch("posthog.temporal.ai_observability.run_evaluation.Team.objects.get") as mock_team_get:
- with patch("posthog.temporal.ai_observability.run_evaluation.capture_internal") as mock_capture:
+ with patch("posthog.temporal.ai_observability.run_evaluation.capture_internal_routed") as mock_capture:
mock_team_get.return_value = team
mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())
@@ -511,7 +511,7 @@ class TestRunEvaluationWorkflow:
}
with patch("posthog.temporal.ai_observability.run_evaluation.Team.objects.get") as mock_team_get:
- with patch("posthog.temporal.ai_observability.run_evaluation.capture_internal") as mock_capture:
+ with patch("posthog.temporal.ai_observability.run_evaluation.capture_internal_routed") as mock_capture:
mock_team_get.return_value = team
mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())
@@ -552,7 +552,7 @@ class TestRunEvaluationWorkflow:
}
with patch("posthog.temporal.ai_observability.run_evaluation.Team.objects.get") as mock_team_get:
- with patch("posthog.temporal.ai_observability.run_evaluation.capture_internal") as mock_capture:
+ with patch("posthog.temporal.ai_observability.run_evaluation.capture_internal_routed") as mock_capture:
mock_team_get.return_value = team
mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())
diff --git a/posthog/temporal/ai_observability/test_run_tagger.py b/posthog/temporal/ai_observability/test_run_tagger.py
index 099966549349..0cec4c0271d8 100644
--- a/posthog/temporal/ai_observability/test_run_tagger.py
+++ b/posthog/temporal/ai_observability/test_run_tagger.py
@@ -380,7 +380,7 @@ class TestRunTaggerWorkflow:
event_data = create_mock_event_data(team.id, properties={})
with patch("posthog.temporal.ai_observability.run_tagger.Team.objects.get") as mock_team_get:
- with patch("posthog.temporal.ai_observability.run_tagger.capture_internal") as mock_capture:
+ with patch("posthog.temporal.ai_observability.run_tagger.capture_internal_routed") as mock_capture:
mock_team_get.return_value = team
mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())
diff --git a/posthog/temporal/session_replay/session_summary/event_capture.py b/posthog/temporal/session_replay/session_summary/event_capture.py
index b47d03b62b24..892f39c24660 100644
--- a/posthog/temporal/session_replay/session_summary/event_capture.py
+++ b/posthog/temporal/session_replay/session_summary/event_capture.py
@@ -2,7 +2,7 @@ from django.conf import settings
import structlog
-from posthog.api.capture import capture_internal
+from posthog.api.capture_dispatch import capture_internal_routed
from posthog.temporal.session_replay.session_summary.types.events import SessionSummaryReadyProperties
from products.replay.backend.models.session_summaries import SingleSessionSummary
@@ -36,7 +36,7 @@ def capture_session_summary_ready(
session_duration=summary.session_duration,
)
try:
- response = capture_internal(
+ result = capture_internal_routed(
token=team_api_token,
event_name="$session_summary_ready",
event_source=EVENT_SOURCE,
@@ -44,7 +44,7 @@ def capture_session_summary_ready(
timestamp=summary.created_at,
properties=properties.model_dump(by_alias=True, mode="json"),
)
- response.raise_for_status()
+ result.raise_for_status()
except Exception:
logger.exception(
"failed_to_capture_session_summary_ready",
diff --git a/posthog/temporal/tests/session_replay/session_summary/test_event_capture.py b/posthog/temporal/tests/session_replay/session_summary/test_event_capture.py
index 0b6af70973d7..73ce2eb6a7f6 100644
--- a/posthog/temporal/tests/session_replay/session_summary/test_event_capture.py
+++ b/posthog/temporal/tests/session_replay/session_summary/test_event_capture.py
@@ -2,8 +2,8 @@ import pytest
from unittest.mock import MagicMock
from pytest_mock import MockerFixture
-from requests import HTTPError, Response
+from posthog.api.capture_dispatch import CaptureRoutedError
from posthog.sync import database_sync_to_async
from posthog.temporal.session_replay.session_summary.activities.video_based.a7c_store_video_session_summary import (
store_video_session_summary_activity,
@@ -44,17 +44,17 @@ def test_capture_session_summary_ready_emits_internal_project_event(
created_by=user,
)
settings.SITE_URL = "http://localhost:8000"
- response = mocker.MagicMock()
- capture_internal = mocker.patch(
- "posthog.temporal.session_replay.session_summary.event_capture.capture_internal", return_value=response
+ result = mocker.MagicMock()
+ capture_internal_routed = mocker.patch(
+ "posthog.temporal.session_replay.session_summary.event_capture.capture_internal_routed", return_value=result
)
from posthog.temporal.session_replay.session_summary.event_capture import capture_session_summary_ready
capture_session_summary_ready(summary, team_api_token="token-override")
- capture_internal.assert_called_once()
- _, kwargs = capture_internal.call_args
+ capture_internal_routed.assert_called_once()
+ _, kwargs = capture_internal_routed.call_args
assert kwargs["token"] == "token-override"
assert kwargs["event_name"] == "$session_summary_ready"
assert kwargs["event_source"] == "session_summary_events"
@@ -70,7 +70,7 @@ def test_capture_session_summary_ready_emits_internal_project_event(
assert kwargs["properties"]["model_used"] == "gpt-test"
assert kwargs["properties"]["session_start_time"] is None
assert kwargs["properties"]["session_duration"] is None
- response.raise_for_status.assert_called_once()
+ result.raise_for_status.assert_called_once()
def test_capture_session_summary_ready_swallow_capture_errors(
@@ -87,10 +87,10 @@ def test_capture_session_summary_ready_swallow_capture_errors(
distinct_id="customer-456",
created_by=user,
)
- response = mocker.MagicMock()
- response.raise_for_status.side_effect = HTTPError("boom", response=Response())
+ result = mocker.MagicMock()
+ result.raise_for_status.side_effect = CaptureRoutedError("boom", status_code=500)
mocker.patch(
- "posthog.temporal.session_replay.session_summary.event_capture.capture_internal", return_value=response
+ "posthog.temporal.session_replay.session_summary.event_capture.capture_internal_routed", return_value=result
)
logger = mocker.patch("posthog.temporal.session_replay.session_summary.event_capture.logger")
diff --git a/products/conversations/backend/api/tests/test_events.py b/products/conversations/backend/api/tests/test_events.py
index 1ee1cf2af319..0dbe9da53a1b 100644
--- a/products/conversations/backend/api/tests/test_events.py
+++ b/products/conversations/backend/api/tests/test_events.py
@@ -34,7 +34,7 @@ class TestConversationEvents(BaseTest):
anonymous_traits={"name": "Test Customer", "email": "[email protected]"},
)
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
def test_capture_ticket_created_uses_team_token(self, mock_capture):
capture_ticket_created(self.ticket)
@@ -48,7 +48,7 @@ class TestConversationEvents(BaseTest):
assert call_kwargs["properties"]["customer_name"] == "Test Customer"
assert call_kwargs["properties"]["customer_email"] == "[email protected]"
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
def test_capture_ticket_status_changed_uses_team_token(self, mock_capture):
capture_ticket_status_changed(self.ticket, "new", "pending")
@@ -61,7 +61,7 @@ class TestConversationEvents(BaseTest):
assert call_kwargs["properties"]["old_status"] == "new"
assert call_kwargs["properties"]["new_status"] == "pending"
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
def test_capture_ticket_priority_changed_uses_team_token(self, mock_capture):
capture_ticket_priority_changed(self.ticket, None, "high")
@@ -74,7 +74,7 @@ class TestConversationEvents(BaseTest):
assert call_kwargs["properties"]["old_priority"] is None
assert call_kwargs["properties"]["new_priority"] == "high"
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
def test_capture_ticket_assigned_uses_team_token(self, mock_capture):
capture_ticket_assigned(self.ticket, "user", "123")
@@ -87,7 +87,7 @@ class TestConversationEvents(BaseTest):
assert call_kwargs["properties"]["assignee_type"] == "user"
assert call_kwargs["properties"]["assignee_id"] == "123"
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
def test_capture_message_sent_uses_team_token(self, mock_capture):
capture_message_sent(self.ticket, "msg-123", "Hello customer", 42)
@@ -102,7 +102,7 @@ class TestConversationEvents(BaseTest):
assert call_kwargs["properties"]["author_type"] == "team"
assert call_kwargs["properties"]["author_id"] == 42
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
def test_capture_message_received_uses_team_token(self, mock_capture):
capture_message_received(self.ticket, "msg-456", "Hello support")
@@ -143,7 +143,7 @@ class TestConversationEvents(BaseTest):
),
]
)
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
def test_all_events_include_base_properties(self, _name, capture_fn, expected_event, extra_args, mock_capture):
capture_fn(self.ticket, *extra_args)
@@ -157,7 +157,7 @@ class TestConversationEvents(BaseTest):
assert props["status"] == self.ticket.status
assert props["priority"] == self.ticket.priority
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
def test_message_content_truncated_to_1000_chars(self, mock_capture):
long_content = "x" * 1500
capture_message_sent(self.ticket, "msg-id", long_content, 1)
@@ -165,7 +165,7 @@ class TestConversationEvents(BaseTest):
call_kwargs = mock_capture.call_args.kwargs
assert len(call_kwargs["properties"]["message_content"]) == 1000
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
def test_event_uses_ticket_team_token_not_other_team(self, mock_capture):
"""Verify events route to the ticket's team, not any other team."""
from posthog.models import Organization, Team
@@ -181,7 +181,7 @@ class TestConversationEvents(BaseTest):
assert call_kwargs["token"] == self.team.api_token
assert call_kwargs["token"] != other_team.api_token
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
def test_two_teams_events_routed_to_respective_projects(self, mock_capture):
"""Events from Team 1 ticket use Team 1 token, Team 2 ticket uses Team 2 token."""
from posthog.models import Organization, Team
@@ -223,7 +223,7 @@ class TestConversationEvents(BaseTest):
("empty_distinct_id", False, False, False),
]
)
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
@patch("products.conversations.backend.events.get_persons_by_distinct_ids")
def test_capture_ticket_created_person_processing(
self, _name, has_person, is_identified, expect_groups, mock_get_persons, mock_capture
@@ -256,7 +256,7 @@ class TestConversationEvents(BaseTest):
assert call_kwargs["process_person_profile"] is expect_groups
assert "$groups" not in call_kwargs["properties"]
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
@patch("products.conversations.backend.events.get_persons_by_distinct_ids")
def test_capture_ticket_created_groups_from_person_org(self, mock_get_persons, mock_capture):
from posthog.models.person.person import Person
@@ -276,7 +276,7 @@ class TestConversationEvents(BaseTest):
assert groups["project"] == str(self.team.uuid)
assert "instance" in groups
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
@patch("products.conversations.backend.events.get_persons_by_distinct_ids")
def test_capture_message_received_groups_from_person_org(self, mock_get_persons, mock_capture):
from posthog.models.person.person import Person
@@ -303,7 +303,7 @@ class TestConversationEvents(BaseTest):
("empty_distinct_id", False, False),
]
)
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
@patch("products.conversations.backend.events.get_persons_by_distinct_ids")
def test_capture_message_received_person_processing(
self, _name, has_person, is_identified, mock_get_persons, mock_capture
@@ -336,7 +336,7 @@ class TestConversationEvents(BaseTest):
assert call_kwargs["process_person_profile"] is False
assert "$groups" not in call_kwargs["properties"]
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
@patch("products.conversations.backend.events.get_persons_by_distinct_ids", side_effect=Exception("db timeout"))
def test_capture_message_received_still_fires_on_person_lookup_failure(self, mock_get_persons, mock_capture):
capture_message_received(self.ticket, "msg-456", "Hello support")
@@ -352,7 +352,7 @@ class TestConversationEvents(BaseTest):
("user_has_no_membership", True, False),
]
)
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
@patch("products.conversations.backend.events.get_persons_by_distinct_ids")
def test_capture_ticket_created_no_groups_when(
self, _name, create_user, create_membership, mock_get_persons, mock_capture
@@ -370,7 +370,7 @@ class TestConversationEvents(BaseTest):
assert call_kwargs["process_person_profile"] is False
assert "$groups" not in call_kwargs["properties"]
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
@patch("products.conversations.backend.events.get_persons_by_distinct_ids", side_effect=Exception("db timeout"))
def test_capture_ticket_created_still_fires_on_person_lookup_failure(self, mock_get_persons, mock_capture):
capture_ticket_created(self.ticket)
@@ -389,7 +389,7 @@ class TestConversationEvents(BaseTest):
("email_from_only", "email", None, "[email protected]"),
]
)
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
@patch("products.conversations.backend.events._get_persons_by_email")
@patch("products.conversations.backend.events.get_persons_by_distinct_ids")
def test_capture_ticket_created_email_fallback_groups(
@@ -438,7 +438,7 @@ class TestConversationEvents(BaseTest):
("person_without_membership", True),
]
)
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
@patch("products.conversations.backend.events._get_persons_by_email")
@patch("products.conversations.backend.events.get_persons_by_distinct_ids")
def test_capture_ticket_created_email_fallback_no_groups(
@@ -472,7 +472,7 @@ class TestConversationEvents(BaseTest):
assert call_kwargs["process_person_profile"] is False
assert "$groups" not in call_kwargs["properties"]
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
@patch("products.conversations.backend.events._get_persons_by_email")
@patch("products.conversations.backend.events.get_persons_by_distinct_ids")
def test_capture_ticket_created_identified_person_without_membership_skips_email_fallback(
@@ -498,7 +498,7 @@ class TestConversationEvents(BaseTest):
("github_no_email", "github"),
]
)
- @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.capture_internal_routed")
@patch("products.conversations.backend.events._get_persons_by_email")
@patch("products.conversations.backend.events.get_persons_by_distinct_ids")
def test_capture_ticket_created_non_verified_channels_skip_email_fallback(
diff --git a/products/conversations/backend/events.py b/products/conversations/backend/events.py
index c22452427b48..8cc1c4a855ea 100644
--- a/products/conversations/backend/events.py
+++ b/products/conversations/backend/events.py
@@ -8,7 +8,7 @@ Events are sent to the customer's PostHog project via their team's API token.
import structlog
-from posthog.api.capture import capture_internal
+from posthog.api.capture_dispatch import capture_internal_routed
from posthog.event_usage import groups as build_groups
from posthog.models.organization import OrganizationMembership
from posthog.models.person.util import get_persons_by_distinct_ids
@@ -101,7 +101,7 @@ def capture_ticket_created(ticket: Ticket) -> None:
except Exception:
logger.exception("ticket_created_person_lookup_failed", team_id=team_id, ticket_id=str(ticket.id))
- capture_internal(
+ capture_internal_routed(
token=team.api_token,
event_name="$conversation_ticket_created",
event_source=EVENT_SOURCE,
@@ -117,7 +117,7 @@ def capture_ticket_status_changed(ticket: Ticket, old_status: str, new_status: s
properties["old_status"] = old_status
properties["new_status"] = new_status
- capture_internal(
+ capture_internal_routed(
token=ticket.team.api_token,
event_name="$conversation_ticket_status_changed",
event_source=EVENT_SOURCE,
@@ -132,7 +132,7 @@ def capture_ticket_priority_changed(ticket: Ticket, old_priority: str | None, ne
properties["old_priority"] = old_priority
properties["new_priority"] = new_priority
- capture_internal(
+ capture_internal_routed(
token=ticket.team.api_token,
event_name="$conversation_ticket_priority_changed",
event_source=EVENT_SOURCE,
@@ -147,7 +147,7 @@ def capture_ticket_assigned(ticket: Ticket, assignee_type: str | None, assignee_
properties["assignee_type"] = assignee_type
properties["assignee_id"] = assignee_id
- capture_internal(
+ capture_internal_routed(
token=ticket.team.api_token,
event_name="$conversation_ticket_assigned",
event_source=EVENT_SOURCE,
@@ -165,7 +165,7 @@ def capture_message_sent(ticket: Ticket, message_id: str, message_content: str,
properties["author_type"] = "team"
properties["author_id"] = author_id
- capture_internal(
+ capture_internal_routed(
token=ticket.team.api_token,
event_name="$conversation_message_sent",
event_source=EVENT_SOURCE,
@@ -194,7 +194,7 @@ def capture_message_received(ticket: Ticket, message_id: str, message_content: s
except Exception:
logger.exception("message_received_person_lookup_failed", team_id=team.id, ticket_id=str(ticket.id))
- capture_internal(
+ capture_internal_routed(
token=team.api_token,
event_name="$conversation_message_received",
event_source=EVENT_SOURCE,
diff --git a/products/replay_vision/backend/temporal/activities/emit_observation_event.py b/products/replay_vision/backend/temporal/activities/emit_observation_event.py
index 8f86290aa42d..17b99602fc78 100644
--- a/products/replay_vision/backend/temporal/activities/emit_observation_event.py
+++ b/products/replay_vision/backend/temporal/activities/emit_observation_event.py
@@ -5,7 +5,7 @@ from datetime import UTC, datetime
import structlog
from temporalio import activity
-from posthog.api.capture import capture_internal
+from posthog.api.capture_dispatch import capture_internal_routed
from posthog.models.team import Team
from posthog.sync import database_sync_to_async
@@ -65,7 +65,7 @@ def _emit_event(inputs: EmitObservationEventInputs) -> None:
else replay_vision_distinct_id(observation.team_id)
)
- response = capture_internal(
+ result = capture_internal_routed(
token=team.api_token,
event_name=_EVENT_NAME,
event_source=_EVENT_SOURCE,
@@ -76,4 +76,4 @@ def _emit_event(inputs: EmitObservationEventInputs) -> None:
# Make the captured event UUID equal to observation.id so the admin UI can link back to it directly.
event_uuid=str(observation.id),
)
- response.raise_for_status()
+ result.raise_for_status()