: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
refactor(capture): complete capture_internal v0->v1 cutover (#65273)
Eli Reismanc8917c2b6992
diff --git a/ee/clickhouse/views/groups.py b/ee/clickhouse/views/groups.pyindex 4b4133454edd..cfd54c5397eb 100644--- a/ee/clickhouse/views/groups.py+++ b/ee/clickhouse/views/groups.py@@ -18,7 +18,7 @@ from rest_framework.exceptions import NotFound, ValidationErrorfrom posthog.schema import ProductKey-from posthog.api.capture_dispatch import CaptureRoutedError, capture_internal_routed+from posthog.api.capture import CaptureInternalError, capture_internalfrom posthog.api.documentation import extend_schemafrom posthog.api.property_value_metrics import PROPERTY_VALUES_DURATIONfrom posthog.api.routing import TeamAndOrgViewSetMixin@@ -324,7 +324,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create"$group_set": group_properties or group.group_properties,}try:- result = capture_internal_routed(+ result = capture_internal(token=self.team.api_token,event_name="$groupidentify",event_source="ee_ch_views_groups",@@ -334,7 +334,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Createprocess_person_profile=False,)result.raise_for_status()- except CaptureRoutedError as error:+ except CaptureInternalError as error:raise TriggerGroupIdentifyException(exception_data={"code": f"Failed to submit {operation} event.",@@ -682,7 +682,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create}try:- routed_result = capture_internal_routed(+ routed_result = capture_internal(token=self.team.api_token,event_name=event_name,event_source="ee_ch_views_groups",@@ -693,7 +693,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create)routed_result.raise_for_status()- except CaptureRoutedError as e:+ except CaptureInternalError as e:return response.Response({"attr": "$unset",diff --git a/ee/clickhouse/views/test/test_clickhouse_groups.py b/ee/clickhouse/views/test/test_clickhouse_groups.pyindex bbebc69ca459..4e0cc8d7afda 100644--- a/ee/clickhouse/views/test/test_clickhouse_groups.py+++ b/ee/clickhouse/views/test/test_clickhouse_groups.py@@ -328,7 +328,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_routed")+ @mock.patch("ee.clickhouse.views.groups.capture_internal")def test_create_group_missing_group_properties(self, mock_capture):group_type_mapping = create_group_type_mapping_without_created_at(team=self.team,@@ -360,7 +360,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):mock_capture.assert_called_once()@freeze_time("2021-05-02")- @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")+ @mock.patch("ee.clickhouse.views.groups.capture_internal")@pytest.mark.flaky(reruns=2)def test_create_group(self, mock_capture):group_type_mapping = create_group_type_mapping_without_created_at(@@ -448,7 +448,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_routed")+ @mock.patch("ee.clickhouse.views.groups.capture_internal")def test_create_group_duplicated_group_key(self, mock_capture):group_type_mapping = create_group_type_mapping_without_created_at(team=self.team,@@ -485,7 +485,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):)mock_capture.assert_not_called()- @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")+ @mock.patch("ee.clickhouse.views.groups.capture_internal")def test_create_group_missing_group_key(self, mock_capture):group_type_mapping = create_group_type_mapping_without_created_at(team=self.team,@@ -515,7 +515,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):)mock_capture.assert_not_called()- @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")+ @mock.patch("ee.clickhouse.views.groups.capture_internal")def test_create_group_missing_group_type_index(self, mock_capture):response = self.client.post(f"/api/projects/{self.team.id}/groups",@@ -539,7 +539,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):mock_capture.assert_not_called()@freeze_time("2021-05-02")- @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")+ @mock.patch("ee.clickhouse.views.groups.capture_internal")@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(@@ -624,7 +624,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_routed")+ @mock.patch("ee.clickhouse.views.groups.capture_internal")@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(@@ -748,7 +748,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, 404)@freeze_time("2021-05-02")- @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")+ @mock.patch("ee.clickhouse.views.groups.capture_internal")@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(@@ -883,7 +883,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, 400)@freeze_time("2021-05-02")- @patch("ee.clickhouse.views.groups.capture_internal_routed")+ @patch("ee.clickhouse.views.groups.capture_internal")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(@@ -928,7 +928,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, 400)@freeze_time("2021-05-02")- @patch("ee.clickhouse.views.groups.capture_internal_routed")+ @patch("ee.clickhouse.views.groups.capture_internal")def test_get_group_activities_success(self, mock_capture):# Mock the response to return a 200 OKmock_capture.return_value = mock.MagicMock(status_code=200)@@ -968,7 +968,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_routed")+ @patch("ee.clickhouse.views.groups.capture_internal")def test_get_group_activities_invalid_group(self, mock_capture):# Mock the response to return a 200 OKmock_capture.return_value = mock.MagicMock(status_code=200)@@ -2201,7 +2201,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_routed")+ @mock.patch("ee.clickhouse.views.groups.capture_internal")def test_create_group_creates_property_definitions(self, mock_capture):data = {"group_type_index": self.group_type_index,@@ -2235,7 +2235,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_routed")+ @mock.patch("ee.clickhouse.views.groups.capture_internal")def test_update_property_creates_property_definition(self, mock_capture):create_group(team_id=self.team.pk,@@ -2265,7 +2265,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_routed")+ @mock.patch("ee.clickhouse.views.groups.capture_internal")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={}@@ -2302,7 +2302,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_routed")+ @mock.patch("ee.clickhouse.views.groups.capture_internal")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={}@@ -2330,7 +2330,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_routed")+ @mock.patch("ee.clickhouse.views.groups.capture_internal")def test_update_property_missing_key(self, mock_capture):mock_capture.return_value = mock.MagicMock(status_code=200)create_group(@@ -2344,7 +2344,7 @@ class GroupPropertyDefinitionsTestCase(ClickhouseTestMixin, APIBaseTest):)self.assertEqual(response.status_code, 400)- @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")+ @mock.patch("ee.clickhouse.views.groups.capture_internal")def test_update_property_empty_key(self, mock_capture):mock_capture.return_value = mock.MagicMock(status_code=200)create_group(@@ -2358,7 +2358,7 @@ class GroupPropertyDefinitionsTestCase(ClickhouseTestMixin, APIBaseTest):)self.assertEqual(response.status_code, 400)- @mock.patch("ee.clickhouse.views.groups.capture_internal_routed")+ @mock.patch("ee.clickhouse.views.groups.capture_internal")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.pyindex 3df61ac4d63e..9b22ccdc75bd 100644--- a/posthog/api/capture.py+++ b/posthog/api/capture.py@@ -1,255 +1,828 @@-from concurrent.futures import Future, ThreadPoolExecutor+"""capture_internal — batch-native client for the v1 analytics capture endpoint.++This module provides the PREFERRED method for publishing analytics events from the Django+app on behalf of customer teams/projects. PLEASE DO NOT write events directly to+ingestion Kafka topics — USE THIS! The capture-rs pipeline handles deduplication,+quotas, billing, and routing; bypassing it creates safety and correctness problems.++NOTE: This is for submitting events ON BEHALF OF A CUSTOMER TEAM. It is NOT for+submitting SDK-style internal telemetry events for PostHog's own team (team 2) — the+posthoganalytics SDK integration handles that separately.++Session replay events ($snapshot, $performance_event, $snapshot_items) are NOT SUPPORTED.+They are rejected client-side with CaptureInternalError. Real replay ingestion flows+through SDKs directly to the capture-rs /s/ endpoint.++Targets ``/i/v1/analytics/events`` (capture-rs v1). Typed ``event.options`` replaces+the legacy property-stuffing pattern, and legacy ``$``-keys are defensively stripped so+capture-rs's blind property splicing never produces duplicate keys.+"""++from __future__ import annotations++import time+from concurrent.futures import ThreadPoolExecutor, as_completed+from dataclasses import dataclass, fieldfrom datetime import UTC, datetimefrom typing import Any, Optional+from uuid import uuid4import structlogfrom prometheus_client import Counter-from requests import Responsefrom requests.adapters import HTTPAdapter, Retryfrom requests.exceptions import RequestException-from posthog.logging.timing import timedfrom posthog.security.outbound_proxy import internal_requests_sessionfrom posthog.settings.ingestion import (+ CAPTURE_INTERNAL_BATCH_CHUNK_SIZE,CAPTURE_INTERNAL_MAX_WORKERS,CAPTURE_INTERNAL_URL,- CAPTURE_REPLAY_INTERNAL_URL,- NEW_ANALYTICS_CAPTURE_ENDPOINT,- REPLAY_CAPTURE_ENDPOINT,+ CAPTURE_V1_INTERNAL_ENDPOINT,+ CAPTURE_V1_INTERNAL_MAX_ATTEMPTS,+ CAPTURE_V1_INTERNAL_RETRY_AFTER_CAP_SECONDS,)logger = structlog.get_logger(__name__)-# These event names are reserved for internal use and refer to non-analytics-# events that are ingested via a separate path than analytics events. They have-# fewer restrictions on e.g. the order they need to be processed in.+# --------------------------------------------------------------------------- #+# Replay event names — shared constant for client-side rejection+# --------------------------------------------------------------------------- #+SESSION_RECORDING_DEDICATED_KAFKA_EVENTS = ("$snapshot_items",)SESSION_RECORDING_EVENT_NAMES = ("$snapshot", "$performance_event", *SESSION_RECORDING_DEDICATED_KAFKA_EVENTS)-# let's track who is using this to detect new (ab)usive call sites quickly-CAPTURE_INTERNAL_EVENT_SUBMITTED_COUNTER = Counter(- "capture_internal_event_submitted",- "Events received by capture_internal, tagged by source.",- labelnames=["event_source"], # which internal codepath submitted this event+# --------------------------------------------------------------------------- #+# Constants+# --------------------------------------------------------------------------- #++SDK_INFO = "posthog-capture-v1-internal/1.0"++# v1 Options struct fields and their legacy property counterparts.+_OPTIONS_TO_LEGACY_PROPERTY: dict[str, str] = {+ "cookieless_mode": "$cookieless_mode",+ "disable_skew_correction": "$ignore_sent_at",+ "product_tour_id": "$product_tour_id",+ "process_person_profile": "$process_person_profile",+}+_VALID_OPTION_KEYS = frozenset(_OPTIONS_TO_LEGACY_PROPERTY.keys())++# Extra legacy aliases that must also be stripped from properties.+_EXTRA_LEGACY_ALIASES: dict[str, str] = {+ "disable_skew_correction": "disable_skew_adjustment",+}++_KNOWN_RESULT_STATUSES = frozenset({"ok", "drop", "warning", "retry"})++# --------------------------------------------------------------------------- #+# Metrics+# --------------------------------------------------------------------------- #++CAPTURE_V1_BATCH_SUBMITTED = Counter(+ "capture_v1_internal_batch_submitted",+ "Chunked batches submitted to capture v1 endpoint (one per chunk, retries excluded).",+ labelnames=["event_source"],+)+CAPTURE_V1_REQUEST_SUBMITTED = Counter(+ "capture_v1_internal_request_submitted",+ "HTTP POST requests to capture v1 endpoint (one per attempt, retries included).",+ labelnames=["event_source"],)-CAPTURE_INTERNAL_REQUEST_FAILED = Counter(- "capture_internal_request_failed",- "Failures from legacy capture_internal, tagged by source and status.",+CAPTURE_V1_EVENT_SUBMITTED = Counter(+ "capture_v1_internal_event_submitted",+ "Individual events submitted to capture v1 endpoint.",+ labelnames=["event_source"],+)+CAPTURE_V1_EVENT_RESULT = Counter(+ "capture_v1_internal_event_result",+ "Per-event result status from capture v1 endpoint.",+ labelnames=["event_source", "result"],+)+CAPTURE_V1_REQUEST_FAILED = Counter(+ "capture_v1_internal_request_failed",+ "Whole-request failures from capture v1 endpoint.",labelnames=["event_source", "status_code"],)+CAPTURE_V1_RESUBMIT = Counter(+ "capture_v1_internal_resubmit",+ "Resubmit rounds triggered by retry results.",+ labelnames=["event_source"],+)+CAPTURE_V1_OPTION_CONFLICT = Counter(+ "capture_v1_internal_option_conflict",+ "Typed option input disagreed with a legacy property; explicit won.",+ labelnames=["event_source", "field"],+)++# --------------------------------------------------------------------------- #+# Errors & result type+# --------------------------------------------------------------------------- #class CaptureInternalError(Exception):- pass+ """Raised on client-side validation failures or transport/HTTP errors.+ Carries a ``.status_code`` (the HTTP status from capture-rs, or 0 for+ client-side / transport errors) so callers can propagate it into their+ own HTTP responses.+ """-@timed("capture_internal_event_submission")-def capture_internal(- *, # only keyword args for clarity+ def __init__(self, message: str, *, status_code: int = 0) -> None:+ super().__init__(message)+ self.status_code = status_code+++@dataclass+class CaptureInternalResult:+ """Aggregated outcome of a (possibly multi-round) v1 batch submission."""++ status_code: int+ results: dict[str, dict[str, Any]] = field(default_factory=dict)+ error: Optional[dict[str, Any]] = None++ ok: list[str] = field(default_factory=list)+ dropped: list[str] = field(default_factory=list)+ warnings: list[str] = field(default_factory=list)+ retried: list[str] = field(default_factory=list)+ unaccounted: list[str] = field(default_factory=list)++ def succeeded(self) -> bool:+ return self.error is None and not self.dropped and not self.retried and not self.unaccounted++ def terminal_failures(self) -> dict[str, dict[str, Any]]:+ return {+ uid: self.results[uid] for uid in (*self.dropped, *self.retried, *self.unaccounted) if uid in self.results+ }++ def raise_for_status(self) -> None:+ if self.error:+ raise CaptureInternalError(+ f"capture internal whole-request failure ({self.status_code}): "+ f"{self.error.get('error', 'unknown')}: {self.error.get('error_description', '')}",+ status_code=self.status_code,+ )+ failures = len(self.dropped) + len(self.retried) + len(self.unaccounted)+ if failures:+ raise CaptureInternalError(+ f"capture internal partial failure: {len(self.dropped)} dropped, "+ f"{len(self.retried)} exhausted retries, {len(self.unaccounted)} unaccounted",+ status_code=0,+ )+++# --------------------------------------------------------------------------- #+# Header builder — single chokepoint for every physical POST+# --------------------------------------------------------------------------- #+++def _build_v1_headers(token: str, attempt: int) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {token}",+ "Content-Type": "application/json",+ "User-Agent": SDK_INFO,+ "PostHog-Sdk-Info": SDK_INFO,+ "PostHog-Attempt": str(attempt),+ "PostHog-Request-Id": str(uuid4()),+ "PostHog-Request-Timestamp": datetime.now(UTC).isoformat(),+ }+++# --------------------------------------------------------------------------- #+# Options / properties normalizer+# --------------------------------------------------------------------------- #+++def _resolve_scalar(+ explicit: Any,+ legacy: Any,+ *,+ field: str,+ event_source: str,+) -> Any:+ """Return *explicit* if set, else *legacy*; log + count when both are set and disagree."""+ if explicit is not None:+ if legacy is not None and legacy != explicit:+ logger.warning(+ "capture_internal option conflict",+ event_source=event_source,+ field=field,+ explicit=explicit,+ legacy=legacy,+ )+ CAPTURE_V1_OPTION_CONFLICT.labels(event_source=event_source, field=field).inc()+ return explicit+ return legacy+++def _normalize_options_and_properties(+ event_dict: dict[str, Any],+ *,+ process_person_profile: bool,+ event_source: str,+) -> tuple[dict[str, Any], Optional[str], Optional[str], dict[str, Any]]:+ """Separate typed ``options``/fields from free-form ``properties``.++ Returns ``(options_dict, session_id, window_id, cleaned_properties)``.+ The caller's dicts are never mutated.+ """+ raw_options: dict[str, Any] = event_dict.get("options") or {}+ props: dict[str, Any] = dict(event_dict.get("properties") or {})++ unknown = set(raw_options.keys()) - _VALID_OPTION_KEYS+ if unknown:+ raise CaptureInternalError(f"capture_internal ({event_source}): unknown option key(s): {sorted(unknown)}")++ options: dict[str, Any] = {}++ for opt_key, legacy_prop in _OPTIONS_TO_LEGACY_PROPERTY.items():+ explicit = raw_options.get(opt_key)+ legacy = props.pop(legacy_prop, None)++ alias = _EXTRA_LEGACY_ALIASES.get(opt_key)+ if alias:+ alias_val = props.pop(alias, None)+ if legacy is None:+ legacy = alias_val++ resolved = _resolve_scalar(explicit, legacy, field=opt_key, event_source=event_source)+ if resolved is not None:+ options[opt_key] = resolved++ session_id: Optional[str] = _resolve_scalar(+ event_dict.get("session_id"),+ props.pop("$session_id", None),+ field="session_id",+ event_source=event_source,+ )+ window_id: Optional[str] = _resolve_scalar(+ event_dict.get("window_id"),+ props.pop("$window_id", None),+ field="window_id",+ event_source=event_source,+ )++ # Function-level override: when the caller says no person processing,+ # force it even if the event-level option disagrees (but log the conflict).+ if not process_person_profile:+ existing = options.get("process_person_profile")+ if existing not in (None, False):+ logger.warning(+ "capture_internal option conflict",+ event_source=event_source,+ field="process_person_profile",+ explicit=f"function_param={process_person_profile}",+ legacy=existing,+ )+ CAPTURE_V1_OPTION_CONFLICT.labels(event_source=event_source, field="process_person_profile").inc()+ options["process_person_profile"] = False++ return options, session_id, window_id, props+++# --------------------------------------------------------------------------- #+# Payload builder+# --------------------------------------------------------------------------- #+++def _validate_batch_inputs(events: list[dict[str, Any]], *, token: str, event_source: str) -> None:+ """Validate required batch-level inputs. Raises CaptureInternalError on failure."""+ if not event_source:+ raise CaptureInternalError("capture_internal: event_source is required (identifies the submitting call site)")+ if not token:+ raise CaptureInternalError(f"capture_internal ({event_source}): API token is required")+ if not events:+ raise CaptureInternalError(f"capture_internal ({event_source}): at least one event is required")+++def prepare_capture_internal_batch(+ events: list[dict[str, Any]],+ *,token: str,- event_name: str,event_source: str,- distinct_id: str,- timestamp: Optional[datetime | str],- properties: dict[str, Any],- sent_at: Optional[datetime | str] = None,+ historical_migration: bool = False,process_person_profile: bool = False,- event_uuid: Optional[str] = None,-) -> Response:+) -> tuple[dict[str, Any], list[str]]:+ """Build a v1 batch envelope from caller-supplied event dicts.++ Returns ``(payload, ordered_uuids)`` so callers can correlate the+ results map."""- capture_internal submits a single-event capture request payload to the capture-rs backend service.- This is the preferred method for publishing events from the Django app on behalf of non-PostHog admin- teams/projects. PLEASE DO NOT write events directly to ingestion Kafka topics - USE THIS!+ _validate_batch_inputs(events, token=token, event_source=event_source)- Args:- token: API token to submit the event on behalf of (required)- event_name: the name of the event to be published (required)- event_source: observability tag indicating the internal module/codepath submitting the event (required)- distinct_id: the distict ID of the event (optional; required in properties if absent)- timestamp: the timestamp of the event to be published (optional; will be set to now UTC if absent)- properties: event properties to submit with the event (required; can be empty)- sent_at: time the client submitted this event (optional; typically, let capture_internal set this)- process_person_profile: if TRUE, process the person profile for the event according to the caller's settings.- if FALSE, disable person processing for this event.- event_uuid: optional deterministic UUID to assign to the event (default: capture-rs assigns a fresh UUIDv7).- Use this when the caller needs a stable, queryable event UUID — e.g. to link back to the event- from an admin UI. Must be a parseable UUID string.+ batch: list[dict[str, Any]] = []+ uuids: list[str] = []++ for ev in events:+ event_name: str = ev.get("event", "")+ if not event_name:+ raise CaptureInternalError(f"capture_internal ({event_source}): event name is required")++ if event_name in SESSION_RECORDING_EVENT_NAMES:+ raise CaptureInternalError(+ f"capture_internal ({event_source}): '{event_name}' is a replay event; use the replay capture path"+ )++ distinct_id: str = ev.get("distinct_id", "")+ if not distinct_id:+ props = ev.get("properties") or {}+ distinct_id = props.get("distinct_id", "")+ if not distinct_id:+ raise CaptureInternalError(f"capture_internal ({event_source}, {event_name}): distinct_id is required")++ event_uuid: str = ev.get("event_uuid") or ev.get("uuid") or str(uuid4())+ uuids.append(event_uuid)++ raw_ts: Any = ev.get("timestamp", "")+ if not raw_ts:+ timestamp_str = datetime.now(UTC).isoformat()+ elif isinstance(raw_ts, datetime):+ if raw_ts.tzinfo is None:+ raw_ts = raw_ts.replace(tzinfo=UTC)+ timestamp_str = raw_ts.astimezone(UTC).isoformat()+ else:+ timestamp_str = str(raw_ts)++ options, session_id, window_id, cleaned_props = _normalize_options_and_properties(+ ev, process_person_profile=process_person_profile, event_source=event_source+ )++ entry: dict[str, Any] = {+ "event": event_name,+ "uuid": event_uuid,+ "distinct_id": distinct_id,+ "timestamp": timestamp_str,+ "properties": cleaned_props,+ }+ if session_id is not None:+ entry["session_id"] = session_id+ if window_id is not None:+ entry["window_id"] = window_id+ if options:+ entry["options"] = options++ batch.append(entry)++ payload: dict[str, Any] = {+ "created_at": datetime.now(UTC).isoformat(),+ "capture_internal": True,+ "historical_migration": historical_migration,+ "batch": batch,+ }+ return payload, uuids- Returns:- Response object, the result of POSTing the event payload to the capture-rs backend service.- Throws:- HTTPError if the request fails.- CaptureInternalError if the inputs to capture_internal are malformed or missing required values.+# --------------------------------------------------------------------------- #+# Primary API+# --------------------------------------------------------------------------- #+++def _submit_batch_chunk(+ *,+ events: list[dict[str, Any]],+ token: str,+ event_source: str,+ historical_migration: bool,+ process_person_profile: bool,+ max_attempts: int,+ timeout: float,+) -> CaptureInternalResult:+ """Submit a single chunk of events to the v1 batch endpoint with retry logic.++ This is the internal workhorse — callers should use ``capture_batch_internal``+ which handles validation, chunking, and concurrent fan-out."""- logger.debug(- "capture_internal",+ payload, uuids = prepare_capture_internal_batch(+ events,token=token,- distinct_id=distinct_id,- event_name=event_name,event_source=event_source,+ historical_migration=historical_migration,+ process_person_profile=process_person_profile,)- event_payload = prepare_capture_internal_payload(- token,- event_name,- event_source,- distinct_id,- timestamp,- properties,- sent_at,- process_person_profile,- event_uuid,- )-- # determine if this is a recordings or events type, route to correct capture endpoint- resolved_capture_url = f"{CAPTURE_INTERNAL_URL}{NEW_ANALYTICS_CAPTURE_ENDPOINT}"- if event_name in SESSION_RECORDING_EVENT_NAMES:- resolved_capture_url = f"{CAPTURE_REPLAY_INTERNAL_URL}{REPLAY_CAPTURE_ENDPOINT}"-- with internal_requests_session() as s:- s.mount(- resolved_capture_url,+ url = f"{CAPTURE_INTERNAL_URL}{CAPTURE_V1_INTERNAL_ENDPOINT}"++ CAPTURE_V1_BATCH_SUBMITTED.labels(event_source=event_source).inc()+ CAPTURE_V1_EVENT_SUBMITTED.labels(event_source=event_source).inc(len(uuids))++ uuid_to_event: dict[str, dict[str, Any]] = {}+ for uid, entry in zip(uuids, payload["batch"]):+ uuid_to_event[uid] = entry++ aggregated: dict[str, dict[str, Any]] = {}+ attempt = 1+ pending_batch = payload["batch"]++ def _finalize(status_code: int, error: Optional[dict[str, Any]] = None) -> CaptureInternalResult:+ # Any uuid capture-rs never acked — including whole-request failures — is unaccounted.+ for uid in uuid_to_event:+ aggregated.setdefault(uid, {"result": "unaccounted"})+ result = CaptureInternalResult(status_code=status_code, results=aggregated, error=error)+ for uid, entry in aggregated.items():+ status = entry.get("result", "ok")+ if status == "ok":+ result.ok.append(uid)+ elif status == "drop":+ result.dropped.append(uid)+ elif status == "warning":+ result.warnings.append(uid)+ elif status == "retry":+ result.retried.append(uid)+ else:+ result.unaccounted.append(uid)+ return result++ with internal_requests_session() as session:+ session.mount(+ url,HTTPAdapter(max_retries=Retry(- total=3, backoff_factor=0.1, status_forcelist=[500, 502, 503, 504], allowed_methods={"POST"}+ total=3,+ backoff_factor=0.1,+ status_forcelist=[500, 502, 503, 504],+ allowed_methods={"POST"},)),)- CAPTURE_INTERNAL_EVENT_SUBMITTED_COUNTER.labels(event_source=event_source).inc()- 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()+ while True:+ headers = _build_v1_headers(token, attempt)+ submit_payload: dict[str, Any] = {+ "created_at": payload["created_at"],+ "capture_internal": payload["capture_internal"],+ "historical_migration": payload["historical_migration"],+ "batch": pending_batch,+ }++ CAPTURE_V1_REQUEST_SUBMITTED.labels(event_source=event_source).inc()+ try:+ resp = session.post(url, json=submit_payload, headers=headers, timeout=timeout)+ except RequestException as exc:+ CAPTURE_V1_REQUEST_FAILED.labels(event_source=event_source, status_code="transport").inc()+ logger.warning(+ "capture_internal_transport_error",+ event_source=event_source,+ request_id=headers.get("PostHog-Request-Id", ""),+ batch_size=len(pending_batch),+ error=str(exc),+ )+ return _finalize(0, {"error": "transport_error", "error_description": str(exc)})++ if resp.status_code != 200:+ CAPTURE_V1_REQUEST_FAILED.labels(+ event_source=event_source,+ status_code=str(resp.status_code),+ ).inc()+ try:+ error_body = resp.json()+ except Exception:+ error_body = {+ "error": "unknown",+ "error_description": resp.text[:500] if resp.text else "",+ }+ logger.warning(+ "capture_internal_request_failed",+ event_source=event_source,+ request_id=headers.get("PostHog-Request-Id", ""),+ status_code=resp.status_code,+ batch_size=len(pending_batch),+ error=error_body.get("error", "unknown"),+ )+ return _finalize(resp.status_code, error_body)++ # --- 200: parse per-event results ---+ try:+ body = resp.json()+ except Exception:+ return _finalize(+ resp.status_code,+ {"error": "invalid_json", "error_description": "could not parse 200 body"},+ )- return resp+ results_map: dict[str, Any] = body.get("results", {})++ retry_uuids: list[str] = []+ for uid in list(uuid_to_event.keys()):+ if uid in aggregated:+ continue+ entry = results_map.get(uid)+ if entry is None:+ continue+ clamped = entry.get("result", "ok")+ if clamped not in _KNOWN_RESULT_STATUSES:+ clamped = "unknown"+ CAPTURE_V1_EVENT_RESULT.labels(event_source=event_source, result=clamped).inc()+ if entry.get("result") == "retry":+ retry_uuids.append(uid)+ else:+ aggregated[uid] = entry++ if not retry_uuids or attempt >= max_attempts:+ for uid in retry_uuids:+ entry = results_map.get(uid, {"result": "retry"})+ aggregated[uid] = entry+ break++ # --- resubmit retry-uuids ---+ CAPTURE_V1_RESUBMIT.labels(event_source=event_source).inc()+ retry_after = _parse_retry_after(resp.headers.get("Retry-After"))+ if retry_after > 0:+ time.sleep(retry_after)++ pending_batch = [uuid_to_event[uid] for uid in retry_uuids]+ attempt += 1++ return _finalize(200)+++def _merge_results(chunk_results: list[CaptureInternalResult]) -> CaptureInternalResult:+ """Merge results from multiple chunk submissions into a single result."""+ merged = CaptureInternalResult(status_code=200)+ for cr in chunk_results:+ if cr.error is not None and merged.error is None:+ merged.error = cr.error+ merged.status_code = cr.status_code+ merged.results.update(cr.results)+ merged.ok.extend(cr.ok)+ merged.dropped.extend(cr.dropped)+ merged.warnings.extend(cr.warnings)+ merged.retried.extend(cr.retried)+ merged.unaccounted.extend(cr.unaccounted)+ return mergeddef capture_batch_internal(*,events: list[dict[str, Any]],- event_source: str,token: str,+ event_source: str,+ historical_migration: bool = False,process_person_profile: bool = False,-) -> list[Future]:+ max_attempts: int = CAPTURE_V1_INTERNAL_MAX_ATTEMPTS,+ timeout: float = 2,+) -> CaptureInternalResult:"""- capture_batch_internal submits multiple capture request payloads to- PostHog (capture-rs backend) concurrently. capture_batch_internal does- not submit single requests to the capture /batch/ endpoint, so historical- event submission is not supported.+ capture_batch_internal submits multiple capture request payloads to capture-rs on+ behalf of a customer team. This is the preferred method for publishing analytics events+ from the Django app. PLEASE DO NOT write events directly to ingestion Kafka topics —+ USE THIS! The capture-rs pipeline handles deduplication, quotas, billing, and routing;+ bypassing it creates safety and correctness problems.++ NOTE: This is for submitting events ON BEHALF OF A CUSTOMER TEAM. It is NOT for+ submitting SDK-style internal telemetry events for PostHog's own team (team 2) — the+ posthoganalytics SDK integration handles that separately.++ Submits events as true batch POSTs to the v1 analytics endpoint. capture-rs returns+ per-event results; events that get a ``retry`` result are automatically resubmitted up+ to ``max_attempts`` rounds. Transport-level retries on 5xx are handled by urllib3.++ Automatic chunking:+ Batches larger than ``CAPTURE_INTERNAL_BATCH_CHUNK_SIZE`` (default 200 events) are+ automatically split into chunks and submitted concurrently using up to+ ``CAPTURE_INTERNAL_MAX_WORKERS`` (default 8) threads. Callers do NOT need to+ pre-chunk — the API handles this transparently. Small batches (<=200 events)+ are submitted directly with zero threading overhead.++ Each chunk gets its own retry budget (``max_attempts``). If one chunk fails+ entirely (transport error), its events appear in ``unaccounted``; other chunks'+ results are preserved.++ Session replay events ($snapshot, $performance_event, $snapshot_items) are NOT SUPPORTED+ and will raise CaptureInternalError. Real replay ingestion flows through SDKs directly+ to the capture-rs /s/ endpoint.++ event.options reference (typed options replacing legacy $-prefixed properties):+ ┌─────────────────────────┬────────────────────────────┬──────────────┐+ │ options key │ replaces legacy property │ default │+ ├─────────────────────────┼────────────────────────────┼──────────────┤+ │ cookieless_mode │ $cookieless_mode │ None/omitted │+ │ disable_skew_correction │ $ignore_sent_at │ None/omitted │+ │ │ (alias: disable_skew_ │ │+ │ │ adjustment) │ │+ │ product_tour_id │ $product_tour_id │ None/omitted │+ │ process_person_profile │ $process_person_profile │ see below │+ └─────────────────────────┴────────────────────────────┴──────────────┘++ Additional top-level event fields (also extracted from properties):+ ┌─────────────────────────┬────────────────────────────┬──────────────┐+ │ event field │ replaces legacy property │ default │+ ├─────────────────────────┼────────────────────────────┼──────────────┤+ │ session_id │ $session_id │ None/omitted │+ │ window_id │ $window_id │ None/omitted │+ └─────────────────────────┴────────────────────────────┴──────────────┘++ When both a typed key AND its legacy $-property are present, the typed key wins+ (a warning metric ``capture_v1_internal_option_conflict`` is emitted). The legacy+ property is always stripped from ``properties`` regardless.++ process_person_profile interaction:+ The batch-level ``process_person_profile`` param acts as a SAFETY RAIL. When+ False (default), it forces ``options.process_person_profile = False`` for EVERY+ event in the batch — even if the event's own options dict says True (a warning+ is logged on conflict). Only when the batch-level param is True does the+ per-event ``options.process_person_profile`` value get respected as-is. This+ prevents accidental expensive person profile updates from internal tooling.Args:- events: List of event payloads to capture. Each payload MUST include- well-formed distinct_id, timestamp, and (possibly empty) properties dict- event_source: observability tag indicating the internal module/codepath submitting the event (required)- token: API token to submit events in this batch on behalf of (required; overrides individual event tokens)- process_person_profile: if TRUE, process the person profile for each event according to it's properties or team config- if FALSE, disable person processing for all events in the batch (default: FALSE)+ events: list of event dicts to capture. Each MUST include:+ - ``event`` (str): event name+ - ``distinct_id`` (str): required; may alternatively appear in ``properties``+ - ``properties`` (dict): event properties (required; can be empty)+ Optional per-event fields:+ - ``timestamp`` (str | datetime): defaults to now UTC if absent+ - ``options`` (dict): typed options per table above+ - ``session_id``, ``window_id`` (str): top-level fields per table above+ - ``event_uuid`` (str): deterministic UUID; defaults to a fresh UUIDv7+ token: API token to submit events on behalf of (required; overrides individual+ event tokens)+ event_source: observability tag indicating the internal module/codepath submitting+ the events (REQUIRED — validated; raises CaptureInternalError if empty).+ Callers MUST supply this so Prometheus metrics can identify which call site+ is submitting events and detect (ab)usive new callers.+ historical_migration: if True, routes events to the historical ingestion path+ in capture-rs (separate Kafka topic/consumer group)+ process_person_profile: batch-level safety rail (default: False). See+ "process_person_profile interaction" above.+ max_attempts: application-level retry budget for per-event ``retry`` results from+ capture-rs (default: 4). Does not affect transport-level 5xx retries.+ timeout: HTTP request timeout in seconds (default: 2)Returns:- List of Future objects that the caller can resolve to Response objects or thrown Exceptions+ CaptureInternalResult with per-event outcomes. Call ``.raise_for_status()`` to+ raise ``CaptureInternalError`` on any failure (whole-request or partial). Inspect+ ``.ok``, ``.dropped``, ``.retried``, ``.unaccounted`` lists for fine-grained handling.++ Raises:+ CaptureInternalError: on client-side validation failures (missing/empty event_source,+ missing token, empty batch, replay event names, unknown option keys) or+ HTTP/transport errors. The exception carries a ``.status_code`` attribute+ (the HTTP status from capture-rs, or 0 for client-side/transport errors)."""- logger.debug(- "capture_batch_internal",- event_count=len(events),+ # Validate early so we fail fast before chunking/fan-out, not inside a worker thread.+ _validate_batch_inputs(events, token=token, event_source=event_source)++ chunk_size = max(CAPTURE_INTERNAL_BATCH_CHUNK_SIZE, 1)++ def _submit_chunk(chunk_events: list[dict[str, Any]]) -> CaptureInternalResult:+ return _submit_batch_chunk(+ events=chunk_events,+ token=token,+ event_source=event_source,+ historical_migration=historical_migration,+ process_person_profile=process_person_profile,+ max_attempts=max_attempts,+ timeout=timeout,+ )++ # Hot path: small batch — submit directly, no threading overhead.+ if len(events) <= chunk_size:+ return _submit_chunk(events)++ # Large batch: chunk and fan out concurrently.+ chunks = [events[i : i + chunk_size] for i in range(0, len(events), chunk_size)]+ logger.info(+ "capture_batch_internal_chunked",event_source=event_source,- token=token,- process_person_profile=process_person_profile,+ total_events=len(events),+ chunks=len(chunks),+ chunk_size=chunk_size,+ max_workers=CAPTURE_INTERNAL_MAX_WORKERS,)- futures: list[Future] = []-+ chunk_results: list[CaptureInternalResult] = []with ThreadPoolExecutor(max_workers=CAPTURE_INTERNAL_MAX_WORKERS) as executor:- # Note:- # 1. token should be supplied by caller, and be consistent per batch submitted.- # new capture_internal will attempt to extract from each event if missing- # 2. distinct_id should be present on each event since these can differ within a batch- sent_at: datetime = datetime.now(UTC) # should be same for whole batch- for event in events:- properties: dict[str, Any] = event.get("properties", {})- distinct_id: str = event.get("distinct_id", "")- timestamp: str = event.get("timestamp", properties.get("timestamp", ""))-- future = executor.submit(- capture_internal,- token=token,- event_name=event.get("event", ""),- event_source=event_source,- distinct_id=distinct_id,- timestamp=timestamp,- properties=properties,- sent_at=sent_at,- process_person_profile=process_person_profile,- )- futures.append(future)+ futures = {executor.submit(_submit_chunk, chunk): i for i, chunk in enumerate(chunks)}+ for future in as_completed(futures):+ chunk_idx = futures[future]+ try:+ chunk_results.append(future.result())+ except Exception as exc:+ logger.exception(+ "capture_batch_internal_chunk_error",+ event_source=event_source,+ chunk=chunk_idx,+ error=str(exc),+ )+ chunk_results.append(+ CaptureInternalResult(+ status_code=0,+ error={"error": "chunk_exception", "error_description": str(exc)},+ )+ )- return futures+ return _merge_results(chunk_results)-# prep payload for new capture_internal to POST to capture-rs-def prepare_capture_internal_payload(+def _parse_retry_after(header_value: Optional[str]) -> float:+ """Parse Retry-After header, capped to the configured maximum."""+ if not header_value:+ return 0.0+ try:+ val = float(header_value)+ except (ValueError, TypeError):+ return 1.0+ return min(max(val, 0), CAPTURE_V1_INTERNAL_RETRY_AFTER_CAP_SECONDS)+++# --------------------------------------------------------------------------- #+# Convenience single-event wrapper+# --------------------------------------------------------------------------- #+++def capture_internal(+ *,token: str,event_name: str,event_source: str,- distinct_id: Optional[str],- timestamp: Optional[datetime | str],- properties: dict[str, Any],- sent_at: Optional[datetime | str] = None,- process_person_profile: bool = False,+ distinct_id: str,+ timestamp: Optional[str | datetime] = None,+ properties: Optional[dict[str, Any]] = None,+ options: Optional[dict[str, Any]] = None,+ session_id: Optional[str] = None,+ window_id: Optional[str] = None,event_uuid: Optional[str] = None,-) -> dict[str, Any]:- # mark event as internal for observability- properties["capture_internal"] = True-- # for back compatibility, if this is TRUE, we don't change the event- # so existing event (or team acct) settings for $process_person_profile- # will apply. If FALSE, we set the prop to explicitly force the issue.- # with FALSE as default, we avoid accidental internal uses that cause- # expensive person profile updates for no reason- if not process_person_profile:- properties["$process_person_profile"] = process_person_profile+ process_person_profile: bool = False,+ historical_migration: bool = False,+ timeout: float = 2,+) -> CaptureInternalResult:+ """+ capture_internal submits a single-event capture request payload to the capture-rs+ backend service. This is the preferred method for publishing events from the Django+ app on behalf of non-PostHog-admin teams/projects. PLEASE DO NOT write events directly+ to ingestion Kafka topics — USE THIS! The capture-rs pipeline handles deduplication,+ quotas, billing, and routing; bypassing it creates safety and correctness problems.- # ensure args passed into capture_internal that- # override event attributes are well formed+ NOTE: This is for submitting events ON BEHALF OF A CUSTOMER TEAM. It is NOT for+ submitting SDK-style internal telemetry events for PostHog's own team (team 2) — the+ posthoganalytics SDK integration handles that separately.- if not token:- raise CaptureInternalError(f"capture_internal ({event_source}, {event_name}): API token is required")-- if not distinct_id:- distinct_id = properties.get("distinct_id", None)- if not distinct_id:- raise CaptureInternalError(f"capture_internal ({event_source}, {event_name}): distinct ID is required")-- if not event_name:- raise CaptureInternalError(f"capture_internal ({event_source}): event name is required")-- # if the timestamp or sent_at fields are strings, assume they are well-formed ISO8601 stamps- if not sent_at:- sent_at = datetime.now(UTC).isoformat()- elif isinstance(sent_at, datetime):- sent_at = sent_at.replace(tzinfo=UTC).isoformat()- if not timestamp:- timestamp = datetime.now(UTC).isoformat()- elif isinstance(timestamp, datetime):- timestamp = timestamp.replace(tzinfo=UTC).isoformat()+ Wraps the event into a 1-element batch and delegates to capture_batch_internal.+ See capture_batch_internal's docstring for the full event.options reference table+ and the process_person_profile batch-level interaction.- payload: dict[str, Any] = {- "api_key": token,- "timestamp": timestamp,- "distinct_id": distinct_id,- "sent_at": sent_at,+ Session replay events ($snapshot, $performance_event, $snapshot_items) are NOT SUPPORTED+ and will raise CaptureInternalError. Real replay ingestion flows through SDKs directly+ to the capture-rs /s/ endpoint.++ Args:+ token: API token to submit the event on behalf of (required)+ event_name: the name of the event to be published (required)+ event_source: observability tag indicating the internal module/codepath submitting+ the event (REQUIRED — validated; raises CaptureInternalError if empty).+ Callers MUST supply this so Prometheus metrics can identify which call site+ is submitting events and detect (ab)usive new callers.+ distinct_id: the distinct ID for the event (required)+ timestamp: the timestamp of the event (optional; will be set to now UTC if absent).+ Accepts datetime objects or ISO8601 strings.+ properties: event properties to submit with the event (optional; can be empty).+ Legacy ``$``-prefixed keys that map to typed options are automatically+ extracted and stripped — see the options table in capture_batch_internal.+ options: typed event options dict (optional). See the options reference table in+ capture_batch_internal for valid keys, legacy equivalents, and defaults.+ session_id: session ID (optional). Preferred over ``$session_id`` in properties.+ window_id: window ID (optional). Preferred over ``$window_id`` in properties.+ event_uuid: optional deterministic UUID to assign to the event (default: capture-rs+ assigns a fresh UUIDv7). Use when the caller needs a stable, queryable event+ UUID — e.g. to link back to the event from an admin UI. Must be a parseable+ UUID string.+ process_person_profile: batch-level safety rail (default: False). When False,+ forces person processing OFF regardless of per-event options. When True,+ per-event options.process_person_profile is respected. See+ capture_batch_internal docstring for the full interaction.+ historical_migration: if True, routes to the historical ingestion path in+ capture-rs (separate Kafka topic/consumer group).+ timeout: HTTP request timeout in seconds (default: 2)++ Returns:+ CaptureInternalResult with per-event outcome. Call ``.raise_for_status()`` to raise+ ``CaptureInternalError`` on failure. For best-effort fire-and-forget patterns,+ check ``.succeeded()`` instead.++ Raises:+ CaptureInternalError: on client-side validation failures (missing/empty event_source,+ missing token, replay event names, etc.) or HTTP/transport errors. Carries a+ ``.status_code`` attribute (HTTP status from capture-rs, or 0 for client-side/+ transport errors) so callers can propagate into their own HTTP responses.+ """+ event_dict: dict[str, Any] = {"event": event_name,- "properties": properties,+ "distinct_id": distinct_id,+ "properties": properties or {},}- if event_uuid:- payload["uuid"] = event_uuid- return payload+ if timestamp is not None:+ event_dict["timestamp"] = timestamp+ if options is not None:+ event_dict["options"] = options+ if session_id is not None:+ event_dict["session_id"] = session_id+ if window_id is not None:+ event_dict["window_id"] = window_id+ if event_uuid is not None:+ event_dict["event_uuid"] = event_uuid++ return capture_batch_internal(+ events=[event_dict],+ token=token,+ event_source=event_source,+ historical_migration=historical_migration,+ process_person_profile=process_person_profile,+ timeout=timeout,+ )diff --git a/posthog/api/capture_dispatch.py b/posthog/api/capture_dispatch.pydeleted file mode 100644index 96e36587a432..000000000000--- a/posthog/api/capture_dispatch.py+++ /dev/null@@ -1,398 +0,0 @@-"""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/capture_v1.py b/posthog/api/capture_v1.pydeleted file mode 100644index 79e5cd7b92b8..000000000000--- a/posthog/api/capture_v1.py+++ /dev/null@@ -1,549 +0,0 @@-"""capture_v1_internal — batch-native client for the v1 analytics capture endpoint.--Targets ``/i/v1/analytics/events`` (capture-rs v1). Analytics events only;-replay event names are rejected client-side. Typed ``event.options`` replaces-the legacy property-stuffing pattern, and legacy ``$``-keys are defensively-stripped so capture-rs's blind property splicing never produces duplicate keys.--No existing ``capture_internal`` call sites are touched — this module is wired-in later behind feature flags.-"""--from __future__ import annotations--import time-from dataclasses import dataclass, field-from datetime import UTC, datetime-from typing import Any, Optional-from uuid import uuid4--import structlog-from prometheus_client import Counter-from requests.adapters import HTTPAdapter, Retry-from requests.exceptions import RequestException--from posthog.api.capture import SESSION_RECORDING_EVENT_NAMES-from posthog.security.outbound_proxy import internal_requests_session-from posthog.settings.ingestion import (- CAPTURE_INTERNAL_URL,- CAPTURE_V1_INTERNAL_ENDPOINT,- CAPTURE_V1_INTERNAL_MAX_ATTEMPTS,- CAPTURE_V1_INTERNAL_RETRY_AFTER_CAP_SECONDS,-)--logger = structlog.get_logger(__name__)--# --------------------------------------------------------------------------- #-# Constants-# --------------------------------------------------------------------------- #--SDK_INFO = "posthog-capture-v1-internal/1.0"--# v1 Options struct fields and their legacy property counterparts.-# Mapping is {option_key: $property_key}.-_OPTIONS_TO_LEGACY_PROPERTY: dict[str, str] = {- "cookieless_mode": "$cookieless_mode",- "disable_skew_correction": "$ignore_sent_at",- "product_tour_id": "$product_tour_id",- "process_person_profile": "$process_person_profile",-}-_VALID_OPTION_KEYS = frozenset(_OPTIONS_TO_LEGACY_PROPERTY.keys())--# Extra legacy aliases that must also be stripped from properties.-_EXTRA_LEGACY_ALIASES: dict[str, str] = {- "disable_skew_correction": "disable_skew_adjustment",-}--_KNOWN_RESULT_STATUSES = frozenset({"ok", "drop", "warning", "retry"})--# --------------------------------------------------------------------------- #-# Metrics-# --------------------------------------------------------------------------- #--CAPTURE_V1_BATCH_SUBMITTED = Counter(- "capture_v1_internal_batch_submitted",- "Batch submissions to capture v1 endpoint.",- labelnames=["event_source"],-)-CAPTURE_V1_EVENT_SUBMITTED = Counter(- "capture_v1_internal_event_submitted",- "Individual events submitted to capture v1 endpoint.",- labelnames=["event_source"],-)-CAPTURE_V1_EVENT_RESULT = Counter(- "capture_v1_internal_event_result",- "Per-event result status from capture v1 endpoint.",- labelnames=["event_source", "result"],-)-CAPTURE_V1_REQUEST_FAILED = Counter(- "capture_v1_internal_request_failed",- "Whole-request failures from capture v1 endpoint.",- labelnames=["event_source", "status_code"],-)-CAPTURE_V1_RESUBMIT = Counter(- "capture_v1_internal_resubmit",- "Resubmit rounds triggered by retry results.",- labelnames=["event_source"],-)-CAPTURE_V1_OPTION_CONFLICT = Counter(- "capture_v1_internal_option_conflict",- "Typed option input disagreed with a legacy property; explicit won.",- labelnames=["event_source", "field"],-)--# --------------------------------------------------------------------------- #-# Errors & result type-# --------------------------------------------------------------------------- #---class CaptureV1InternalError(Exception):- """Client-side validation failure — never reaches the network."""---@dataclass-class CaptureV1Result:- """Aggregated outcome of a (possibly multi-round) v1 batch submission."""-- status_code: int- results: dict[str, dict[str, Any]] = field(default_factory=dict)- error: Optional[dict[str, Any]] = None-- ok: list[str] = field(default_factory=list)- dropped: list[str] = field(default_factory=list)- warnings: list[str] = field(default_factory=list)- retried: list[str] = field(default_factory=list)- unaccounted: list[str] = field(default_factory=list)-- def succeeded(self) -> bool:- return self.error is None and not self.dropped and not self.retried and not self.unaccounted-- def terminal_failures(self) -> dict[str, dict[str, Any]]:- return {- uid: self.results[uid] for uid in (*self.dropped, *self.retried, *self.unaccounted) if uid in self.results- }-- def raise_for_status(self) -> None:- if self.error:- raise CaptureV1InternalError(- f"capture v1 whole-request failure ({self.status_code}): "- f"{self.error.get('error', 'unknown')}: {self.error.get('error_description', '')}"- )- failures = len(self.dropped) + len(self.retried) + len(self.unaccounted)- if failures:- raise CaptureV1InternalError(- f"capture v1 partial failure: {len(self.dropped)} dropped, "- f"{len(self.retried)} exhausted retries, {len(self.unaccounted)} unaccounted"- )---# --------------------------------------------------------------------------- #-# Header builder — single chokepoint for every physical POST-# --------------------------------------------------------------------------- #---def _build_v1_headers(token: str, attempt: int) -> dict[str, str]:- return {- "Authorization": f"Bearer {token}",- "Content-Type": "application/json",- "User-Agent": SDK_INFO,- "PostHog-Sdk-Info": SDK_INFO,- "PostHog-Attempt": str(attempt),- "PostHog-Request-Id": str(uuid4()),- "PostHog-Request-Timestamp": datetime.now(UTC).isoformat(),- }---# --------------------------------------------------------------------------- #-# Options / properties normalizer-# --------------------------------------------------------------------------- #---def _resolve_scalar(- explicit: Any,- legacy: Any,- *,- field: str,- event_source: str,-) -> Any:- """Return *explicit* if set, else *legacy*; log + count when both are set and disagree."""- if explicit is not None:- if legacy is not None and legacy != explicit:- logger.warning(- "capture_v1_internal option conflict",- event_source=event_source,- field=field,- explicit=explicit,- legacy=legacy,- )- CAPTURE_V1_OPTION_CONFLICT.labels(event_source=event_source, field=field).inc()- return explicit- return legacy---def _normalize_options_and_properties(- event_dict: dict[str, Any],- *,- process_person_profile: bool,- event_source: str,-) -> tuple[dict[str, Any], Optional[str], Optional[str], dict[str, Any]]:- """Separate typed ``options``/fields from free-form ``properties``.-- Returns ``(options_dict, session_id, window_id, cleaned_properties)``.- The caller's dicts are never mutated.- """- raw_options: dict[str, Any] = event_dict.get("options") or {}- props: dict[str, Any] = dict(event_dict.get("properties") or {})-- unknown = set(raw_options.keys()) - _VALID_OPTION_KEYS- if unknown:- raise CaptureV1InternalError(f"capture_v1_internal ({event_source}): unknown option key(s): {sorted(unknown)}")-- options: dict[str, Any] = {}-- for opt_key, legacy_prop in _OPTIONS_TO_LEGACY_PROPERTY.items():- explicit = raw_options.get(opt_key)- legacy = props.pop(legacy_prop, None)-- alias = _EXTRA_LEGACY_ALIASES.get(opt_key)- if alias:- alias_val = props.pop(alias, None)- if legacy is None:- legacy = alias_val-- resolved = _resolve_scalar(explicit, legacy, field=opt_key, event_source=event_source)- if resolved is not None:- options[opt_key] = resolved-- session_id: Optional[str] = _resolve_scalar(- event_dict.get("session_id"),- props.pop("$session_id", None),- field="session_id",- event_source=event_source,- )- window_id: Optional[str] = _resolve_scalar(- event_dict.get("window_id"),- props.pop("$window_id", None),- field="window_id",- event_source=event_source,- )-- # Function-level override: when the caller says no person processing,- # force it even if the event-level option disagrees (but log the conflict).- if not process_person_profile:- existing = options.get("process_person_profile")- if existing is not None and existing is not False:- logger.warning(- "capture_v1_internal option conflict",- event_source=event_source,- field="process_person_profile",- explicit=f"function_param={process_person_profile}",- legacy=existing,- )- CAPTURE_V1_OPTION_CONFLICT.labels(event_source=event_source, field="process_person_profile").inc()- options["process_person_profile"] = False-- return options, session_id, window_id, props---# --------------------------------------------------------------------------- #-# Payload builder-# --------------------------------------------------------------------------- #---def prepare_capture_v1_batch(- events: list[dict[str, Any]],- *,- token: str,- event_source: str,- historical_migration: bool = False,- process_person_profile: bool = False,-) -> tuple[dict[str, Any], list[str]]:- """Build a v1 batch envelope from caller-supplied event dicts.-- Returns ``(payload, ordered_uuids)`` so callers can correlate the- results map.- """- if not token:- raise CaptureV1InternalError(f"capture_v1_internal ({event_source}): API token is required")- if not events:- raise CaptureV1InternalError(f"capture_v1_internal ({event_source}): at least one event is required")-- batch: list[dict[str, Any]] = []- uuids: list[str] = []-- for ev in events:- event_name: str = ev.get("event", "")- if not event_name:- raise CaptureV1InternalError(f"capture_v1_internal ({event_source}): event name is required")-- if event_name in SESSION_RECORDING_EVENT_NAMES:- raise CaptureV1InternalError(- f"capture_v1_internal ({event_source}): '{event_name}' is a replay event; use capture_internal"- )-- distinct_id: str = ev.get("distinct_id", "")- if not distinct_id:- props = ev.get("properties") or {}- distinct_id = props.get("distinct_id", "")- if not distinct_id:- raise CaptureV1InternalError(f"capture_v1_internal ({event_source}, {event_name}): distinct_id is required")-- event_uuid: str = ev.get("event_uuid") or ev.get("uuid") or str(uuid4())- uuids.append(event_uuid)-- raw_ts: Any = ev.get("timestamp", "")- if not raw_ts:- timestamp_str = datetime.now(UTC).isoformat()- elif isinstance(raw_ts, datetime):- if raw_ts.tzinfo is None:- raw_ts = raw_ts.replace(tzinfo=UTC)- timestamp_str = raw_ts.astimezone(UTC).isoformat()- else:- timestamp_str = str(raw_ts)-- options, session_id, window_id, cleaned_props = _normalize_options_and_properties(- ev, process_person_profile=process_person_profile, event_source=event_source- )-- entry: dict[str, Any] = {- "event": event_name,- "uuid": event_uuid,- "distinct_id": distinct_id,- "timestamp": timestamp_str,- "properties": cleaned_props,- }- if session_id is not None:- entry["session_id"] = session_id- if window_id is not None:- entry["window_id"] = window_id- if options:- entry["options"] = options-- batch.append(entry)-- payload: dict[str, Any] = {- "created_at": datetime.now(UTC).isoformat(),- "capture_internal": True,- "historical_migration": historical_migration,- "batch": batch,- }- return payload, uuids---# --------------------------------------------------------------------------- #-# Primary API-# --------------------------------------------------------------------------- #---def capture_v1_batch_internal(- *,- events: list[dict[str, Any]],- token: str,- event_source: str,- historical_migration: bool = False,- process_person_profile: bool = False,- max_attempts: int = CAPTURE_V1_INTERNAL_MAX_ATTEMPTS,- timeout: float = 2,-) -> CaptureV1Result:- """Submit a batch of events to the v1 analytics capture endpoint.-- Transport-level retries on 5xx are handled by urllib3 (hardcoded at 3,- matching v0). ``max_attempts`` caps application-level resubmit rounds- for per-event ``retry`` results.- """- payload, uuids = prepare_capture_v1_batch(- events,- token=token,- event_source=event_source,- historical_migration=historical_migration,- process_person_profile=process_person_profile,- )-- url = f"{CAPTURE_INTERNAL_URL}{CAPTURE_V1_INTERNAL_ENDPOINT}"-- CAPTURE_V1_BATCH_SUBMITTED.labels(event_source=event_source).inc()- CAPTURE_V1_EVENT_SUBMITTED.labels(event_source=event_source).inc(len(uuids))-- # Build the index of uuid→event so we can resubmit subsets.- uuid_to_event: dict[str, dict[str, Any]] = {}- for uid, entry in zip(uuids, payload["batch"]):- uuid_to_event[uid] = entry-- # Aggregate terminal outcomes across rounds.- aggregated: dict[str, dict[str, Any]] = {}- attempt = 1- pending_batch = payload["batch"]-- with internal_requests_session() as session:- session.mount(- url,- HTTPAdapter(- max_retries=Retry(- total=3,- backoff_factor=0.1,- status_forcelist=[500, 502, 503, 504],- allowed_methods={"POST"},- )- ),- )-- while True:- headers = _build_v1_headers(token, attempt)- submit_payload: dict[str, Any] = {- "created_at": payload["created_at"],- "capture_internal": payload["capture_internal"],- "historical_migration": payload["historical_migration"],- "batch": pending_batch,- }-- try:- resp = session.post(url, json=submit_payload, headers=headers, timeout=timeout)- except RequestException as exc:- CAPTURE_V1_REQUEST_FAILED.labels(event_source=event_source, status_code="transport").inc()- return CaptureV1Result(- status_code=0,- error={"error": "transport_error", "error_description": str(exc)},- )-- if resp.status_code != 200:- CAPTURE_V1_REQUEST_FAILED.labels(- event_source=event_source,- status_code=str(resp.status_code),- ).inc()- try:- error_body = resp.json()- except Exception:- error_body = {- "error": "unknown",- "error_description": resp.text[:500] if resp.text else "",- }- return CaptureV1Result(- status_code=resp.status_code,- error=error_body,- )-- # --- 200: parse per-event results ---- try:- body = resp.json()- except Exception:- return CaptureV1Result(- status_code=resp.status_code,- error={"error": "invalid_json", "error_description": "could not parse 200 body"},- )-- results_map: dict[str, Any] = body.get("results", {})-- retry_uuids: list[str] = []- for uid in list(uuid_to_event.keys()):- if uid in aggregated:- continue- entry = results_map.get(uid)- if entry is None:- continue- clamped = entry.get("result", "ok")- if clamped not in _KNOWN_RESULT_STATUSES:- clamped = "unknown"- CAPTURE_V1_EVENT_RESULT.labels(event_source=event_source, result=clamped).inc()- if entry.get("result") == "retry":- retry_uuids.append(uid)- else:- aggregated[uid] = entry-- if not retry_uuids or attempt >= max_attempts:- for uid in retry_uuids:- entry = results_map.get(uid, {"result": "retry"})- aggregated[uid] = entry- break-- # --- resubmit retry-uuids ---- CAPTURE_V1_RESUBMIT.labels(event_source=event_source).inc()- retry_after = _parse_retry_after(resp.headers.get("Retry-After"))- if retry_after > 0:- time.sleep(retry_after)-- pending_batch = [uuid_to_event[uid] for uid in retry_uuids]- attempt += 1-- # Sweep for uuids never acknowledged by capture-rs.- for uid in uuid_to_event:- if uid not in aggregated:- aggregated[uid] = {"result": "unaccounted"}-- result = CaptureV1Result(status_code=200, results=aggregated)- for uid, entry in aggregated.items():- status = entry.get("result", "ok")- if status == "ok":- result.ok.append(uid)- elif status == "drop":- result.dropped.append(uid)- elif status == "warning":- result.warnings.append(uid)- elif status == "retry":- result.retried.append(uid)- else:- result.unaccounted.append(uid)-- return result---def _parse_retry_after(header_value: Optional[str]) -> float:- """Parse Retry-After header, capped to the configured maximum."""- if not header_value:- return 0.0- try:- val = float(header_value)- except (ValueError, TypeError):- return 1.0- return min(max(val, 0), CAPTURE_V1_INTERNAL_RETRY_AFTER_CAP_SECONDS)---# --------------------------------------------------------------------------- #-# Convenience single-event wrapper-# --------------------------------------------------------------------------- #---def capture_v1_internal(- *,- token: str,- event_name: str,- event_source: str,- distinct_id: str,- timestamp: Optional[str | datetime] = None,- properties: Optional[dict[str, Any]] = None,- options: Optional[dict[str, Any]] = None,- session_id: Optional[str] = None,- window_id: Optional[str] = None,- event_uuid: Optional[str] = None,- process_person_profile: bool = False,- historical_migration: bool = False,- timeout: float = 2,-) -> CaptureV1Result:- """Submit a single event to the v1 analytics capture endpoint.-- Wraps the event into a 1-element batch and delegates to- :func:`capture_v1_batch_internal`.- """- event_dict: dict[str, Any] = {- "event": event_name,- "distinct_id": distinct_id,- "properties": properties or {},- }- if timestamp is not None:- event_dict["timestamp"] = timestamp- if options is not None:- event_dict["options"] = options- if session_id is not None:- event_dict["session_id"] = session_id- if window_id is not None:- event_dict["window_id"] = window_id- if event_uuid is not None:- event_dict["event_uuid"] = event_uuid-- return capture_v1_batch_internal(- events=[event_dict],- token=token,- event_source=event_source,- historical_migration=historical_migration,- process_person_profile=process_person_profile,- timeout=timeout,- )diff --git a/posthog/api/llm_prompt.py b/posthog/api/llm_prompt.pyindex bdc2c0ecc723..2060b1f1bfdb 100644--- a/posthog/api/llm_prompt.py+++ b/posthog/api/llm_prompt.py@@ -15,7 +15,7 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.serializers import BaseSerializer-from posthog.api.capture_dispatch import capture_internal_routed+from posthog.api.capture import capture_internalfrom 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_routed(+ capture_internal(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.pyindex c27dcd44d2a1..a84d97ecda75 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -30,7 +30,7 @@ from posthog.schema import ProductKeyfrom posthog.hogql.constants import CSV_EXPORT_LIMIT-from posthog.api.capture_dispatch import CaptureRoutedError, capture_internal_routed+from posthog.api.capture import CaptureInternalError, capture_internalfrom posthog.api.documentation import PersonPropertiesSerializerfrom posthog.api.property_value_metrics import PROPERTY_VALUES_DURATIONfrom posthog.api.routing import TeamAndOrgViewSetMixin@@ -972,7 +972,7 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):}try:- result = capture_internal_routed(+ result = capture_internal(token=self.team.api_token,event_name=event_name,event_source="person_viewset",@@ -983,7 +983,7 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)result.raise_for_status()- except CaptureRoutedError as cre:+ except CaptureInternalError as cre:logger.warning("delete_person_property.capture_http_error",team_id=self.team_id,@@ -1145,7 +1145,7 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):}try:- result = capture_internal_routed(+ result = capture_internal(token=self.team.api_token,event_name=event_name,event_source="person_viewset",@@ -1156,7 +1156,7 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)result.raise_for_status()- # Failures in this codepath (old and new) are ignored here+ # Failures in this codepath are ignoredexcept Exception:passdiff --git a/posthog/api/report.py b/posthog/api/report.pyindex ba96f9ec6069..3133c8b8516d 100644--- a/posthog/api/report.py+++ b/posthog/api/report.py@@ -4,7 +4,7 @@ from django.views.decorators.csrf import csrf_exemptimport structlogfrom rest_framework import status-from posthog.api.capture_dispatch import CaptureRoutedError, capture_batch_internal_routed, capture_internal_routed+from posthog.api.capture import CaptureInternalError, capture_batch_internal, capture_internalfrom posthog.api.csp import process_csp_reportfrom posthog.api.utils import get_tokenfrom posthog.exceptions import generate_exception_response@@ -59,12 +59,12 @@ def get_csp_event(request):token = ""if isinstance(csp_report, list):- result = capture_batch_internal_routed(+ result = capture_batch_internal(events=csp_report, event_source="get_csp_report", token=token, process_person_profile=False)result.raise_for_status()else:- result = capture_internal_routed(+ result = capture_internal(token=token,event_name=csp_report.get("event", ""),event_source="get_csp_report",@@ -77,7 +77,7 @@ def get_csp_event(request):return cors_response(request, HttpResponse(status=status.HTTP_204_NO_CONTENT))- except CaptureRoutedError as cre:+ except CaptureInternalError 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(diff --git a/posthog/api/test/test_capture_dispatch.py b/posthog/api/test/test_capture_dispatch.pydeleted file mode 100644index 09be073baf98..000000000000--- a/posthog/api/test/test_capture_dispatch.py+++ /dev/null@@ -1,258 +0,0 @@-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.pyindex 97e5f9e91f22..2b2b1c96bcff 100644--- a/posthog/api/test/test_capture_internal.py+++ b/posthog/api/test/test_capture_internal.py@@ -1,556 +1,1248 @@+import threadingfrom datetime import UTC, datetimefrom typing import Anyfrom uuid import uuid4-from posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch+from django.test import SimpleTestCase++from parameterized import parameterized+from requests.adapters import HTTPAdapter+from requests.exceptions import ConnectionError as RequestsConnectionError+from posthog.api.capture import (- CAPTURE_INTERNAL_REQUEST_FAILED,+ CAPTURE_V1_OPTION_CONFLICT,+ CAPTURE_V1_REQUEST_SUBMITTED,CaptureInternalError,+ CaptureInternalResult,+ _build_v1_headers,+ _merge_results,+ _normalize_options_and_properties,+ _parse_retry_after,+ _resolve_scalar,capture_batch_internal,capture_internal,+ prepare_capture_internal_batch,)-from posthog.settings.ingestion import (- CAPTURE_INTERNAL_URL,- CAPTURE_REPLAY_INTERNAL_URL,- NEW_ANALYTICS_CAPTURE_ENDPOINT,- REPLAY_CAPTURE_ENDPOINT,-)+from posthog.settings.ingestion import CAPTURE_INTERNAL_URL, CAPTURE_V1_INTERNAL_ENDPOINT++EXPECTED_URL = f"{CAPTURE_INTERNAL_URL}{CAPTURE_V1_INTERNAL_ENDPOINT}"-class InstallCapturePostSpy:- def __init__(self, mock_session_class, status_code=200):+class MockResponse:+ """Lightweight mock for requests.Response with configurable body and headers."""++ def __init__(+ self,+ status_code: int = 200,+ body: dict[str, Any] | None = None,+ headers: dict[str, str] | None = None,+ text: str = "",+ ):self.status_code = status_code- self.spied_calls: list[dict[str, Any]] = []+ self._body = body+ self.headers = headers or {}+ self.text = text or (str(body) if body else "")++ def json(self) -> dict[str, Any]:+ if self._body is None:+ raise ValueError("no json body")+ return self._body- def spy_post(*args, **kwargs):- self.spied_calls.append(- {- "url": args[0],- "event_payload": kwargs["json"],- }- )- mock_response = MagicMock()- mock_response.status_code = self.status_code- return mock_response++class InstallV1Spy:+ """Spy that records POST calls and returns a configurable sequence of responses.++ Thread-safe: concurrent calls from chunked batch submissions are serialized via lock.+ """++ def __init__(self, mock_session_fn: MagicMock, responses: list[MockResponse] | None = None):+ self.calls: list[dict[str, Any]] = []+ self._responses = list(responses or [MockResponse(body={})])+ self._call_idx = 0+ self._lock = threading.Lock()++ def spy_post(url: str, **kwargs: Any) -> MockResponse:+ with self._lock:+ self.calls.append({"url": url, **kwargs})+ resp = self._responses[min(self._call_idx, len(self._responses) - 1)]+ self._call_idx += 1+ return respmock_session = MagicMock()mock_session.post.side_effect = spy_post- mock_session_class.return_value.__enter__.return_value = mock_session+ mock_session.mount = MagicMock()+ mock_session_fn.return_value.__enter__.return_value = mock_session+ self._mock_session = mock_session- def get_calls(self) -> list[dict[str, Any]]:- return self.spied_calls+def _ok_results(*uuids: str) -> dict[str, Any]:+ return {"results": {uid: {"result": "ok"} for uid in uuids}}-class TestCaptureInternal(BaseTest):- """- Tests the new `capture_internal` function.- """- def setUp(self):- super().setUp()+def _make_event(+ event: str = "test_event",+ distinct_id: str = "user-1",+ **extra: Any,+) -> dict[str, Any]:+ out: dict[str, Any] = {"event": event, "distinct_id": distinct_id}+ out.update(extra)+ return out- @patch("posthog.api.capture.internal_requests_session")- def test_capture_internal(self, mock_session_class):- token = "abc123"- distinct_id = "xyz987"- event_name = "test_event"- timestamp = datetime.now(UTC)- test_props = {- "$current_url": "https://example.com",- "$ip": "127.0.0.1",- "$lib": "python",- "$lib_version": "1.0.0",- "$screen_width": 1920,- "$screen_height": 1080,- "some_custom_property": True,- }+class TestBuildV1Headers(SimpleTestCase):+ def test_all_required_headers_present(self) -> None:+ headers = _build_v1_headers("phc_test123", attempt=1)+ assert headers["Authorization"] == "Bearer phc_test123"+ assert headers["Content-Type"] == "application/json"+ assert "posthog-capture-v1-internal" in headers["User-Agent"]+ assert headers["PostHog-Sdk-Info"] == "posthog-capture-v1-internal/1.0"+ assert headers["PostHog-Attempt"] == "1"+ assert len(headers["PostHog-Request-Id"]) == 36+ assert "T" in headers["PostHog-Request-Timestamp"]- spy = InstallCapturePostSpy(mock_session_class)- response = capture_internal(- token=token,- event_name=event_name,- event_source="test_capture_internal",- distinct_id=distinct_id,- timestamp=timestamp,- properties=test_props,- )- assert response.status_code == 200-- spied_calls = spy.get_calls()- assert len(spied_calls) == 1- assert f"{CAPTURE_INTERNAL_URL}{NEW_ANALYTICS_CAPTURE_ENDPOINT}" in spied_calls[0]["url"]- assert spied_calls[0]["event_payload"]["event"] == event_name- assert spied_calls[0]["event_payload"]["distinct_id"] == distinct_id- assert spied_calls[0]["event_payload"]["api_key"] == token- assert spied_calls[0]["event_payload"]["timestamp"] == timestamp.isoformat()- assert spied_calls[0]["event_payload"].get("sent_at", None) is not None- # note: event payload passed to new capture_internal is mutated. here we inject a source marker- assert spied_calls[0]["event_payload"]["properties"]["capture_internal"] is True- assert len(spied_calls[0]["event_payload"]["properties"]) == len(test_props)- # when process_person_profile is False, new capture_internal explicitly sets this on the event- assert spied_calls[0]["event_payload"]["properties"].get("$process_person_profile", None) is not None- assert spied_calls[0]["event_payload"]["properties"]["$process_person_profile"] is False-- @patch("posthog.api.capture.internal_requests_session")- def test_capture_internal_with_sent_at(self, mock_session_class):- token = "abc123"- distinct_id = "xyz987"- event_name = "test_event"- timestamp = datetime.now(UTC)-- test_props = {- "$current_url": "https://example.com",- "$ip": "127.0.0.1",- "$lib": "python",- "$lib_version": "1.0.0",- "$screen_width": 1920,- "$screen_height": 1080,- "some_custom_property": True,- }+ def test_attempt_increments(self) -> None:+ h1 = _build_v1_headers("tok", attempt=1)+ h2 = _build_v1_headers("tok", attempt=3)+ assert h1["PostHog-Attempt"] == "1"+ assert h2["PostHog-Attempt"] == "3"++ def test_request_id_unique_per_call(self) -> None:+ h1 = _build_v1_headers("tok", attempt=1)+ h2 = _build_v1_headers("tok", attempt=1)+ assert h1["PostHog-Request-Id"] != h2["PostHog-Request-Id"]- spy = InstallCapturePostSpy(mock_session_class)- response = capture_internal(- token=token,- event_name=event_name,- event_source="test_capture_internal",- distinct_id=distinct_id,- timestamp=timestamp,- sent_at=timestamp,- properties=test_props,++class TestNormalizeOptionsAndProperties(SimpleTestCase):+ def test_typed_options_propagated(self) -> None:+ ev: dict[str, Any] = {+ "options": {"cookieless_mode": True, "disable_skew_correction": True, "product_tour_id": "tour-1"},+ "properties": {"some_prop": "val"},+ }+ options, sid, wid, props = _normalize_options_and_properties(+ ev, process_person_profile=True, event_source="test")- assert response.status_code == 200-- spied_calls = spy.get_calls()- assert len(spied_calls) == 1- assert f"{CAPTURE_INTERNAL_URL}{NEW_ANALYTICS_CAPTURE_ENDPOINT}" in spied_calls[0]["url"]- assert spied_calls[0]["event_payload"]["event"] == event_name- assert spied_calls[0]["event_payload"]["distinct_id"] == distinct_id- assert spied_calls[0]["event_payload"]["api_key"] == token- assert spied_calls[0]["event_payload"]["timestamp"] == timestamp.isoformat()- assert spied_calls[0]["event_payload"]["sent_at"] == timestamp.isoformat()- # note: event payload passed to new capture_internal is mutated. here we inject a source marker- assert spied_calls[0]["event_payload"]["properties"]["capture_internal"] is True- assert len(spied_calls[0]["event_payload"]["properties"]) == len(test_props)- # when process_person_profile is False, new capture_internal explicitly sets this on the event- assert spied_calls[0]["event_payload"]["properties"].get("$process_person_profile", None) is not None- assert spied_calls[0]["event_payload"]["properties"]["$process_person_profile"] is False-- @patch("posthog.api.capture.internal_requests_session")- def test_capture_internal_with_persons_processing(self, mock_session_class):- token = "abc123"- distinct_id = "xyz987"- event_name = "test_event"- timestamp = datetime.now(UTC)-- test_props = {- "event": event_name,- "distinct_id": distinct_id,- "api_key": token,- "timestamp": timestamp,+ assert options["cookieless_mode"] is True+ assert options["disable_skew_correction"] is True+ assert options["product_tour_id"] == "tour-1"+ assert "process_person_profile" not in options+ assert sid is None+ assert wid is None+ assert props == {"some_prop": "val"}++ def test_legacy_properties_lifted_and_stripped(self) -> None:+ ev: dict[str, Any] = {"properties": {- "$current_url": "https://example.com",- "$ip": "127.0.0.1",- "$lib": "python",- "$lib_version": "1.0.0",- "$screen_width": 1920,- "$screen_height": 1080,- "some_custom_property": True,+ "$cookieless_mode": True,+ "$ignore_sent_at": True,+ "$product_tour_id": "tour-2",+ "$process_person_profile": True,+ "$session_id": "sess-1",+ "$window_id": "win-1",+ "keep_me": 42,},}-- spy = InstallCapturePostSpy(mock_session_class)- response = capture_internal(- token=token,- event_name=event_name,- event_source="test_capture_internal_with_persons_processing",- distinct_id=distinct_id,- timestamp=timestamp,- properties=test_props,- process_person_profile=True,+ options, sid, wid, props = _normalize_options_and_properties(+ ev, process_person_profile=True, event_source="test")- assert response.status_code == 200-- spied_calls = spy.get_calls()- assert len(spied_calls) == 1- assert f"{CAPTURE_INTERNAL_URL}{NEW_ANALYTICS_CAPTURE_ENDPOINT}" in spied_calls[0]["url"]- assert spied_calls[0]["event_payload"]["event"] == event_name- assert spied_calls[0]["event_payload"]["distinct_id"] == distinct_id- assert spied_calls[0]["event_payload"]["api_key"] == token- assert spied_calls[0]["event_payload"]["timestamp"] == timestamp.isoformat()- assert spied_calls[0]["event_payload"].get("sent_at", None) is not None- assert spied_calls[0]["event_payload"]["properties"]["capture_internal"] is True- assert len(spied_calls[0]["event_payload"]["properties"]) == len(test_props)- # when new capture_internal is called with process_person_profile == True, we don't alter the event payload- assert spied_calls[0]["event_payload"]["properties"].get("$process_person_profile", None) is None-- @patch("posthog.api.capture.internal_requests_session")- def test_capture_internal_with_capture_post_server_error(self, mock_session_class):- token = "abc123"- distinct_id = "xyz987"- event_name = "test_event"- timestamp = datetime.now(UTC)-- test_props = {- "$current_url": "https://example.com",- "$ip": "127.0.0.1",- "$lib": "python",- "$lib_version": "1.0.0",- "$screen_width": 1920,- "$screen_height": 1080,- "some_custom_property": True,+ assert options["cookieless_mode"] is True+ assert options["disable_skew_correction"] is True+ assert options["product_tour_id"] == "tour-2"+ assert sid == "sess-1"+ assert wid == "win-1"+ assert "$cookieless_mode" not in props+ assert "$ignore_sent_at" not in props+ assert "$product_tour_id" not in props+ assert "$process_person_profile" not in props+ assert "$session_id" not in props+ assert "$window_id" not in props+ assert props["keep_me"] == 42++ def test_legacy_alias_disable_skew_adjustment_stripped(self) -> None:+ ev: dict[str, Any] = {+ "properties": {"disable_skew_adjustment": True, "other": 1},+ }+ options, _, _, props = _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")+ assert options["disable_skew_correction"] is True+ assert "disable_skew_adjustment" not in props++ def test_explicit_wins_over_legacy_on_conflict(self) -> None:+ ev: dict[str, Any] = {+ "options": {"cookieless_mode": False},+ "session_id": "explicit-sess",+ "properties": {"$cookieless_mode": True, "$session_id": "legacy-sess"},}+ options, sid, _, props = _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")+ assert options["cookieless_mode"] is False+ assert sid == "explicit-sess"+ assert "$cookieless_mode" not in props+ assert "$session_id" not in props++ def test_unknown_option_key_raises(self) -> None:+ ev: dict[str, Any] = {"options": {"bogus_key": True}, "properties": {}}+ with self.assertRaises(CaptureInternalError) as ctx:+ _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")+ assert "unknown option key" in str(ctx.exception)- 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,- event_name=event_name,- event_source="test_capture_internal_with_capture_post_server_error",- distinct_id=distinct_id,- timestamp=timestamp,- properties=test_props,+ def test_process_person_profile_false_forces_option(self) -> None:+ ev: dict[str, Any] = {"properties": {}}+ options, _, _, _ = _normalize_options_and_properties(ev, process_person_profile=False, event_source="test")+ assert options["process_person_profile"] is False++ def test_process_person_profile_true_leaves_unset(self) -> None:+ ev: dict[str, Any] = {"properties": {}}+ options, _, _, _ = _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")+ assert "process_person_profile" not in options++ def test_no_options_when_all_empty_and_ppp_true(self) -> None:+ ev: dict[str, Any] = {"properties": {"keep": 1}}+ options, sid, wid, props = _normalize_options_and_properties(+ ev, process_person_profile=True, event_source="test")- assert response.status_code == 503+ assert options == {}+ assert sid is None+ assert wid is None+ assert props == {"keep": 1}- after = CAPTURE_INTERNAL_REQUEST_FAILED.labels(- event_source="test_capture_internal_with_capture_post_server_error", status_code="503"- )._value.get()+ def test_caller_input_not_mutated(self) -> None:+ original_props = {"$session_id": "s1", "keep": 1}+ ev: dict[str, Any] = {"properties": original_props}+ _normalize_options_and_properties(ev, process_person_profile=False, event_source="test")+ assert "$session_id" in original_props++ @parameterized.expand(+ [+ (+ "option_conflict",+ {"options": {"cookieless_mode": False}, "properties": {"$cookieless_mode": True}},+ "cookieless_mode",+ ),+ ("session_id_conflict", {"session_id": "a", "properties": {"$session_id": "b"}}, "session_id"),+ ("window_id_conflict", {"window_id": "a", "properties": {"$window_id": "b"}}, "window_id"),+ ]+ )+ def test_conflict_increments_metric(self, _name: str, ev: dict[str, Any], field: str) -> None:+ before = CAPTURE_V1_OPTION_CONFLICT.labels(event_source="metric_test", field=field)._value.get()+ _normalize_options_and_properties(ev, process_person_profile=True, event_source="metric_test")+ after = CAPTURE_V1_OPTION_CONFLICT.labels(event_source="metric_test", field=field)._value.get()assert after == before + 1- @patch("posthog.api.capture.internal_requests_session")- def test_capture_internal_replay(self, mock_session_class):- token = "abc123"- distinct_id = "xyz987"- event_name = "$snapshot"- timestamp = datetime.now(UTC)-- test_replay_props = {- "$screen_density": 2.75,- "$screen_height": 2154,- "$screen_width": 1080,- "$app_version": "1.0",- "$app_namespace": "com.posthog.android.sample",- "$app_build": 1,- "$app_name": "PostHog Android Sample",- "$device_manufacturer": "Google",- "$device_model": "sdk_gphone64_arm64",- "$device_name": "emu64a",- "$device_type": "Mobile",- "$os_name": "Android",- "$os_version": "14",- "$lib": "posthog-android",- "$lib_version": "3.0.0-beta.3",- "$is_emulator": True,- "$locale": "en-US",- "$user_agent": "Dalvik/2.1.0 (Linux; U; Android 14; sdk_gphone64_arm64 Build/UPB5.230623.003)",- "$timezone": "Europe/Vienna",- "$network_wifi": True,- "$network_bluetooth": False,- "$network_cellular": False,- "$network_carrier": "T-Mobile",- "$snapshot_data": [- {"timestamp": 1699354586963, "type": 0},- {"timestamp": 1699354586963, "type": 1},- {- "data": {"href": "http://localhost", "width": 1080, "height": 2220},- "timestamp": 1699354586963,- "type": 4,- },- {- "data": {- "node": {- "id": 1,- "type": 0,- "childNodes": [- {"type": 1, "name": "html", "id": 2, "childNodes": []},- {- "id": 3,- "type": 2,- "tagName": "html",- "childNodes": [- {- "id": 5,- "type": 2,- "tagName": "body",- "childNodes": [- {- "type": 2,- "tagName": "canvas",- "id": 7,- "attributes": {- "id": "canvas",- "width": "1080",- "height": "2220",- },- "childNodes": [],- }- ],- }- ],- },- ],- "initialOffset": {"left": 0, "top": 0},- }- },- "timestamp": 1699354586963,- "type": 2,- },- ],- "$session_id": "bceaa9ce-dc9d-4728-8a90-4a7c249604b1",- "$window_id": "31bfffdc-79fc-4504-9ff4-0216a58bf7f6",+ def test_ppp_false_overrides_explicit_true_with_conflict(self) -> None:+ ev: dict[str, Any] = {+ "options": {"process_person_profile": True},+ "properties": {},}+ before = CAPTURE_V1_OPTION_CONFLICT.labels(event_source="ppp_test", field="process_person_profile")._value.get()+ options, _, _, _ = _normalize_options_and_properties(ev, process_person_profile=False, event_source="ppp_test")+ after = CAPTURE_V1_OPTION_CONFLICT.labels(event_source="ppp_test", field="process_person_profile")._value.get()+ assert options["process_person_profile"] is False+ assert after == before + 1+++class TestResolveScalar(SimpleTestCase):+ def test_explicit_wins(self) -> None:+ assert _resolve_scalar("a", "b", field="f", event_source="t") == "a"++ def test_legacy_fallback(self) -> None:+ assert _resolve_scalar(None, "b", field="f", event_source="t") == "b"++ def test_both_none(self) -> None:+ assert _resolve_scalar(None, None, field="f", event_source="t") is None++ def test_no_conflict_when_equal(self) -> None:+ before = CAPTURE_V1_OPTION_CONFLICT.labels(event_source="eq_test", field="f")._value.get()+ _resolve_scalar("same", "same", field="f", event_source="eq_test")+ after = CAPTURE_V1_OPTION_CONFLICT.labels(event_source="eq_test", field="f")._value.get()+ assert after == before+++class TestPrepareCaptureInternalBatch(SimpleTestCase):+ def test_envelope_shape(self) -> None:+ events = [_make_event()]+ payload, uuids = prepare_capture_internal_batch(events, token="tok", event_source="test")+ assert payload["capture_internal"] is True+ assert payload["historical_migration"] is False+ assert "created_at" in payload+ assert len(payload["batch"]) == 1+ assert len(uuids) == 1+ assert payload["batch"][0]["uuid"] == uuids[0]- spy = InstallCapturePostSpy(mock_session_class)- response = capture_internal(- token=token,- event_name=event_name,- event_source="test_capture_internal_replay",- distinct_id=distinct_id,- timestamp=timestamp,- properties=test_replay_props,+ def test_uuid_generated_when_absent(self) -> None:+ events = [_make_event()]+ payload, uuids = prepare_capture_internal_batch(events, token="tok", event_source="test")+ assert len(uuids[0]) == 36+ assert payload["batch"][0]["uuid"] == uuids[0]++ def test_uuid_preserved_when_present(self) -> None:+ uid = str(uuid4())+ events = [_make_event(event_uuid=uid)]+ payload, uuids = prepare_capture_internal_batch(events, token="tok", event_source="test")+ assert uuids[0] == uid+ assert payload["batch"][0]["uuid"] == uid++ def test_options_omitted_when_empty(self) -> None:+ events = [_make_event()]+ payload, _ = prepare_capture_internal_batch(+ events, token="tok", event_source="test", process_person_profile=True)- assert response.status_code == 200-- spied_calls = spy.get_calls()- assert len(spied_calls) == 1- assert f"{CAPTURE_REPLAY_INTERNAL_URL}{REPLAY_CAPTURE_ENDPOINT}" in spied_calls[0]["url"]- assert spied_calls[0]["event_payload"]["event"] == event_name- assert spied_calls[0]["event_payload"]["distinct_id"] == distinct_id- assert spied_calls[0]["event_payload"]["api_key"] == token- assert spied_calls[0]["event_payload"]["timestamp"] == timestamp.isoformat()- assert spied_calls[0]["event_payload"].get("sent_at", None) is not None- assert spied_calls[0]["event_payload"]["properties"]["capture_internal"] is True- assert len(spied_calls[0]["event_payload"]["properties"]) == len(test_replay_props)- assert spied_calls[0]["event_payload"]["properties"].get("$process_person_profile", None) is not None- assert spied_calls[0]["event_payload"]["properties"]["$process_person_profile"] is False-- def test_capture_internal_invalid_token(self):- token = ""- distinct_id = "xyz987"- event_name = "test_event"- timestamp = datetime.now(UTC)-- # no fallback token provided in event payload- test_props = {- "$current_url": "https://example.com",- "$ip": "127.0.0.1",- "$lib": "python",- "$lib_version": "1.0.0",- "$screen_width": 1920,- "$screen_height": 1080,- "some_custom_property": True,- }+ assert "options" not in payload["batch"][0]++ def test_options_present_when_set(self) -> None:+ events = [_make_event(options={"cookieless_mode": True})]+ payload, _ = prepare_capture_internal_batch(events, token="tok", event_source="test")+ assert payload["batch"][0]["options"]["cookieless_mode"] is True++ def test_session_window_as_top_level_fields(self) -> None:+ events = [_make_event(session_id="s1", window_id="w1")]+ payload, _ = prepare_capture_internal_batch(events, token="tok", event_source="test")+ entry = payload["batch"][0]+ assert entry["session_id"] == "s1"+ assert entry["window_id"] == "w1"+ assert "$session_id" not in entry.get("properties", {})+ assert "$window_id" not in entry.get("properties", {})++ def test_distinct_id_fallback_from_properties(self) -> None:+ events = [{"event": "e", "properties": {"distinct_id": "from_props"}}]+ payload, _ = prepare_capture_internal_batch(events, token="tok", event_source="test")+ assert payload["batch"][0]["distinct_id"] == "from_props"++ def test_timestamp_defaults_to_now(self) -> None:+ events = [_make_event()]+ before = datetime.now(UTC).isoformat()+ payload, _ = prepare_capture_internal_batch(events, token="tok", event_source="test")+ after = datetime.now(UTC).isoformat()+ ts = payload["batch"][0]["timestamp"]+ assert before <= ts <= after++ def test_timestamp_non_utc_datetime_converted_correctly(self) -> None:+ from datetime import timedelta, timezone- with self.assertRaises(CaptureInternalError) as e:- capture_internal(- token=token,- event_name=event_name,- event_source="test_capture_internal_invalid_token",- distinct_id=distinct_id,- timestamp=timestamp,- properties=test_props,+ est = timezone(timedelta(hours=-5))+ # 2024-01-15 17:00 EST = 2024-01-15 22:00 UTC+ ts_est = datetime(2024, 1, 15, 17, 0, 0, tzinfo=est)+ events = [_make_event(timestamp=ts_est)]+ payload, _ = prepare_capture_internal_batch(events, token="tok", event_source="test")+ assert payload["batch"][0]["timestamp"] == "2024-01-15T22:00:00+00:00"++ def test_timestamp_naive_datetime_assumed_utc(self) -> None:+ ts_naive = datetime(2024, 6, 1, 12, 0, 0)+ events = [_make_event(timestamp=ts_naive)]+ payload, _ = prepare_capture_internal_batch(events, token="tok", event_source="test")+ assert payload["batch"][0]["timestamp"] == "2024-06-01T12:00:00+00:00"++ @parameterized.expand(+ [+ ("empty_token", "", [{"event": "e", "distinct_id": "u"}], "src", "api token is required"),+ ("no_events", "tok", [], "src", "at least one event is required"),+ ("empty_event_source", "tok", [{"event": "e", "distinct_id": "u"}], "", "event_source is required"),+ ]+ )+ def test_validation_errors(+ self, _name: str, token: str, events: list[dict[str, Any]], event_source: str, fragment: str+ ) -> None:+ with self.assertRaises(CaptureInternalError) as ctx:+ prepare_capture_internal_batch(events, token=token, event_source=event_source)+ assert fragment in str(ctx.exception).lower()++ def test_missing_event_name_raises(self) -> None:+ events = [{"distinct_id": "u1", "properties": {}}]+ with self.assertRaises(CaptureInternalError) as ctx:+ prepare_capture_internal_batch(events, token="tok", event_source="src")+ assert "event name" in str(ctx.exception).lower()++ def test_missing_distinct_id_raises(self) -> None:+ events = [{"event": "e", "properties": {}}]+ with self.assertRaises(CaptureInternalError) as ctx:+ prepare_capture_internal_batch(events, token="tok", event_source="src")+ assert "distinct_id" in str(ctx.exception).lower()++ @parameterized.expand(+ [+ ("$snapshot",),+ ("$performance_event",),+ ("$snapshot_items",),+ ]+ )+ def test_replay_event_names_rejected(self, event_name: str) -> None:+ events = [_make_event(event=event_name)]+ with self.assertRaises(CaptureInternalError) as ctx:+ prepare_capture_internal_batch(events, token="tok", event_source="src")+ assert "replay event" in str(ctx.exception).lower()++ def test_legacy_properties_stripped_in_batch(self) -> None:+ events = [+ _make_event(+ properties={+ "$cookieless_mode": True,+ "$ignore_sent_at": False,+ "$product_tour_id": "t",+ "$process_person_profile": True,+ "$session_id": "s1",+ "$window_id": "w1",+ "keep": 1,+ })- assert (- str(e.exception)- == "capture_internal (test_capture_internal_invalid_token, test_event): API token is required"- )+ ]+ payload, _ = prepare_capture_internal_batch(events, token="tok", event_source="test")+ entry = payload["batch"][0]+ props = entry["properties"]+ for key in (+ "$cookieless_mode",+ "$ignore_sent_at",+ "$product_tour_id",+ "$process_person_profile",+ "$session_id",+ "$window_id",+ ):+ assert key not in props, f"{key} should have been stripped"+ assert props["keep"] == 1+ assert entry["session_id"] == "s1"+ assert entry["window_id"] == "w1"+ assert entry["options"]["cookieless_mode"] is True- def test_capture_internal_invalid_distinct_id(self):- token = "abc123"- distinct_id = ""- event_name = "test_event"- timestamp = datetime.now(UTC)-- # no fallback distinct ID provided in event payload (top-level or in properties)- test_props = {- "$current_url": "https://example.com",- "$ip": "127.0.0.1",- "$lib": "python",- "$lib_version": "1.0.0",- "$screen_width": 1920,- "$screen_height": 1080,- "some_custom_property": True,- }- with self.assertRaises(CaptureInternalError) as e:- capture_internal(- token=token,- event_name=event_name,- event_source="test_capture_internal_invalid_distinct_id",- distinct_id=distinct_id,- timestamp=timestamp,- properties=test_props,+class TestCaptureBatchInternal(SimpleTestCase):+ @patch("posthog.api.capture.internal_requests_session")+ def test_happy_path_batch(self, mock_session_fn: MagicMock) -> None:+ uid1, uid2 = str(uuid4()), str(uuid4())+ events = [+ _make_event(event_uuid=uid1),+ _make_event(event="other", distinct_id="u2", event_uuid=uid2),+ ]+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid1, uid2))])++ result = capture_batch_internal(events=events, token="tok", event_source="happy")++ assert result.status_code == 200+ assert result.succeeded()+ assert set(result.ok) == {uid1, uid2}+ assert not result.dropped+ assert not result.warnings+ assert not result.retried+ assert result.error is None++ assert len(spy.calls) == 1+ assert spy.calls[0]["url"] == EXPECTED_URL++ @patch("posthog.api.capture.internal_requests_session")+ def test_headers_on_initial_request(self, mock_session_fn: MagicMock) -> None:+ uid = str(uuid4())+ events = [_make_event(event_uuid=uid)]+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])++ capture_batch_internal(events=events, token="phc_abc", event_source="hdr")++ headers = spy.calls[0]["headers"]+ assert headers["Authorization"] == "Bearer phc_abc"+ assert headers["Content-Type"] == "application/json"+ assert headers["PostHog-Sdk-Info"] == "posthog-capture-v1-internal/1.0"+ assert headers["PostHog-Attempt"] == "1"+ assert len(headers["PostHog-Request-Id"]) == 36+ assert "T" in headers["PostHog-Request-Timestamp"]++ @patch("posthog.api.capture.internal_requests_session")+ def test_envelope_shape_on_wire(self, mock_session_fn: MagicMock) -> None:+ uid = str(uuid4())+ events = [_make_event(event_uuid=uid)]+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])++ capture_batch_internal(events=events, token="tok", event_source="env")++ body = spy.calls[0]["json"]+ assert body["capture_internal"] is True+ assert body["historical_migration"] is False+ assert "created_at" in body+ assert len(body["batch"]) == 1+ assert body["batch"][0]["uuid"] == uid++ @patch("posthog.api.capture.internal_requests_session")+ def test_options_propagated_to_wire(self, mock_session_fn: MagicMock) -> None:+ uid = str(uuid4())+ events = [+ _make_event(+ event_uuid=uid,+ options={"cookieless_mode": True, "disable_skew_correction": True, "product_tour_id": "t1"},+ session_id="s1",+ window_id="w1",)- assert (- str(e.exception)- == "capture_internal (test_capture_internal_invalid_distinct_id, test_event): distinct ID is required"- )+ ]+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])++ capture_batch_internal(events=events, token="tok", event_source="opt")++ entry = spy.calls[0]["json"]["batch"][0]+ assert entry["options"]["cookieless_mode"] is True+ assert entry["options"]["disable_skew_correction"] is True+ assert entry["options"]["product_tour_id"] == "t1"+ assert entry["session_id"] == "s1"+ assert entry["window_id"] == "w1"+ assert "$cookieless_mode" not in entry["properties"]+ assert "$session_id" not in entry["properties"]++ @patch("posthog.api.capture.internal_requests_session")+ def test_options_omitted_when_none_set_and_ppp_true(self, mock_session_fn: MagicMock) -> None:+ uid = str(uuid4())+ events = [_make_event(event_uuid=uid)]+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])++ capture_batch_internal(events=events, token="tok", event_source="nopt", process_person_profile=True)++ entry = spy.calls[0]["json"]["batch"][0]+ assert "options" not in entry++ @patch("posthog.api.capture.internal_requests_session")+ def test_process_person_profile_false(self, mock_session_fn: MagicMock) -> None:+ uid = str(uuid4())+ events = [_make_event(event_uuid=uid)]+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])++ capture_batch_internal(events=events, token="tok", event_source="ppp")++ entry = spy.calls[0]["json"]["batch"][0]+ assert entry["options"]["process_person_profile"] is False+ assert "$process_person_profile" not in entry["properties"]++ @parameterized.expand(+ [+ ("400_validation", 400, {"error": "invalid_request", "error_description": "bad"}),+ ("401_auth", 401, {"error": "unauthorized", "error_description": "bad token"}),+ ("402_billing", 402, {"error": "billing_limit", "error_description": "quota"}),+ ("408_timeout", 408, {"error": "request_timeout", "error_description": "timeout"}),+ ("413_too_large", 413, {"error": "too_large", "error_description": "payload"}),+ ("415_media", 415, {"error": "unsupported_media", "error_description": "type"}),+ ("429_rate_limit", 429, {"error": "rate_limited", "error_description": "slow down"}),+ ("500_internal", 500, {"error": "internal_error", "error_description": "boom"}),+ ("502_bad_gateway", 502, {"error": "bad_gateway", "error_description": "upstream"}),+ ("503_unavailable", 503, {"error": "service_unavailable", "error_description": "down"}),+ ("504_gateway_timeout", 504, {"error": "gateway_timeout", "error_description": "slow"}),+ ]+ )+ @patch("posthog.api.capture.internal_requests_session")+ def test_whole_request_failures(+ self,+ _name: str,+ status: int,+ error_body: dict[str, str],+ mock_session_fn: MagicMock,+ ) -> None:+ events = [_make_event()]+ InstallV1Spy(mock_session_fn, [MockResponse(status_code=status, body=error_body)])++ result = capture_batch_internal(events=events, token="tok", event_source="fail")- def test_capture_internal_invalid_event_name(self):- event_name = ""- token = "abc123"- distinct_id = "xyz678"- timestamp = datetime.now(UTC)-- # no event name supplied in payload- test_props = {- "$current_url": "https://example.com",- "$ip": "127.0.0.1",- "$lib": "python",- "$lib_version": "1.0.0",- "$screen_width": 1920,- "$screen_height": 1080,- "some_custom_property": True,+ assert result.status_code == status+ assert result.error is not None+ assert result.error["error"] == error_body["error"]+ assert not result.succeeded()++ @patch("posthog.api.capture.internal_requests_session")+ def test_partial_failure_mixed_results(self, mock_session_fn: MagicMock) -> None:+ u_ok, u_drop, u_warn = str(uuid4()), str(uuid4()), str(uuid4())+ events = [+ _make_event(event_uuid=u_ok),+ _make_event(event_uuid=u_drop, event="drop_me"),+ _make_event(event_uuid=u_warn, event="warn_me"),+ ]+ body: dict[str, Any] = {+ "results": {+ u_ok: {"result": "ok"},+ u_drop: {"result": "drop", "details": "quota"},+ u_warn: {"result": "warning", "details": "sdk old"},+ }}+ InstallV1Spy(mock_session_fn, [MockResponse(body=body)])- with self.assertRaises(CaptureInternalError) as e:- capture_internal(- token=token,- event_name=event_name,- event_source="test_capture_internal_invalid_event_name",- distinct_id=distinct_id,- timestamp=timestamp,- properties=test_props,- )- assert str(e.exception) == "capture_internal (test_capture_internal_invalid_event_name): event name is required"-- @patch("posthog.api.capture.internal_requests_session")- def test_capture_batch_internal(self, mock_session_class):- token = "abc123"- base_event_name = "test_event"- timestamp = datetime.now(UTC).isoformat()-- test_events = []- for i in range(10):- test_events.append(- {- "event": f"{base_event_name}_{i}",- "distinct_id": str(uuid4()),- "api_key": token,- "timestamp": timestamp,- "properties": {- "$current_url": "https://example.com",- "$ip": "127.0.0.1",- "$lib": "python",- "$lib_version": "1.0.0",- "$screen_width": 1920,- "$screen_height": 1080,- "some_custom_property": True,- },+ result = capture_batch_internal(events=events, token="tok", event_source="partial")++ assert result.status_code == 200+ assert u_ok in result.ok+ assert u_drop in result.dropped+ assert u_warn in result.warnings+ assert not result.retried+ assert not result.succeeded()++ @patch("posthog.api.capture.time.sleep")+ @patch("posthog.api.capture.internal_requests_session")+ def test_auto_resubmit_retry_events(self, mock_session_fn: MagicMock, mock_sleep: MagicMock) -> None:+ u_ok, u_retry = str(uuid4()), str(uuid4())+ events = [+ _make_event(event_uuid=u_ok),+ _make_event(event_uuid=u_retry, event="retryable"),+ ]+ first_response = MockResponse(+ body={+ "results": {+ u_ok: {"result": "ok"},+ u_retry: {"result": "retry", "details": "busy"},}- )+ },+ headers={"Retry-After": "2"},+ )+ second_response = MockResponse(+ body={"results": {u_retry: {"result": "ok"}}},+ )+ spy = InstallV1Spy(mock_session_fn, [first_response, second_response])- spy = InstallCapturePostSpy(mock_session_class)- resp_futures = capture_batch_internal(- events=test_events, event_source="test_capture_batch_internal", token=token, process_person_profile=False+ result = capture_batch_internal(events=events, token="tok", event_source="resub")++ assert result.status_code == 200+ assert result.succeeded()+ assert set(result.ok) == {u_ok, u_retry}+ assert not result.retried++ assert len(spy.calls) == 2+ mock_sleep.assert_called_once_with(2.0)++ # Second request should have incremented attempt and only retry uuid.+ second_headers = spy.calls[1]["headers"]+ assert second_headers["PostHog-Attempt"] == "2"+ assert second_headers["PostHog-Request-Id"] != spy.calls[0]["headers"]["PostHog-Request-Id"]+ second_batch = spy.calls[1]["json"]["batch"]+ assert len(second_batch) == 1+ assert second_batch[0]["uuid"] == u_retry++ @patch("posthog.api.capture.time.sleep")+ @patch("posthog.api.capture.internal_requests_session")+ def test_bounded_retries_exhausted(self, mock_session_fn: MagicMock, mock_sleep: MagicMock) -> None:+ u_retry = str(uuid4())+ events = [_make_event(event_uuid=u_retry)]+ persistent_retry = MockResponse(+ body={"results": {u_retry: {"result": "retry"}}},+ headers={"Retry-After": "1"},+ )+ InstallV1Spy(mock_session_fn, [persistent_retry, persistent_retry, persistent_retry])++ result = capture_batch_internal(events=events, token="tok", event_source="bounded", max_attempts=2)++ assert result.status_code == 200+ assert u_retry in result.retried+ assert not result.succeeded()++ @patch("posthog.api.capture.time.sleep")+ @patch("posthog.api.capture.internal_requests_session")+ def test_retry_after_capped(self, mock_session_fn: MagicMock, mock_sleep: MagicMock) -> None:+ u_retry = str(uuid4())+ events = [_make_event(event_uuid=u_retry)]+ resp1 = MockResponse(+ body={"results": {u_retry: {"result": "retry"}}},+ headers={"Retry-After": "9999"},+ )+ resp2 = MockResponse(body=_ok_results(u_retry))+ InstallV1Spy(mock_session_fn, [resp1, resp2])++ capture_batch_internal(events=events, token="tok", event_source="cap")++ mock_sleep.assert_called_once_with(5.0)++ @patch("posthog.api.capture.internal_requests_session")+ def test_headers_on_resubmit(self, mock_session_fn: MagicMock) -> None:+ u_retry = str(uuid4())+ events = [_make_event(event_uuid=u_retry)]+ resp1 = MockResponse(+ body={"results": {u_retry: {"result": "retry"}}},+ headers={"Retry-After": "0"},)+ resp2 = MockResponse(body=_ok_results(u_retry))+ spy = InstallV1Spy(mock_session_fn, [resp1, resp2])++ with patch("posthog.api.capture.time.sleep"):+ capture_batch_internal(events=events, token="tok", event_source="rh")- for future in resp_futures:- resp = future.result()- assert resp.status_code == 200-- spied_calls = spy.get_calls()- assert len(spied_calls) == 10-- # ensure stable test assertions against test_events list- spied_calls = sorted(spied_calls, key=lambda evt: evt["event_payload"]["event"])-- for i in range(10):- assert f"{CAPTURE_INTERNAL_URL}{NEW_ANALYTICS_CAPTURE_ENDPOINT}" in spied_calls[i]["url"]- assert spied_calls[i]["event_payload"]["event"] == f"{base_event_name}_{i}"- assert spied_calls[i]["event_payload"]["distinct_id"] == test_events[i]["distinct_id"]- assert spied_calls[i]["event_payload"]["api_key"] == token- assert spied_calls[i]["event_payload"]["timestamp"] == timestamp- assert spied_calls[i]["event_payload"].get("sent_at", None) is not None- assert len(spied_calls[i]["event_payload"]["properties"]) == len(test_events[i]["properties"])- # every event in the batch should be marked asinternally-sourced- assert spied_calls[i]["event_payload"]["properties"]["capture_internal"] is True- # since process_person_profile is False, it should have been injected into the event- assert spied_calls[i]["event_payload"]["properties"].get("$process_person_profile", None) is not None- assert spied_calls[i]["event_payload"]["properties"]["$process_person_profile"] is False-- def test_capture_batch_internal_invalid_payload(self):- token = "abc123"- base_event_name = "test_event"- timestamp = datetime.now(UTC).isoformat()-- test_events = []- for i in range(3):- test_events.append(- {- "event": f"{base_event_name}_{i}",- # without a distinct_id on each event, this won't go well- "api_key": token,- "timestamp": timestamp,- "properties": {- "$current_url": "https://example.com",- "$ip": "127.0.0.1",- "$lib": "python",- "$lib_version": "1.0.0",- "$screen_width": 1920,- "$screen_height": 1080,- "some_custom_property": True,- },+ h1 = spy.calls[0]["headers"]+ h2 = spy.calls[1]["headers"]+ assert h1["PostHog-Attempt"] == "1"+ assert h2["PostHog-Attempt"] == "2"+ assert h1["PostHog-Request-Id"] != h2["PostHog-Request-Id"]+ for h in (h1, h2):+ assert "Authorization" in h+ assert "PostHog-Sdk-Info" in h+ assert "PostHog-Request-Timestamp" in h++ @patch("posthog.api.capture.internal_requests_session")+ def test_transport_retry_adapter_mounted(self, mock_session_fn: MagicMock) -> None:+ uid = str(uuid4())+ events = [_make_event(event_uuid=uid)]+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])++ capture_batch_internal(events=events, token="tok", event_source="mount")++ spy._mock_session.mount.assert_called_once()+ args = spy._mock_session.mount.call_args+ assert args[0][0] == EXPECTED_URL+ adapter = args[0][1]+ assert isinstance(adapter, HTTPAdapter)++ @patch("posthog.api.capture.internal_requests_session")+ def test_all_drop_batch(self, mock_session_fn: MagicMock) -> None:+ u1, u2 = str(uuid4()), str(uuid4())+ events = [_make_event(event_uuid=u1), _make_event(event_uuid=u2)]+ body: dict[str, Any] = {+ "results": {+ u1: {"result": "drop", "details": "quota"},+ u2: {"result": "drop", "details": "restricted"},+ }+ }+ InstallV1Spy(mock_session_fn, [MockResponse(body=body)])++ result = capture_batch_internal(events=events, token="tok", event_source="alldrop")++ assert result.status_code == 200+ assert not result.succeeded()+ assert set(result.dropped) == {u1, u2}+ assert not result.ok+ assert not result.retried++ @patch("posthog.api.capture.time.sleep")+ @patch("posthog.api.capture.internal_requests_session")+ def test_mixed_retry_drop_warn_resubmits_only_retry(+ self, mock_session_fn: MagicMock, mock_sleep: MagicMock+ ) -> None:+ u_drop, u_warn, u_retry = str(uuid4()), str(uuid4()), str(uuid4())+ events = [+ _make_event(event_uuid=u_drop),+ _make_event(event_uuid=u_warn),+ _make_event(event_uuid=u_retry),+ ]+ first_resp = MockResponse(+ body={+ "results": {+ u_drop: {"result": "drop"},+ u_warn: {"result": "warning"},+ u_retry: {"result": "retry"},}- )+ },+ headers={"Retry-After": "0"},+ )+ second_resp = MockResponse(body={"results": {u_retry: {"result": "ok"}}})+ spy = InstallV1Spy(mock_session_fn, [first_resp, second_resp])++ result = capture_batch_internal(events=events, token="tok", event_source="mix")- resp_futures = capture_batch_internal(- events=test_events,- event_source="test_capture_batch_internal_invalid_payload",- token=token,- process_person_profile=False,+ assert len(spy.calls) == 2+ assert u_drop in result.dropped+ assert u_warn in result.warnings+ assert u_retry in result.ok+ assert not result.retried++ @patch("posthog.api.capture.internal_requests_session")+ def test_empty_results_map_marks_unaccounted(self, mock_session_fn: MagicMock) -> None:+ uid = str(uuid4())+ events = [_make_event(event_uuid=uid)]+ InstallV1Spy(mock_session_fn, [MockResponse(body={"results": {}})])++ result = capture_batch_internal(events=events, token="tok", event_source="empty")++ assert result.status_code == 200+ assert uid in result.unaccounted+ assert not result.ok+ assert not result.succeeded()++ @patch("posthog.api.capture.internal_requests_session")+ def test_non_json_200_body(self, mock_session_fn: MagicMock) -> None:+ events = [_make_event()]+ InstallV1Spy(mock_session_fn, [MockResponse(status_code=200, body=None, text="not json")])++ result = capture_batch_internal(events=events, token="tok", event_source="badjson")++ assert result.status_code == 200+ assert result.error is not None+ assert result.error["error"] == "invalid_json"+ assert not result.succeeded()++ @patch("posthog.api.capture.time.sleep")+ @patch("posthog.api.capture.internal_requests_session")+ def test_retry_without_retry_after_header(self, mock_session_fn: MagicMock, mock_sleep: MagicMock) -> None:+ u_retry = str(uuid4())+ events = [_make_event(event_uuid=u_retry)]+ resp1 = MockResponse(+ body={"results": {u_retry: {"result": "retry"}}},+ )+ resp2 = MockResponse(body=_ok_results(u_retry))+ InstallV1Spy(mock_session_fn, [resp1, resp2])++ result = capture_batch_internal(events=events, token="tok", event_source="noheader")++ assert result.succeeded()+ mock_sleep.assert_not_called()++ @patch("posthog.api.capture.time.sleep")+ @patch("posthog.api.capture.internal_requests_session")+ def test_resubmit_preserves_envelope_metadata(self, mock_session_fn: MagicMock, mock_sleep: MagicMock) -> None:+ u_retry = str(uuid4())+ events = [_make_event(event_uuid=u_retry)]+ resp1 = MockResponse(+ body={"results": {u_retry: {"result": "retry"}}},+ headers={"Retry-After": "0"},+ )+ resp2 = MockResponse(body=_ok_results(u_retry))+ spy = InstallV1Spy(mock_session_fn, [resp1, resp2])++ capture_batch_internal(+ events=events,+ token="tok",+ event_source="envelope",+ historical_migration=True,+ )++ body1 = spy.calls[0]["json"]+ body2 = spy.calls[1]["json"]+ assert body2["capture_internal"] is True+ assert body2["historical_migration"] is True+ assert body2["created_at"] == body1["created_at"]++ @patch("posthog.api.capture.internal_requests_session")+ def test_max_attempts_one_means_no_resubmit(self, mock_session_fn: MagicMock) -> None:+ u_retry = str(uuid4())+ events = [_make_event(event_uuid=u_retry)]+ resp = MockResponse(+ body={"results": {u_retry: {"result": "retry"}}},+ headers={"Retry-After": "0"},)- assert len(resp_futures) == 3-- for future in resp_futures:- with self.assertRaises(CaptureInternalError) as e:- future.result()- err_msg = str(e.exception)- assert "capture_internal" in err_msg- assert "test_capture_batch_internal_invalid_payload" in err_msg- assert "distinct ID is required" in err_msg-- @patch("posthog.api.capture.internal_requests_session")- def test_capture_batch_internal_bad_req(self, mock_session_class):- token = "abc123"- base_event_name = "test_event"- timestamp = datetime.now(UTC).isoformat()-- test_events = []- for i in range(3):- test_events.append(- {- "event": f"{base_event_name}_{i}",- "distinct_id": "xyz456",- "api_key": token,- "timestamp": timestamp,- "properties": {- "$current_url": "https://example.com",- "$ip": "127.0.0.1",- "$lib": "python",- "$lib_version": "1.0.0",- "$screen_width": 1920,- "$screen_height": 1080,- "some_custom_property": True,- },+ spy = InstallV1Spy(mock_session_fn, [resp])++ result = capture_batch_internal(events=events, token="tok", event_source="noretry", max_attempts=1)++ assert len(spy.calls) == 1+ assert u_retry in result.retried+ assert not result.succeeded()++ @patch("posthog.api.capture.time.sleep")+ @patch("posthog.api.capture.internal_requests_session")+ def test_drop_round1_retry_ok_round2_merged(self, mock_session_fn: MagicMock, mock_sleep: MagicMock) -> None:+ u_drop, u_retry = str(uuid4()), str(uuid4())+ events = [+ _make_event(event_uuid=u_drop),+ _make_event(event_uuid=u_retry),+ ]+ resp1 = MockResponse(+ body={+ "results": {+ u_drop: {"result": "drop", "details": "quota"},+ u_retry: {"result": "retry"},}- )+ },+ headers={"Retry-After": "0"},+ )+ resp2 = MockResponse(body={"results": {u_retry: {"result": "ok"}}})+ InstallV1Spy(mock_session_fn, [resp1, resp2])++ result = capture_batch_internal(events=events, token="tok", event_source="merge")++ assert u_drop in result.dropped+ assert u_retry in result.ok+ assert not result.retried+ assert result.results[u_drop]["result"] == "drop"+ assert result.results[u_retry]["result"] == "ok"++ @parameterized.expand(+ [+ ("unaccounted_uuid", {}, "unaccounted", False),+ ("unknown_status", {"result": "new_fancy_status"}, "unaccounted", False),+ ("drop", {"result": "drop"}, "dropped", False),+ ("warning", {"result": "warning"}, "warnings", True),+ ]+ )+ @patch("posthog.api.capture.internal_requests_session")+ def test_terminal_categorization(+ self,+ _name: str,+ entry: dict[str, Any],+ expected_bucket: str,+ expect_succeeded: bool,+ mock_session_fn: MagicMock,+ ) -> None:+ uid = str(uuid4())+ events = [_make_event(event_uuid=uid)]+ results = {uid: entry} if entry else {}+ InstallV1Spy(mock_session_fn, [MockResponse(body={"results": results})])++ result = capture_batch_internal(events=events, token="tok", event_source="cat")++ assert uid in getattr(result, expected_bucket)+ assert result.succeeded() == expect_succeeded++ @patch("posthog.api.capture.internal_requests_session")+ def test_transport_exception_returns_structured_error(self, mock_session_fn: MagicMock) -> None:+ events = [_make_event()]+ mock_session = MagicMock()+ mock_session.post.side_effect = RequestsConnectionError("connection refused")+ mock_session.mount = MagicMock()+ mock_session_fn.return_value.__enter__.return_value = mock_session++ result = capture_batch_internal(events=events, token="tok", event_source="transport")++ assert result.status_code == 0+ assert result.error is not None+ assert result.error["error"] == "transport_error"+ assert "connection refused" in result.error["error_description"]+ assert not result.succeeded()++ @patch("posthog.api.capture.internal_requests_session")+ def test_transport_failure_marks_events_unaccounted(self, mock_session_fn: MagicMock) -> None:+ u1, u2 = str(uuid4()), str(uuid4())+ events = [_make_event(event_uuid=u1), _make_event(event_uuid=u2)]+ mock_session = MagicMock()+ mock_session.post.side_effect = RequestsConnectionError("connection refused")+ mock_session.mount = MagicMock()+ mock_session_fn.return_value.__enter__.return_value = mock_session++ result = capture_batch_internal(events=events, token="tok", event_source="unacct")++ assert set(result.unaccounted) == {u1, u2}+ assert not result.ok++ @patch("posthog.api.capture.time.sleep")+ @patch("posthog.api.capture.internal_requests_session")+ def test_request_submitted_metric_counts_each_attempt(+ self, mock_session_fn: MagicMock, mock_sleep: MagicMock+ ) -> None:+ u_retry = str(uuid4())+ events = [_make_event(event_uuid=u_retry)]+ resp1 = MockResponse(body={"results": {u_retry: {"result": "retry"}}}, headers={"Retry-After": "0"})+ resp2 = MockResponse(body=_ok_results(u_retry))+ InstallV1Spy(mock_session_fn, [resp1, resp2])++ before = CAPTURE_V1_REQUEST_SUBMITTED.labels(event_source="reqmetric")._value.get()+ capture_batch_internal(events=events, token="tok", event_source="reqmetric")+ after = CAPTURE_V1_REQUEST_SUBMITTED.labels(event_source="reqmetric")._value.get()++ # Two HTTP POSTs: initial + one retry round.+ assert after == before + 2+++class TestParseRetryAfter(SimpleTestCase):+ @parameterized.expand(+ [+ ("none", None, 0.0),+ ("empty_string", "", 0.0),+ ("zero", "0", 0.0),+ ("positive", "2", 2.0),+ ("float_value", "1.5", 1.5),+ ("capped", "9999", 5.0),+ ("negative_clamped", "-1", 0.0),+ ("non_numeric_fallback", "garbage", 1.0),+ ]+ )+ def test_parse_retry_after(self, _name: str, header: str | None, expected: float) -> None:+ assert _parse_retry_after(header) == expected+++class TestCaptureInternal(SimpleTestCase):+ @patch("posthog.api.capture.internal_requests_session")+ def test_single_event_wrapper(self, mock_session_fn: MagicMock) -> None:+ uid = str(uuid4())+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])++ result = capture_internal(+ token="tok",+ event_name="single_test",+ event_source="single",+ distinct_id="u1",+ event_uuid=uid,+ session_id="s1",+ window_id="w1",+ options={"cookieless_mode": True},+ properties={"custom": "val"},+ )++ assert result.status_code == 200+ assert uid in result.ok++ entry = spy.calls[0]["json"]["batch"][0]+ assert entry["event"] == "single_test"+ assert entry["distinct_id"] == "u1"+ assert entry["uuid"] == uid+ assert entry["session_id"] == "s1"+ assert entry["window_id"] == "w1"+ assert entry["options"]["cookieless_mode"] is True+ assert entry["properties"]["custom"] == "val"++ @patch("posthog.api.capture.internal_requests_session")+ def test_single_minimal(self, mock_session_fn: MagicMock) -> None:+ InstallV1Spy(mock_session_fn, [MockResponse(body={"results": {}})])++ result = capture_internal(+ token="tok",+ event_name="minimal",+ event_source="min",+ distinct_id="u1",+ )+ assert result.status_code == 200+++class TestCaptureInternalResult(SimpleTestCase):+ def test_succeeded_true(self) -> None:+ r = CaptureInternalResult(status_code=200, ok=["a", "b"])+ assert r.succeeded()- InstallCapturePostSpy(mock_session_class, status_code=400)- resp_futures = capture_batch_internal(- events=test_events,- event_source="test_capture_batch_internal_bad_req",- token=token,- process_person_profile=False,+ @parameterized.expand(+ [+ ("error", {"error": {"error": "bad"}}, {}),+ ("dropped", {}, {"dropped": ["a"]}),+ ("retried", {}, {"retried": ["a"]}),+ ("unaccounted", {}, {"unaccounted": ["a"]}),+ ]+ )+ def test_succeeded_false(self, _name: str, kwargs: dict[str, Any], list_kwargs: dict[str, Any]) -> None:+ r = CaptureInternalResult(status_code=200, **kwargs, **list_kwargs)+ assert not r.succeeded()++ def test_terminal_failures_includes_all_buckets(self) -> None:+ r = CaptureInternalResult(+ status_code=200,+ results={+ "a": {"result": "drop"},+ "b": {"result": "retry"},+ "c": {"result": "unaccounted"},+ },+ dropped=["a"],+ retried=["b"],+ unaccounted=["c"],)- assert len(resp_futures) == 3+ failures = r.terminal_failures()+ assert set(failures.keys()) == {"a", "b", "c"}++ def test_raise_for_status_on_error(self) -> None:+ r = CaptureInternalResult(status_code=503, error={"error": "server_error", "error_description": "down"})+ with self.assertRaises(CaptureInternalError):+ r.raise_for_status()++ @parameterized.expand(+ [+ ("dropped", {"dropped": ["a"]}),+ ("retried", {"retried": ["a"]}),+ ("unaccounted", {"unaccounted": ["a"]}),+ ]+ )+ def test_raise_for_status_on_partial_failure(self, _name: str, kwargs: dict[str, Any]) -> None:+ r = CaptureInternalResult(status_code=200, **kwargs)+ with self.assertRaises(CaptureInternalError):+ r.raise_for_status()++ def test_raise_for_status_noop_on_success(self) -> None:+ r = CaptureInternalResult(status_code=200, ok=["a"])+ r.raise_for_status()+++# --------------------------------------------------------------------------- #+# Helpers for chunking tests+# --------------------------------------------------------------------------- #+++def _make_realistic_event(index: int = 0, **overrides: Any) -> dict[str, Any]:+ """Generate an event dict with realistic properties (5-10 fields)."""+ uid = str(uuid4())+ ev: dict[str, Any] = {+ "event": f"test_event_{index % 5}",+ "distinct_id": f"user-{index % 50}",+ "event_uuid": uid,+ "timestamp": datetime(2025, 6, 15, 12, 0, index % 60, tzinfo=UTC).isoformat(),+ "session_id": f"sess-{index % 20}",+ "properties": {+ "url": f"https://app.example.com/page/{index}",+ "referrer": "https://google.com",+ "screen_width": 1920,+ "screen_height": 1080,+ "browser": "Chrome",+ "os": "macOS",+ "lib_version": "1.42.0",+ "custom_metric": index * 3.14,+ },+ }+ ev.update(overrides)+ return ev+++def _make_batch(size: int) -> list[dict[str, Any]]:+ return [_make_realistic_event(i) for i in range(size)]+++# --------------------------------------------------------------------------- #+# Chunking orchestration tests+# --------------------------------------------------------------------------- #+++class TestBatchChunking(SimpleTestCase):+ @patch("posthog.api.capture.CAPTURE_INTERNAL_BATCH_CHUNK_SIZE", 200)+ @patch("posthog.api.capture.CAPTURE_INTERNAL_MAX_WORKERS", 8)+ @patch("posthog.api.capture.internal_requests_session")+ def test_small_batch_no_chunking(self, mock_session_fn: MagicMock) -> None:+ events = _make_batch(200)+ uuids = [e["event_uuid"] for e in events]+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(*uuids))])++ result = capture_batch_internal(events=events, token="tok", event_source="small")++ assert result.succeeded()+ assert len(result.ok) == 200+ assert len(spy.calls) == 1++ @patch("posthog.api.capture.CAPTURE_INTERNAL_BATCH_CHUNK_SIZE", 200)+ @patch("posthog.api.capture.CAPTURE_INTERNAL_MAX_WORKERS", 8)+ @patch("posthog.api.capture.internal_requests_session")+ def test_boundary_201_triggers_chunking(self, mock_session_fn: MagicMock) -> None:+ events = _make_batch(201)+ uuids = [e["event_uuid"] for e in events]+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(*uuids))])++ result = capture_batch_internal(events=events, token="tok", event_source="boundary")++ assert result.succeeded()+ assert len(result.ok) == 201+ # 2 chunks: 200 + 1+ assert len(spy.calls) == 2+ batch_sizes = sorted(len(c["json"]["batch"]) for c in spy.calls)+ assert batch_sizes == [1, 200]++ @patch("posthog.api.capture.CAPTURE_INTERNAL_BATCH_CHUNK_SIZE", 200)+ @patch("posthog.api.capture.CAPTURE_INTERNAL_MAX_WORKERS", 8)+ @patch("posthog.api.capture.internal_requests_session")+ def test_large_batch_450_events_three_chunks(self, mock_session_fn: MagicMock) -> None:+ events = _make_batch(450)+ uuids = [e["event_uuid"] for e in events]+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(*uuids))])++ result = capture_batch_internal(events=events, token="tok", event_source="large")++ assert result.succeeded()+ assert len(result.ok) == 450+ assert len(spy.calls) == 3+ batch_sizes = sorted(len(c["json"]["batch"]) for c in spy.calls)+ assert batch_sizes == [50, 200, 200]++ @patch("posthog.api.capture.CAPTURE_INTERNAL_BATCH_CHUNK_SIZE", 200)+ @patch("posthog.api.capture.CAPTURE_INTERNAL_MAX_WORKERS", 8)+ @patch("posthog.api.capture.internal_requests_session")+ def test_partial_chunk_failure_preserves_successful_chunks(self, mock_session_fn: MagicMock) -> None:+ events = _make_batch(400)+ chunk1_uuids = [e["event_uuid"] for e in events[:200]]+ lock = threading.Lock()++ def spy_post(url: str, **kwargs: Any) -> MockResponse:+ with lock:+ pass+ batch_uuids = [e["uuid"] for e in kwargs["json"]["batch"]]+ if set(batch_uuids) & set(chunk1_uuids):+ return MockResponse(body=_ok_results(*batch_uuids))+ else:+ raise RequestsConnectionError("connection refused")++ mock_session = MagicMock()+ mock_session.post.side_effect = spy_post+ mock_session.mount = MagicMock()+ mock_session_fn.return_value.__enter__.return_value = mock_session++ result = capture_batch_internal(events=events, token="tok", event_source="partial")++ assert not result.succeeded()+ assert len(result.ok) == 200+ assert result.error is not None++ @patch("posthog.api.capture.CAPTURE_INTERNAL_BATCH_CHUNK_SIZE", 200)+ @patch("posthog.api.capture.CAPTURE_INTERNAL_MAX_WORKERS", 8)+ @patch("posthog.api.capture.internal_requests_session")+ def test_all_chunks_fail(self, mock_session_fn: MagicMock) -> None:+ events = _make_batch(400)++ mock_session = MagicMock()+ mock_session.post.side_effect = RequestsConnectionError("network down")+ mock_session.mount = MagicMock()+ mock_session_fn.return_value.__enter__.return_value = mock_session++ result = capture_batch_internal(events=events, token="tok", event_source="allfail")++ assert not result.succeeded()+ assert result.error is not None+ assert result.error["error"] == "transport_error"++ @patch("posthog.api.capture.CAPTURE_INTERNAL_BATCH_CHUNK_SIZE", 200)+ @patch("posthog.api.capture.CAPTURE_INTERNAL_MAX_WORKERS", 8)+ @patch("posthog.api.capture.internal_requests_session")+ def test_chunked_results_merge_correctly(self, mock_session_fn: MagicMock) -> None:+ events = _make_batch(400)+ chunk1_uuids = [e["event_uuid"] for e in events[:200]]+ chunk2_uuids = [e["event_uuid"] for e in events[200:]]++ def spy_post(url: str, **kwargs: Any) -> MockResponse:+ batch_uuids = [e["uuid"] for e in kwargs["json"]["batch"]]+ results: dict[str, Any] = {}+ for uid in batch_uuids:+ if uid in chunk1_uuids:+ results[uid] = {"result": "ok"}+ else:+ results[uid] = {"result": "drop", "details": "quota"}+ return MockResponse(body={"results": results})++ mock_session = MagicMock()+ mock_session.post.side_effect = spy_post+ mock_session.mount = MagicMock()+ mock_session_fn.return_value.__enter__.return_value = mock_session++ result = capture_batch_internal(events=events, token="tok", event_source="merge")++ assert not result.succeeded()+ assert len(result.ok) == 200+ assert len(result.dropped) == 200+ assert set(result.ok) == set(chunk1_uuids)+ assert set(result.dropped) == set(chunk2_uuids)++ @patch("posthog.api.capture.CAPTURE_INTERNAL_BATCH_CHUNK_SIZE", 200)+ @patch("posthog.api.capture.CAPTURE_INTERNAL_MAX_WORKERS", 8)+ @patch("posthog.api.capture.internal_requests_session")+ def test_chunked_historical_migration_flag_propagated(self, mock_session_fn: MagicMock) -> None:+ events = _make_batch(201)+ uuids = [e["event_uuid"] for e in events]+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(*uuids))])++ capture_batch_internal(events=events, token="tok", event_source="hist", historical_migration=True)++ for call in spy.calls:+ assert call["json"]["historical_migration"] is True+ assert call["json"]["capture_internal"] is True+++class TestMergeResults(SimpleTestCase):+ def test_merge_all_success(self) -> None:+ r1 = CaptureInternalResult(status_code=200, results={"a": {"result": "ok"}}, ok=["a"])+ r2 = CaptureInternalResult(status_code=200, results={"b": {"result": "ok"}}, ok=["b"])++ merged = _merge_results([r1, r2])++ assert merged.status_code == 200+ assert merged.succeeded()+ assert set(merged.ok) == {"a", "b"}+ assert merged.error is None++ def test_merge_with_one_error(self) -> None:+ r1 = CaptureInternalResult(status_code=200, results={"a": {"result": "ok"}}, ok=["a"])+ r2 = CaptureInternalResult(status_code=0, error={"error": "transport_error", "error_description": "timeout"})++ merged = _merge_results([r1, r2])++ assert merged.status_code == 0+ assert not merged.succeeded()+ assert "a" in merged.ok+ assert merged.error is not None++ def test_merge_mixed_buckets(self) -> None:+ r1 = CaptureInternalResult(+ status_code=200,+ results={"a": {"result": "ok"}, "b": {"result": "drop"}},+ ok=["a"],+ dropped=["b"],+ )+ r2 = CaptureInternalResult(+ status_code=200,+ results={"c": {"result": "warning"}, "d": {"result": "retry"}},+ warnings=["c"],+ retried=["d"],+ )++ merged = _merge_results([r1, r2])- for future in resp_futures:- resp = future.result()- assert resp.status_code == 400+ assert merged.ok == ["a"]+ assert merged.dropped == ["b"]+ assert merged.warnings == ["c"]+ assert merged.retried == ["d"]+ assert set(merged.results.keys()) == {"a", "b", "c", "d"}diff --git a/posthog/api/test/test_capture_v1_internal.py b/posthog/api/test/test_capture_v1_internal.pydeleted file mode 100644index 9e0e4fa8b4d0..000000000000--- a/posthog/api/test/test_capture_v1_internal.py+++ /dev/null@@ -1,980 +0,0 @@-from datetime import UTC, datetime-from typing import Any-from uuid import uuid4--from unittest.mock import MagicMock, patch--from django.test import SimpleTestCase--from parameterized import parameterized-from requests.adapters import HTTPAdapter-from requests.exceptions import ConnectionError as RequestsConnectionError--from posthog.api.capture_v1 import (- CAPTURE_V1_OPTION_CONFLICT,- CaptureV1InternalError,- CaptureV1Result,- _build_v1_headers,- _normalize_options_and_properties,- _parse_retry_after,- _resolve_scalar,- capture_v1_batch_internal,- capture_v1_internal,- prepare_capture_v1_batch,-)-from posthog.settings.ingestion import CAPTURE_INTERNAL_URL, CAPTURE_V1_INTERNAL_ENDPOINT--EXPECTED_URL = f"{CAPTURE_INTERNAL_URL}{CAPTURE_V1_INTERNAL_ENDPOINT}"---class MockResponse:- """Lightweight mock for requests.Response with configurable body and headers."""-- def __init__(- self,- status_code: int = 200,- body: dict[str, Any] | None = None,- headers: dict[str, str] | None = None,- text: str = "",- ):- self.status_code = status_code- self._body = body- self.headers = headers or {}- self.text = text or (str(body) if body else "")-- def json(self) -> dict[str, Any]:- if self._body is None:- raise ValueError("no json body")- return self._body---class InstallV1Spy:- """Spy that records POST calls and returns a configurable sequence of responses."""-- def __init__(self, mock_session_fn: MagicMock, responses: list[MockResponse] | None = None):- self.calls: list[dict[str, Any]] = []- self._responses = list(responses or [MockResponse(body={})])- self._call_idx = 0-- def spy_post(url: str, **kwargs: Any) -> MockResponse:- self.calls.append({"url": url, **kwargs})- resp = self._responses[min(self._call_idx, len(self._responses) - 1)]- self._call_idx += 1- return resp-- mock_session = MagicMock()- mock_session.post.side_effect = spy_post- mock_session.mount = MagicMock()- mock_session_fn.return_value.__enter__.return_value = mock_session- self._mock_session = mock_session---def _ok_results(*uuids: str) -> dict[str, Any]:- return {"results": {uid: {"result": "ok"} for uid in uuids}}---def _make_event(- event: str = "test_event",- distinct_id: str = "user-1",- **extra: Any,-) -> dict[str, Any]:- out: dict[str, Any] = {"event": event, "distinct_id": distinct_id}- out.update(extra)- return out---class TestBuildV1Headers(SimpleTestCase):- def test_all_required_headers_present(self) -> None:- headers = _build_v1_headers("phc_test123", attempt=1)- assert headers["Authorization"] == "Bearer phc_test123"- assert headers["Content-Type"] == "application/json"- assert "posthog-capture-v1-internal" in headers["User-Agent"]- assert headers["PostHog-Sdk-Info"] == "posthog-capture-v1-internal/1.0"- assert headers["PostHog-Attempt"] == "1"- assert len(headers["PostHog-Request-Id"]) == 36- assert "T" in headers["PostHog-Request-Timestamp"]-- def test_attempt_increments(self) -> None:- h1 = _build_v1_headers("tok", attempt=1)- h2 = _build_v1_headers("tok", attempt=3)- assert h1["PostHog-Attempt"] == "1"- assert h2["PostHog-Attempt"] == "3"-- def test_request_id_unique_per_call(self) -> None:- h1 = _build_v1_headers("tok", attempt=1)- h2 = _build_v1_headers("tok", attempt=1)- assert h1["PostHog-Request-Id"] != h2["PostHog-Request-Id"]---class TestNormalizeOptionsAndProperties(SimpleTestCase):- def test_typed_options_propagated(self) -> None:- ev: dict[str, Any] = {- "options": {"cookieless_mode": True, "disable_skew_correction": True, "product_tour_id": "tour-1"},- "properties": {"some_prop": "val"},- }- options, sid, wid, props = _normalize_options_and_properties(- ev, process_person_profile=True, event_source="test"- )- assert options["cookieless_mode"] is True- assert options["disable_skew_correction"] is True- assert options["product_tour_id"] == "tour-1"- assert "process_person_profile" not in options- assert sid is None- assert wid is None- assert props == {"some_prop": "val"}-- def test_legacy_properties_lifted_and_stripped(self) -> None:- ev: dict[str, Any] = {- "properties": {- "$cookieless_mode": True,- "$ignore_sent_at": True,- "$product_tour_id": "tour-2",- "$process_person_profile": True,- "$session_id": "sess-1",- "$window_id": "win-1",- "keep_me": 42,- },- }- options, sid, wid, props = _normalize_options_and_properties(- ev, process_person_profile=True, event_source="test"- )- assert options["cookieless_mode"] is True- assert options["disable_skew_correction"] is True- assert options["product_tour_id"] == "tour-2"- assert sid == "sess-1"- assert wid == "win-1"- assert "$cookieless_mode" not in props- assert "$ignore_sent_at" not in props- assert "$product_tour_id" not in props- assert "$process_person_profile" not in props- assert "$session_id" not in props- assert "$window_id" not in props- assert props["keep_me"] == 42-- def test_legacy_alias_disable_skew_adjustment_stripped(self) -> None:- ev: dict[str, Any] = {- "properties": {"disable_skew_adjustment": True, "other": 1},- }- options, _, _, props = _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")- assert options["disable_skew_correction"] is True- assert "disable_skew_adjustment" not in props-- def test_explicit_wins_over_legacy_on_conflict(self) -> None:- ev: dict[str, Any] = {- "options": {"cookieless_mode": False},- "session_id": "explicit-sess",- "properties": {"$cookieless_mode": True, "$session_id": "legacy-sess"},- }- options, sid, _, props = _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")- assert options["cookieless_mode"] is False- assert sid == "explicit-sess"- assert "$cookieless_mode" not in props- assert "$session_id" not in props-- def test_unknown_option_key_raises(self) -> None:- ev: dict[str, Any] = {"options": {"bogus_key": True}, "properties": {}}- with self.assertRaises(CaptureV1InternalError) as ctx:- _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")- assert "unknown option key" in str(ctx.exception)-- def test_process_person_profile_false_forces_option(self) -> None:- ev: dict[str, Any] = {"properties": {}}- options, _, _, _ = _normalize_options_and_properties(ev, process_person_profile=False, event_source="test")- assert options["process_person_profile"] is False-- def test_process_person_profile_true_leaves_unset(self) -> None:- ev: dict[str, Any] = {"properties": {}}- options, _, _, _ = _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")- assert "process_person_profile" not in options-- def test_no_options_when_all_empty_and_ppp_true(self) -> None:- ev: dict[str, Any] = {"properties": {"keep": 1}}- options, sid, wid, props = _normalize_options_and_properties(- ev, process_person_profile=True, event_source="test"- )- assert options == {}- assert sid is None- assert wid is None- assert props == {"keep": 1}-- def test_caller_input_not_mutated(self) -> None:- original_props = {"$session_id": "s1", "keep": 1}- ev: dict[str, Any] = {"properties": original_props}- _normalize_options_and_properties(ev, process_person_profile=False, event_source="test")- assert "$session_id" in original_props-- @parameterized.expand(- [- (- "option_conflict",- {"options": {"cookieless_mode": False}, "properties": {"$cookieless_mode": True}},- "cookieless_mode",- ),- ("session_id_conflict", {"session_id": "a", "properties": {"$session_id": "b"}}, "session_id"),- ("window_id_conflict", {"window_id": "a", "properties": {"$window_id": "b"}}, "window_id"),- ]- )- def test_conflict_increments_metric(self, _name: str, ev: dict[str, Any], field: str) -> None:- before = CAPTURE_V1_OPTION_CONFLICT.labels(event_source="metric_test", field=field)._value.get()- _normalize_options_and_properties(ev, process_person_profile=True, event_source="metric_test")- after = CAPTURE_V1_OPTION_CONFLICT.labels(event_source="metric_test", field=field)._value.get()- assert after == before + 1-- def test_ppp_false_overrides_explicit_true_with_conflict(self) -> None:- ev: dict[str, Any] = {- "options": {"process_person_profile": True},- "properties": {},- }- before = CAPTURE_V1_OPTION_CONFLICT.labels(event_source="ppp_test", field="process_person_profile")._value.get()- options, _, _, _ = _normalize_options_and_properties(ev, process_person_profile=False, event_source="ppp_test")- after = CAPTURE_V1_OPTION_CONFLICT.labels(event_source="ppp_test", field="process_person_profile")._value.get()- assert options["process_person_profile"] is False- assert after == before + 1---class TestResolveScalar(SimpleTestCase):- def test_explicit_wins(self) -> None:- assert _resolve_scalar("a", "b", field="f", event_source="t") == "a"-- def test_legacy_fallback(self) -> None:- assert _resolve_scalar(None, "b", field="f", event_source="t") == "b"-- def test_both_none(self) -> None:- assert _resolve_scalar(None, None, field="f", event_source="t") is None-- def test_no_conflict_when_equal(self) -> None:- before = CAPTURE_V1_OPTION_CONFLICT.labels(event_source="eq_test", field="f")._value.get()- _resolve_scalar("same", "same", field="f", event_source="eq_test")- after = CAPTURE_V1_OPTION_CONFLICT.labels(event_source="eq_test", field="f")._value.get()- assert after == before---class TestPrepareCaptureV1Batch(SimpleTestCase):- def test_envelope_shape(self) -> None:- events = [_make_event()]- payload, uuids = prepare_capture_v1_batch(events, token="tok", event_source="test")- assert payload["capture_internal"] is True- assert payload["historical_migration"] is False- assert "created_at" in payload- assert len(payload["batch"]) == 1- assert len(uuids) == 1- assert payload["batch"][0]["uuid"] == uuids[0]-- def test_uuid_generated_when_absent(self) -> None:- events = [_make_event()]- payload, uuids = prepare_capture_v1_batch(events, token="tok", event_source="test")- assert len(uuids[0]) == 36- assert payload["batch"][0]["uuid"] == uuids[0]-- def test_uuid_preserved_when_present(self) -> None:- uid = str(uuid4())- events = [_make_event(event_uuid=uid)]- payload, uuids = prepare_capture_v1_batch(events, token="tok", event_source="test")- assert uuids[0] == uid- assert payload["batch"][0]["uuid"] == uid-- def test_options_omitted_when_empty(self) -> None:- events = [_make_event()]- payload, _ = prepare_capture_v1_batch(events, token="tok", event_source="test", process_person_profile=True)- assert "options" not in payload["batch"][0]-- def test_options_present_when_set(self) -> None:- events = [_make_event(options={"cookieless_mode": True})]- payload, _ = prepare_capture_v1_batch(events, token="tok", event_source="test")- assert payload["batch"][0]["options"]["cookieless_mode"] is True-- def test_session_window_as_top_level_fields(self) -> None:- events = [_make_event(session_id="s1", window_id="w1")]- payload, _ = prepare_capture_v1_batch(events, token="tok", event_source="test")- entry = payload["batch"][0]- assert entry["session_id"] == "s1"- assert entry["window_id"] == "w1"- assert "$session_id" not in entry.get("properties", {})- assert "$window_id" not in entry.get("properties", {})-- def test_distinct_id_fallback_from_properties(self) -> None:- events = [{"event": "e", "properties": {"distinct_id": "from_props"}}]- payload, _ = prepare_capture_v1_batch(events, token="tok", event_source="test")- assert payload["batch"][0]["distinct_id"] == "from_props"-- def test_timestamp_defaults_to_now(self) -> None:- events = [_make_event()]- before = datetime.now(UTC).isoformat()- payload, _ = prepare_capture_v1_batch(events, token="tok", event_source="test")- after = datetime.now(UTC).isoformat()- ts = payload["batch"][0]["timestamp"]- assert before <= ts <= after-- def test_timestamp_non_utc_datetime_converted_correctly(self) -> None:- from datetime import timedelta, timezone-- est = timezone(timedelta(hours=-5))- # 2024-01-15 17:00 EST = 2024-01-15 22:00 UTC- ts_est = datetime(2024, 1, 15, 17, 0, 0, tzinfo=est)- events = [_make_event(timestamp=ts_est)]- payload, _ = prepare_capture_v1_batch(events, token="tok", event_source="test")- assert payload["batch"][0]["timestamp"] == "2024-01-15T22:00:00+00:00"-- def test_timestamp_naive_datetime_assumed_utc(self) -> None:- ts_naive = datetime(2024, 6, 1, 12, 0, 0)- events = [_make_event(timestamp=ts_naive)]- payload, _ = prepare_capture_v1_batch(events, token="tok", event_source="test")- assert payload["batch"][0]["timestamp"] == "2024-06-01T12:00:00+00:00"-- @parameterized.expand(- [- ("empty_token", "", [{"event": "e", "distinct_id": "u"}], "api token is required"),- ("no_events", "tok", [], "at least one event is required"),- ]- )- def test_validation_errors(self, _name: str, token: str, events: list[dict[str, Any]], fragment: str) -> None:- with self.assertRaises(CaptureV1InternalError) as ctx:- prepare_capture_v1_batch(events, token=token, event_source="src")- assert fragment in str(ctx.exception).lower()-- def test_missing_event_name_raises(self) -> None:- events = [{"distinct_id": "u1", "properties": {}}]- with self.assertRaises(CaptureV1InternalError) as ctx:- prepare_capture_v1_batch(events, token="tok", event_source="src")- assert "event name" in str(ctx.exception).lower()-- def test_missing_distinct_id_raises(self) -> None:- events = [{"event": "e", "properties": {}}]- with self.assertRaises(CaptureV1InternalError) as ctx:- prepare_capture_v1_batch(events, token="tok", event_source="src")- assert "distinct_id" in str(ctx.exception).lower()-- @parameterized.expand(- [- ("$snapshot",),- ("$performance_event",),- ("$snapshot_items",),- ]- )- def test_replay_event_names_rejected(self, event_name: str) -> None:- events = [_make_event(event=event_name)]- with self.assertRaises(CaptureV1InternalError) as ctx:- prepare_capture_v1_batch(events, token="tok", event_source="src")- assert "replay event" in str(ctx.exception).lower()-- def test_legacy_properties_stripped_in_batch(self) -> None:- events = [- _make_event(- properties={- "$cookieless_mode": True,- "$ignore_sent_at": False,- "$product_tour_id": "t",- "$process_person_profile": True,- "$session_id": "s1",- "$window_id": "w1",- "keep": 1,- }- )- ]- payload, _ = prepare_capture_v1_batch(events, token="tok", event_source="test")- entry = payload["batch"][0]- props = entry["properties"]- for key in (- "$cookieless_mode",- "$ignore_sent_at",- "$product_tour_id",- "$process_person_profile",- "$session_id",- "$window_id",- ):- assert key not in props, f"{key} should have been stripped"- assert props["keep"] == 1- assert entry["session_id"] == "s1"- assert entry["window_id"] == "w1"- assert entry["options"]["cookieless_mode"] is True---class TestCaptureV1BatchInternal(SimpleTestCase):- @patch("posthog.api.capture_v1.internal_requests_session")- def test_happy_path_batch(self, mock_session_fn: MagicMock) -> None:- uid1, uid2 = str(uuid4()), str(uuid4())- events = [- _make_event(event_uuid=uid1),- _make_event(event="other", distinct_id="u2", event_uuid=uid2),- ]- spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid1, uid2))])-- result = capture_v1_batch_internal(events=events, token="tok", event_source="happy")-- assert result.status_code == 200- assert result.succeeded()- assert set(result.ok) == {uid1, uid2}- assert not result.dropped- assert not result.warnings- assert not result.retried- assert result.error is None-- assert len(spy.calls) == 1- assert spy.calls[0]["url"] == EXPECTED_URL-- @patch("posthog.api.capture_v1.internal_requests_session")- def test_headers_on_initial_request(self, mock_session_fn: MagicMock) -> None:- uid = str(uuid4())- events = [_make_event(event_uuid=uid)]- spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])-- capture_v1_batch_internal(events=events, token="phc_abc", event_source="hdr")-- headers = spy.calls[0]["headers"]- assert headers["Authorization"] == "Bearer phc_abc"- assert headers["Content-Type"] == "application/json"- assert headers["PostHog-Sdk-Info"] == "posthog-capture-v1-internal/1.0"- assert headers["PostHog-Attempt"] == "1"- assert len(headers["PostHog-Request-Id"]) == 36- assert "T" in headers["PostHog-Request-Timestamp"]-- @patch("posthog.api.capture_v1.internal_requests_session")- def test_envelope_shape_on_wire(self, mock_session_fn: MagicMock) -> None:- uid = str(uuid4())- events = [_make_event(event_uuid=uid)]- spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])-- capture_v1_batch_internal(events=events, token="tok", event_source="env")-- body = spy.calls[0]["json"]- assert body["capture_internal"] is True- assert body["historical_migration"] is False- assert "created_at" in body- assert len(body["batch"]) == 1- assert body["batch"][0]["uuid"] == uid-- @patch("posthog.api.capture_v1.internal_requests_session")- def test_options_propagated_to_wire(self, mock_session_fn: MagicMock) -> None:- uid = str(uuid4())- events = [- _make_event(- event_uuid=uid,- options={"cookieless_mode": True, "disable_skew_correction": True, "product_tour_id": "t1"},- session_id="s1",- window_id="w1",- )- ]- spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])-- capture_v1_batch_internal(events=events, token="tok", event_source="opt")-- entry = spy.calls[0]["json"]["batch"][0]- assert entry["options"]["cookieless_mode"] is True- assert entry["options"]["disable_skew_correction"] is True- assert entry["options"]["product_tour_id"] == "t1"- assert entry["session_id"] == "s1"- assert entry["window_id"] == "w1"- assert "$cookieless_mode" not in entry["properties"]- assert "$session_id" not in entry["properties"]-- @patch("posthog.api.capture_v1.internal_requests_session")- def test_options_omitted_when_none_set_and_ppp_true(self, mock_session_fn: MagicMock) -> None:- uid = str(uuid4())- events = [_make_event(event_uuid=uid)]- spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])-- capture_v1_batch_internal(events=events, token="tok", event_source="nopt", process_person_profile=True)-- entry = spy.calls[0]["json"]["batch"][0]- assert "options" not in entry-- @patch("posthog.api.capture_v1.internal_requests_session")- def test_process_person_profile_false(self, mock_session_fn: MagicMock) -> None:- uid = str(uuid4())- events = [_make_event(event_uuid=uid)]- spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])-- capture_v1_batch_internal(events=events, token="tok", event_source="ppp")-- entry = spy.calls[0]["json"]["batch"][0]- assert entry["options"]["process_person_profile"] is False- assert "$process_person_profile" not in entry["properties"]-- @parameterized.expand(- [- ("400_validation", 400, {"error": "invalid_request", "error_description": "bad"}),- ("401_auth", 401, {"error": "unauthorized", "error_description": "bad token"}),- ("402_billing", 402, {"error": "billing_limit", "error_description": "quota"}),- ("408_timeout", 408, {"error": "request_timeout", "error_description": "timeout"}),- ("413_too_large", 413, {"error": "too_large", "error_description": "payload"}),- ("415_media", 415, {"error": "unsupported_media", "error_description": "type"}),- ("429_rate_limit", 429, {"error": "rate_limited", "error_description": "slow down"}),- ("500_internal", 500, {"error": "internal_error", "error_description": "boom"}),- ("502_bad_gateway", 502, {"error": "bad_gateway", "error_description": "upstream"}),- ("503_unavailable", 503, {"error": "service_unavailable", "error_description": "down"}),- ("504_gateway_timeout", 504, {"error": "gateway_timeout", "error_description": "slow"}),- ]- )- @patch("posthog.api.capture_v1.internal_requests_session")- def test_whole_request_failures(- self,- _name: str,- status: int,- error_body: dict[str, str],- mock_session_fn: MagicMock,- ) -> None:- events = [_make_event()]- InstallV1Spy(mock_session_fn, [MockResponse(status_code=status, body=error_body)])-- result = capture_v1_batch_internal(events=events, token="tok", event_source="fail")-- assert result.status_code == status- assert result.error is not None- assert result.error["error"] == error_body["error"]- assert not result.succeeded()-- @patch("posthog.api.capture_v1.internal_requests_session")- def test_partial_failure_mixed_results(self, mock_session_fn: MagicMock) -> None:- u_ok, u_drop, u_warn = str(uuid4()), str(uuid4()), str(uuid4())- events = [- _make_event(event_uuid=u_ok),- _make_event(event_uuid=u_drop, event="drop_me"),- _make_event(event_uuid=u_warn, event="warn_me"),- ]- body: dict[str, Any] = {- "results": {- u_ok: {"result": "ok"},- u_drop: {"result": "drop", "details": "quota"},- u_warn: {"result": "warning", "details": "sdk old"},- }- }- InstallV1Spy(mock_session_fn, [MockResponse(body=body)])-- result = capture_v1_batch_internal(events=events, token="tok", event_source="partial")-- assert result.status_code == 200- assert u_ok in result.ok- assert u_drop in result.dropped- assert u_warn in result.warnings- assert not result.retried- assert not result.succeeded()-- @patch("posthog.api.capture_v1.time.sleep")- @patch("posthog.api.capture_v1.internal_requests_session")- def test_auto_resubmit_retry_events(self, mock_session_fn: MagicMock, mock_sleep: MagicMock) -> None:- u_ok, u_retry = str(uuid4()), str(uuid4())- events = [- _make_event(event_uuid=u_ok),- _make_event(event_uuid=u_retry, event="retryable"),- ]- first_response = MockResponse(- body={- "results": {- u_ok: {"result": "ok"},- u_retry: {"result": "retry", "details": "busy"},- }- },- headers={"Retry-After": "2"},- )- second_response = MockResponse(- body={"results": {u_retry: {"result": "ok"}}},- )- spy = InstallV1Spy(mock_session_fn, [first_response, second_response])-- result = capture_v1_batch_internal(events=events, token="tok", event_source="resub")-- assert result.status_code == 200- assert result.succeeded()- assert set(result.ok) == {u_ok, u_retry}- assert not result.retried-- assert len(spy.calls) == 2- mock_sleep.assert_called_once_with(2.0)-- # Second request should have incremented attempt and only retry uuid.- second_headers = spy.calls[1]["headers"]- assert second_headers["PostHog-Attempt"] == "2"- assert second_headers["PostHog-Request-Id"] != spy.calls[0]["headers"]["PostHog-Request-Id"]- second_batch = spy.calls[1]["json"]["batch"]- assert len(second_batch) == 1- assert second_batch[0]["uuid"] == u_retry-- @patch("posthog.api.capture_v1.time.sleep")- @patch("posthog.api.capture_v1.internal_requests_session")- def test_bounded_retries_exhausted(self, mock_session_fn: MagicMock, mock_sleep: MagicMock) -> None:- u_retry = str(uuid4())- events = [_make_event(event_uuid=u_retry)]- persistent_retry = MockResponse(- body={"results": {u_retry: {"result": "retry"}}},- headers={"Retry-After": "1"},- )- InstallV1Spy(mock_session_fn, [persistent_retry, persistent_retry, persistent_retry])-- result = capture_v1_batch_internal(events=events, token="tok", event_source="bounded", max_attempts=2)-- assert result.status_code == 200- assert u_retry in result.retried- assert not result.succeeded()-- @patch("posthog.api.capture_v1.time.sleep")- @patch("posthog.api.capture_v1.internal_requests_session")- def test_retry_after_capped(self, mock_session_fn: MagicMock, mock_sleep: MagicMock) -> None:- u_retry = str(uuid4())- events = [_make_event(event_uuid=u_retry)]- resp1 = MockResponse(- body={"results": {u_retry: {"result": "retry"}}},- headers={"Retry-After": "9999"},- )- resp2 = MockResponse(body=_ok_results(u_retry))- InstallV1Spy(mock_session_fn, [resp1, resp2])-- capture_v1_batch_internal(events=events, token="tok", event_source="cap")-- mock_sleep.assert_called_once_with(5.0)-- @patch("posthog.api.capture_v1.internal_requests_session")- def test_headers_on_resubmit(self, mock_session_fn: MagicMock) -> None:- u_retry = str(uuid4())- events = [_make_event(event_uuid=u_retry)]- resp1 = MockResponse(- body={"results": {u_retry: {"result": "retry"}}},- headers={"Retry-After": "0"},- )- resp2 = MockResponse(body=_ok_results(u_retry))- spy = InstallV1Spy(mock_session_fn, [resp1, resp2])-- with patch("posthog.api.capture_v1.time.sleep"):- capture_v1_batch_internal(events=events, token="tok", event_source="rh")-- h1 = spy.calls[0]["headers"]- h2 = spy.calls[1]["headers"]- assert h1["PostHog-Attempt"] == "1"- assert h2["PostHog-Attempt"] == "2"- assert h1["PostHog-Request-Id"] != h2["PostHog-Request-Id"]- for h in (h1, h2):- assert "Authorization" in h- assert "PostHog-Sdk-Info" in h- assert "PostHog-Request-Timestamp" in h-- @patch("posthog.api.capture_v1.internal_requests_session")- def test_transport_retry_adapter_mounted(self, mock_session_fn: MagicMock) -> None:- uid = str(uuid4())- events = [_make_event(event_uuid=uid)]- spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])-- capture_v1_batch_internal(events=events, token="tok", event_source="mount")-- spy._mock_session.mount.assert_called_once()- args = spy._mock_session.mount.call_args- assert args[0][0] == EXPECTED_URL- adapter = args[0][1]- assert isinstance(adapter, HTTPAdapter)-- @patch("posthog.api.capture_v1.internal_requests_session")- def test_all_drop_batch(self, mock_session_fn: MagicMock) -> None:- u1, u2 = str(uuid4()), str(uuid4())- events = [_make_event(event_uuid=u1), _make_event(event_uuid=u2)]- body: dict[str, Any] = {- "results": {- u1: {"result": "drop", "details": "quota"},- u2: {"result": "drop", "details": "restricted"},- }- }- InstallV1Spy(mock_session_fn, [MockResponse(body=body)])-- result = capture_v1_batch_internal(events=events, token="tok", event_source="alldrop")-- assert result.status_code == 200- assert not result.succeeded()- assert set(result.dropped) == {u1, u2}- assert not result.ok- assert not result.retried-- @patch("posthog.api.capture_v1.time.sleep")- @patch("posthog.api.capture_v1.internal_requests_session")- def test_mixed_retry_drop_warn_resubmits_only_retry(- self, mock_session_fn: MagicMock, mock_sleep: MagicMock- ) -> None:- u_drop, u_warn, u_retry = str(uuid4()), str(uuid4()), str(uuid4())- events = [- _make_event(event_uuid=u_drop),- _make_event(event_uuid=u_warn),- _make_event(event_uuid=u_retry),- ]- first_resp = MockResponse(- body={- "results": {- u_drop: {"result": "drop"},- u_warn: {"result": "warning"},- u_retry: {"result": "retry"},- }- },- headers={"Retry-After": "0"},- )- second_resp = MockResponse(body={"results": {u_retry: {"result": "ok"}}})- spy = InstallV1Spy(mock_session_fn, [first_resp, second_resp])-- result = capture_v1_batch_internal(events=events, token="tok", event_source="mix")-- assert len(spy.calls) == 2- assert u_drop in result.dropped- assert u_warn in result.warnings- assert u_retry in result.ok- assert not result.retried-- @patch("posthog.api.capture_v1.internal_requests_session")- def test_empty_results_map_marks_unaccounted(self, mock_session_fn: MagicMock) -> None:- uid = str(uuid4())- events = [_make_event(event_uuid=uid)]- InstallV1Spy(mock_session_fn, [MockResponse(body={"results": {}})])-- result = capture_v1_batch_internal(events=events, token="tok", event_source="empty")-- assert result.status_code == 200- assert uid in result.unaccounted- assert not result.ok- assert not result.succeeded()-- @patch("posthog.api.capture_v1.internal_requests_session")- def test_non_json_200_body(self, mock_session_fn: MagicMock) -> None:- events = [_make_event()]- InstallV1Spy(mock_session_fn, [MockResponse(status_code=200, body=None, text="not json")])-- result = capture_v1_batch_internal(events=events, token="tok", event_source="badjson")-- assert result.status_code == 200- assert result.error is not None- assert result.error["error"] == "invalid_json"- assert not result.succeeded()-- @patch("posthog.api.capture_v1.time.sleep")- @patch("posthog.api.capture_v1.internal_requests_session")- def test_retry_without_retry_after_header(self, mock_session_fn: MagicMock, mock_sleep: MagicMock) -> None:- u_retry = str(uuid4())- events = [_make_event(event_uuid=u_retry)]- resp1 = MockResponse(- body={"results": {u_retry: {"result": "retry"}}},- )- resp2 = MockResponse(body=_ok_results(u_retry))- InstallV1Spy(mock_session_fn, [resp1, resp2])-- result = capture_v1_batch_internal(events=events, token="tok", event_source="noheader")-- assert result.succeeded()- mock_sleep.assert_not_called()-- @patch("posthog.api.capture_v1.time.sleep")- @patch("posthog.api.capture_v1.internal_requests_session")- def test_resubmit_preserves_envelope_metadata(self, mock_session_fn: MagicMock, mock_sleep: MagicMock) -> None:- u_retry = str(uuid4())- events = [_make_event(event_uuid=u_retry)]- resp1 = MockResponse(- body={"results": {u_retry: {"result": "retry"}}},- headers={"Retry-After": "0"},- )- resp2 = MockResponse(body=_ok_results(u_retry))- spy = InstallV1Spy(mock_session_fn, [resp1, resp2])-- capture_v1_batch_internal(- events=events,- token="tok",- event_source="envelope",- historical_migration=True,- )-- body1 = spy.calls[0]["json"]- body2 = spy.calls[1]["json"]- assert body2["capture_internal"] is True- assert body2["historical_migration"] is True- assert body2["created_at"] == body1["created_at"]-- @patch("posthog.api.capture_v1.internal_requests_session")- def test_max_attempts_one_means_no_resubmit(self, mock_session_fn: MagicMock) -> None:- u_retry = str(uuid4())- events = [_make_event(event_uuid=u_retry)]- resp = MockResponse(- body={"results": {u_retry: {"result": "retry"}}},- headers={"Retry-After": "0"},- )- spy = InstallV1Spy(mock_session_fn, [resp])-- result = capture_v1_batch_internal(events=events, token="tok", event_source="noretry", max_attempts=1)-- assert len(spy.calls) == 1- assert u_retry in result.retried- assert not result.succeeded()-- @patch("posthog.api.capture_v1.time.sleep")- @patch("posthog.api.capture_v1.internal_requests_session")- def test_drop_round1_retry_ok_round2_merged(self, mock_session_fn: MagicMock, mock_sleep: MagicMock) -> None:- u_drop, u_retry = str(uuid4()), str(uuid4())- events = [- _make_event(event_uuid=u_drop),- _make_event(event_uuid=u_retry),- ]- resp1 = MockResponse(- body={- "results": {- u_drop: {"result": "drop", "details": "quota"},- u_retry: {"result": "retry"},- }- },- headers={"Retry-After": "0"},- )- resp2 = MockResponse(body={"results": {u_retry: {"result": "ok"}}})- InstallV1Spy(mock_session_fn, [resp1, resp2])-- result = capture_v1_batch_internal(events=events, token="tok", event_source="merge")-- assert u_drop in result.dropped- assert u_retry in result.ok- assert not result.retried- assert result.results[u_drop]["result"] == "drop"- assert result.results[u_retry]["result"] == "ok"-- @parameterized.expand(- [- ("unaccounted_uuid", {}, "unaccounted", False),- ("unknown_status", {"result": "new_fancy_status"}, "unaccounted", False),- ("drop", {"result": "drop"}, "dropped", False),- ("warning", {"result": "warning"}, "warnings", True),- ]- )- @patch("posthog.api.capture_v1.internal_requests_session")- def test_terminal_categorization(- self,- _name: str,- entry: dict[str, Any],- expected_bucket: str,- expect_succeeded: bool,- mock_session_fn: MagicMock,- ) -> None:- uid = str(uuid4())- events = [_make_event(event_uuid=uid)]- results = {uid: entry} if entry else {}- InstallV1Spy(mock_session_fn, [MockResponse(body={"results": results})])-- result = capture_v1_batch_internal(events=events, token="tok", event_source="cat")-- assert uid in getattr(result, expected_bucket)- assert result.succeeded() == expect_succeeded-- @patch("posthog.api.capture_v1.internal_requests_session")- def test_transport_exception_returns_structured_error(self, mock_session_fn: MagicMock) -> None:- events = [_make_event()]- mock_session = MagicMock()- mock_session.post.side_effect = RequestsConnectionError("connection refused")- mock_session.mount = MagicMock()- mock_session_fn.return_value.__enter__.return_value = mock_session-- result = capture_v1_batch_internal(events=events, token="tok", event_source="transport")-- assert result.status_code == 0- assert result.error is not None- assert result.error["error"] == "transport_error"- assert "connection refused" in result.error["error_description"]- assert not result.succeeded()---class TestParseRetryAfter(SimpleTestCase):- @parameterized.expand(- [- ("none", None, 0.0),- ("empty_string", "", 0.0),- ("zero", "0", 0.0),- ("positive", "2", 2.0),- ("float_value", "1.5", 1.5),- ("capped", "9999", 5.0),- ("negative_clamped", "-1", 0.0),- ("non_numeric_fallback", "garbage", 1.0),- ]- )- def test_parse_retry_after(self, _name: str, header: str | None, expected: float) -> None:- assert _parse_retry_after(header) == expected---class TestCaptureV1Internal(SimpleTestCase):- @patch("posthog.api.capture_v1.internal_requests_session")- def test_single_event_wrapper(self, mock_session_fn: MagicMock) -> None:- uid = str(uuid4())- spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])-- result = capture_v1_internal(- token="tok",- event_name="single_test",- event_source="single",- distinct_id="u1",- event_uuid=uid,- session_id="s1",- window_id="w1",- options={"cookieless_mode": True},- properties={"custom": "val"},- )-- assert result.status_code == 200- assert uid in result.ok-- entry = spy.calls[0]["json"]["batch"][0]- assert entry["event"] == "single_test"- assert entry["distinct_id"] == "u1"- assert entry["uuid"] == uid- assert entry["session_id"] == "s1"- assert entry["window_id"] == "w1"- assert entry["options"]["cookieless_mode"] is True- assert entry["properties"]["custom"] == "val"-- @patch("posthog.api.capture_v1.internal_requests_session")- def test_single_minimal(self, mock_session_fn: MagicMock) -> None:- InstallV1Spy(mock_session_fn, [MockResponse(body={"results": {}})])-- result = capture_v1_internal(- token="tok",- event_name="minimal",- event_source="min",- distinct_id="u1",- )- assert result.status_code == 200---class TestCaptureV1Result(SimpleTestCase):- def test_succeeded_true(self) -> None:- r = CaptureV1Result(status_code=200, ok=["a", "b"])- assert r.succeeded()-- @parameterized.expand(- [- ("error", {"error": {"error": "bad"}}, {}),- ("dropped", {}, {"dropped": ["a"]}),- ("retried", {}, {"retried": ["a"]}),- ("unaccounted", {}, {"unaccounted": ["a"]}),- ]- )- def test_succeeded_false(self, _name: str, kwargs: dict[str, Any], list_kwargs: dict[str, Any]) -> None:- r = CaptureV1Result(status_code=200, **kwargs, **list_kwargs)- assert not r.succeeded()-- def test_terminal_failures_includes_all_buckets(self) -> None:- r = CaptureV1Result(- status_code=200,- results={- "a": {"result": "drop"},- "b": {"result": "retry"},- "c": {"result": "unaccounted"},- },- dropped=["a"],- retried=["b"],- unaccounted=["c"],- )- failures = r.terminal_failures()- assert set(failures.keys()) == {"a", "b", "c"}-- def test_raise_for_status_on_error(self) -> None:- r = CaptureV1Result(status_code=503, error={"error": "server_error", "error_description": "down"})- with self.assertRaises(CaptureV1InternalError):- r.raise_for_status()-- @parameterized.expand(- [- ("dropped", {"dropped": ["a"]}),- ("retried", {"retried": ["a"]}),- ("unaccounted", {"unaccounted": ["a"]}),- ]- )- def test_raise_for_status_on_partial_failure(self, _name: str, kwargs: dict[str, Any]) -> None:- r = CaptureV1Result(status_code=200, **kwargs)- with self.assertRaises(CaptureV1InternalError):- r.raise_for_status()-- def test_raise_for_status_noop_on_success(self) -> None:- r = CaptureV1Result(status_code=200, ok=["a"])- r.raise_for_status()diff --git a/posthog/api/test/test_llm_prompt.py b/posthog/api/test/test_llm_prompt.pyindex f2e329be908e..a9155d292524 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_routed")+ @patch("posthog.api.llm_prompt.capture_internal")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.pyindex 15d9ebee3c7a..9c28bcadea7c 100644--- a/posthog/api/test/test_person.py+++ b/posthog/api/test/test_person.py@@ -1039,7 +1039,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.validation_error_response("required", "This field is required.", "properties"),)- @mock.patch("posthog.api.person.capture_internal_routed")+ @mock.patch("posthog.api.person.capture_internal")def test_new_update_single_person_property(self, mock_capture) -> None:person = _create_person(team=self.team,@@ -1062,7 +1062,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):process_person_profile=True,)- @mock.patch("posthog.api.person.capture_internal_routed")+ @mock.patch("posthog.api.person.capture_internal")def test_new_delete_person_properties(self, mock_capture) -> None:person = _create_person(team=self.team,@@ -1085,7 +1085,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):process_person_profile=True,)- @mock.patch("posthog.api.person.capture_internal_routed")+ @mock.patch("posthog.api.person.capture_internal")def test_update_person_property_by_numeric_id(self, mock_capture) -> None:person = _create_person(team=self.team,@@ -1108,7 +1108,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):process_person_profile=True,)- @mock.patch("posthog.api.person.capture_internal_routed")+ @mock.patch("posthog.api.person.capture_internal")def test_delete_person_property_by_numeric_id(self, mock_capture) -> None:person = _create_person(team=self.team,@@ -1131,7 +1131,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):process_person_profile=True,)- @mock.patch("posthog.api.person.capture_internal_routed")+ @mock.patch("posthog.api.person.capture_internal")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.pyindex 691eec7eceb1..a5024c8d111c 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_routed")+ @mock.patch("posthog.api.person.capture_internal")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_routed")+ @mock.patch("posthog.api.person.capture_internal")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_routed")+ @mock.patch("posthog.api.person.capture_internal")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_routed")+ @mock.patch("posthog.api.person.capture_internal")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.pyindex 98486b3c1c34..c0c9af0a271a 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 clientself.client = Client(enforce_csrf_checks=True)- @patch("posthog.api.report.capture_internal_routed")+ @patch("posthog.api.report.capture_internal")def test_submit_csp_report_to_new_internal_capture(self, mock_capture) -> None:payload = {"csp-report": {@@ -43,7 +43,7 @@ class TestCspReport(BaseTest):assert resp.status_code == status.HTTP_204_NO_CONTENTassert mock_capture.call_count == 1- @patch("posthog.api.report.capture_batch_internal_routed")+ @patch("posthog.api.report.capture_batch_internal")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())@@ -103,7 +103,7 @@ class TestCspReport(BaseTest):mock_batch_capture.assert_called_once()assert len(mock_batch_capture.call_args.kwargs["events"]) == 3- @patch("posthog.api.report.capture_internal_routed")+ @patch("posthog.api.report.capture_internal")def test_capture_csp_violation(self, mock_capture):mock_capture.return_value = MagicMock(status_code=204)@@ -132,7 +132,7 @@ class TestCspReport(BaseTest):assert status.HTTP_204_NO_CONTENT == response.status_codeassert mock_capture.call_count == 1- @patch("posthog.api.report.capture_internal_routed")+ @patch("posthog.api.report.capture_internal")def test_capture_csp_no_trailing_slash(self, mock_capture):mock_capture.return_value = MagicMock(status_code=204)@@ -231,7 +231,7 @@ class TestCspReport(BaseTest):assert response.json()["code"] == "invalid_payload"assert "Failed to submit CSP report" in response.json()["detail"]- @patch("posthog.api.report.capture_batch_internal_routed")+ @patch("posthog.api.report.capture_batch_internal")def test_integration_csp_report_with_report_to_format_returns_204(self, mock_capture):mock_capture.return_value = MagicMock(raise_for_status=MagicMock())@@ -262,7 +262,7 @@ class TestCspReport(BaseTest):assert response.content == b""mock_capture.assert_called_once()- @patch("posthog.api.report.capture_batch_internal_routed")+ @patch("posthog.api.report.capture_batch_internal")def test_capture_csp_report_to_violation(self, mock_capture):mock_capture.return_value = MagicMock(raise_for_status=MagicMock())@@ -317,7 +317,7 @@ class TestCspReport(BaseTest):mock_capture.assert_called_once()assert len(mock_capture.call_args.kwargs["events"]) == 2- @patch("posthog.api.report.capture_internal_routed")+ @patch("posthog.api.report.capture_internal")@patch("posthog.api.report.logger")def test_csp_debug_logging_enabled(self, mock_logger, mock_capture):mock_capture.return_value = MagicMock(status_code=204)@@ -347,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_routed")+ @patch("posthog.api.report.capture_internal")@patch("posthog.api.report.logger")def test_csp_debug_logging_disabled(self, mock_logger, mock_capture):mock_capture.return_value = MagicMock(status_code=204)@@ -369,7 +369,7 @@ class TestCspReport(BaseTest):mock_capture.assert_called_once()mock_logger.exception.assert_not_called()- @patch("posthog.api.report.capture_internal_routed")+ @patch("posthog.api.report.capture_internal")@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)@@ -441,7 +441,7 @@ class TestCspReport(BaseTest):assert response.status_code == status.HTTP_204_NO_CONTENT- @patch("posthog.api.report.capture_internal_routed")+ @patch("posthog.api.report.capture_internal")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/management/commands/plugin_server_load_test.py b/posthog/management/commands/plugin_server_load_test.pyindex ed6ad8361665..cae4b473dfb0 100644--- a/posthog/management/commands/plugin_server_load_test.py+++ b/posthog/management/commands/plugin_server_load_test.py@@ -112,22 +112,23 @@ class Command(BaseCommand):})- # as in "classic" capture_internal, ordered_events are submitted async- # returning a list of futures (previously ignored!) so final event- # ordering in the ingest topic is not guaranteed here+ logger.info("submitting_events", total=len(events))+start_time = time.monotonic()- results = capture_batch_internal(+ result = capture_batch_internal(events=events,event_source="plugin_server_load_test",token=token,- process_person_profile=True, # allow person profile processing to occur as cfg for this token (team/project)+ process_person_profile=True,+ timeout=10.0,)- for future in results:- try:- result = future.result()- result.raise_for_status()- except Exception as e:- logger.exception("event_submission_fail", error=e)+ if not result.succeeded():+ logger.warning(+ "submission_partial_failure",+ dropped=len(result.dropped),+ retried=len(result.retried),+ unaccounted=len(result.unaccounted),+ )while True:offsets = admin.list_consumer_group_offsets(group_id="clickhouse-ingestion")diff --git a/posthog/settings/ingestion.py b/posthog/settings/ingestion.pyindex 4b61eadce00d..336621999f56 100644--- a/posthog/settings/ingestion.py+++ b/posthog/settings/ingestion.py@@ -53,7 +53,8 @@ REPLAY_CAPTURE_ENDPOINT = os.getenv("REPLAY_CAPTURE_ENDPOINT", "/s/")CAPTURE_INTERNAL_URL = os.getenv("CAPTURE_INTERNAL_URL", "http://localhost:8010")CAPTURE_REPLAY_INTERNAL_URL = os.getenv("CAPTURE_REPLAY_INTERNAL_URL", "http://localhost:8010")-CAPTURE_INTERNAL_MAX_WORKERS = get_from_env("CAPTURE_INTERNAL_MAX_WORKERS", type_cast=int, default=16)+# Thread-pool size for capture_internal batch chunk fan-out (default 8, was per-event fan-out pre-v1).+CAPTURE_INTERNAL_MAX_WORKERS = get_from_env("CAPTURE_INTERNAL_MAX_WORKERS", type_cast=int, default=8)NEW_ANALYTICS_CAPTURE_ENDPOINT = os.getenv("NEW_CAPTURE_ENDPOINT", "/i/v0/e/")@@ -62,6 +63,8 @@ CAPTURE_V1_INTERNAL_MAX_ATTEMPTS = get_from_env("CAPTURE_V1_INTERNAL_MAX_ATTEMPTCAPTURE_V1_INTERNAL_RETRY_AFTER_CAP_SECONDS = get_from_env("CAPTURE_V1_INTERNAL_RETRY_AFTER_CAP_SECONDS", type_cast=float, default=5.0)+# Chunk fan-out reuses CAPTURE_INTERNAL_MAX_WORKERS (above) for its thread pool.+CAPTURE_INTERNAL_BATCH_CHUNK_SIZE = get_from_env("CAPTURE_INTERNAL_BATCH_CHUNK_SIZE", type_cast=int, default=200)NEW_ANALYTICS_CAPTURE_EXCLUDED_TEAM_IDS = get_set(os.getenv("NEW_ANALYTICS_CAPTURE_EXCLUDED_TEAM_IDS", ""))ELEMENT_CHAIN_AS_STRING_EXCLUDED_TEAMS = get_set(os.getenv("ELEMENT_CHAIN_AS_STRING_EXCLUDED_TEAMS", ""))diff --git a/posthog/temporal/ai_observability/evaluation_workflow_activities.py b/posthog/temporal/ai_observability/evaluation_workflow_activities.pyindex 26c94bde5d1b..d4ad62ce40ad 100644--- a/posthog/temporal/ai_observability/evaluation_workflow_activities.py+++ b/posthog/temporal/ai_observability/evaluation_workflow_activities.py@@ -10,7 +10,7 @@ import structlogimport temporaliofrom structlog.contextvars import bind_contextvars-from posthog.api.capture_dispatch import capture_internal_routed+from posthog.api.capture import capture_internalfrom posthog.models.team import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.ai_observability.evaluation_llm_judge import DEFAULT_JUDGE_MODEL@@ -383,7 +383,7 @@ async def emit_evaluation_event_activity(inputs: EmitEvaluationEventInputs) -> Nevent_timestamp = datetime.now(UTC)- capture_result = capture_internal_routed(+ capture_result = capture_internal(token=team.api_token,event_name="$ai_evaluation",event_source="llm_analytics_evaluation",diff --git a/posthog/temporal/ai_observability/run_tagger.py b/posthog/temporal/ai_observability/run_tagger.pyindex 218bb6864774..e8353f2e7455 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_contextvarsfrom temporalio.common import RetryPolicyfrom temporalio.exceptions import ApplicationError-from posthog.api.capture_dispatch import capture_internal_routed+from posthog.api.capture import capture_internalfrom posthog.models.team import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.ai_observability.evaluation_event_io import extract_event_io@@ -522,7 +522,7 @@ async def emit_tagger_event_activity(inputs: EmitTaggerEventInputs) -> None:event_timestamp = datetime.now(UTC)- routed_result = capture_internal_routed(+ routed_result = capture_internal(token=team.api_token,event_name="$ai_tag",event_source="llm_analytics_tagger",diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex 0eaf99928ab5..4b5742709a98 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -179,7 +179,7 @@ class TestRunEvaluationWorkflow:"posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get") as mock_team_get:with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_routed"+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal") as mock_capture:mock_team_get.return_value = teammock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())@@ -242,7 +242,7 @@ class TestRunEvaluationWorkflow:"posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get") as mock_team_get:with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_routed"+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal") as mock_capture:mock_team_get.return_value = teammock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())@@ -302,7 +302,7 @@ class TestRunEvaluationWorkflow:"posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get") as mock_team_get:with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_routed"+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal") as mock_capture:mock_team_get.return_value = teammock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())@@ -586,7 +586,7 @@ class TestRunEvaluationWorkflow:"posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get") as mock_team_get:with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_routed"+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal") as mock_capture:mock_team_get.return_value = teammock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())@@ -633,7 +633,7 @@ class TestRunEvaluationWorkflow:"posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get") as mock_team_get:with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_routed"+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal") as mock_capture:mock_team_get.return_value = teammock_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.pyindex 49f413d7177a..1af893e90ea9 100644--- a/posthog/temporal/ai_observability/test_run_tagger.py+++ b/posthog/temporal/ai_observability/test_run_tagger.py@@ -384,7 +384,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_routed") as mock_capture:+ with patch("posthog.temporal.ai_observability.run_tagger.capture_internal") as mock_capture:mock_team_get.return_value = teammock_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.pyindex 892f39c24660..07c5ba9907fd 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 settingsimport structlog-from posthog.api.capture_dispatch import capture_internal_routed+from posthog.api.capture import capture_internalfrom posthog.temporal.session_replay.session_summary.types.events import SessionSummaryReadyPropertiesfrom products.replay.backend.models.session_summaries import SingleSessionSummary@@ -36,7 +36,7 @@ def capture_session_summary_ready(session_duration=summary.session_duration,)try:- result = capture_internal_routed(+ result = capture_internal(token=team_api_token,event_name="$session_summary_ready",event_source=EVENT_SOURCE,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.pyindex 73ce2eb6a7f6..55a258fe7f18 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@@ -3,7 +3,7 @@ from unittest.mock import MagicMockfrom pytest_mock import MockerFixture-from posthog.api.capture_dispatch import CaptureRoutedError+from posthog.api.capture import CaptureInternalErrorfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.session_replay.session_summary.activities.video_based.a7c_store_video_session_summary import (store_video_session_summary_activity,@@ -45,16 +45,16 @@ def test_capture_session_summary_ready_emits_internal_project_event()settings.SITE_URL = "http://localhost:8000"result = mocker.MagicMock()- capture_internal_routed = mocker.patch(- "posthog.temporal.session_replay.session_summary.event_capture.capture_internal_routed", return_value=result+ mock_capture_internal = mocker.patch(+ "posthog.temporal.session_replay.session_summary.event_capture.capture_internal", return_value=result)from posthog.temporal.session_replay.session_summary.event_capture import capture_session_summary_readycapture_session_summary_ready(summary, team_api_token="token-override")- capture_internal_routed.assert_called_once()- _, kwargs = capture_internal_routed.call_args+ mock_capture_internal.assert_called_once()+ _, kwargs = mock_capture_internal.call_argsassert kwargs["token"] == "token-override"assert kwargs["event_name"] == "$session_summary_ready"assert kwargs["event_source"] == "session_summary_events"@@ -88,10 +88,8 @@ def test_capture_session_summary_ready_swallow_capture_errors(created_by=user,)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_routed", return_value=result- )+ result.raise_for_status.side_effect = CaptureInternalError("boom", status_code=500)+ mocker.patch("posthog.temporal.session_replay.session_summary.event_capture.capture_internal", return_value=result)logger = mocker.patch("posthog.temporal.session_replay.session_summary.event_capture.logger")from posthog.temporal.session_replay.session_summary.event_capture import capture_session_summary_readydiff --git a/products/conversations/backend/api/tests/test_events.py b/products/conversations/backend/api/tests/test_events.pyindex 4a7e6e2e184a..a27fb5be6c63 100644--- a/products/conversations/backend/api/tests/test_events.py+++ b/products/conversations/backend/api/tests/test_events.py@@ -40,7 +40,7 @@ class TestConversationEvents(BaseTest):anonymous_traits={"name": "Test Customer", "email": "[email protected]"},)- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")def test_capture_ticket_created_uses_team_token(self, mock_capture):capture_ticket_created(self.ticket)@@ -54,7 +54,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_routed")+ @patch("products.conversations.backend.events.capture_internal")def test_capture_ticket_status_changed_uses_team_token(self, mock_capture):capture_ticket_status_changed(self.ticket, "new", "pending", actor=self.user, actor_type="user")@@ -70,7 +70,7 @@ class TestConversationEvents(BaseTest):assert call_kwargs["properties"]["actor_id"] == self.user.idassert call_kwargs["properties"]["actor_email"] == self.user.email- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")def test_capture_ticket_priority_changed_uses_team_token(self, mock_capture):capture_ticket_priority_changed(self.ticket, None, "high", actor=self.user, actor_type="user")@@ -86,7 +86,7 @@ class TestConversationEvents(BaseTest):assert call_kwargs["properties"]["actor_id"] == self.user.idassert call_kwargs["properties"]["actor_email"] == self.user.email- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")def test_capture_ticket_assigned_uses_team_token(self, mock_capture):capture_ticket_assigned(self.ticket, "user", "123", actor=self.user, actor_type="user")@@ -102,7 +102,7 @@ class TestConversationEvents(BaseTest):assert call_kwargs["properties"]["actor_id"] == self.user.idassert call_kwargs["properties"]["actor_email"] == self.user.email- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")def test_capture_message_sent_uses_team_token(self, mock_capture):capture_message_sent(self.ticket, "msg-123", "Hello customer", author=self.user)@@ -129,7 +129,7 @@ class TestConversationEvents(BaseTest):("capture_message_sent", capture_message_sent, ["msg-id", "content"]),])- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")def test_customer_email_falls_back_to_email_from(self, _name, capture_fn, extra_args, mock_capture):self.ticket.anonymous_traits = {}self.ticket.email_from = "[email protected]"@@ -142,7 +142,7 @@ class TestConversationEvents(BaseTest):call_kwargs = mock_capture.call_args.kwargsassert call_kwargs["properties"]["customer_email"] == "[email protected]"- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")def test_capture_message_received_uses_team_token(self, mock_capture):capture_message_received(self.ticket, "msg-456", "Hello support")@@ -183,7 +183,7 @@ class TestConversationEvents(BaseTest):),])- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")def test_all_events_include_base_properties(self, _name, capture_fn, expected_event, extra_args, mock_capture):capture_fn(self.ticket, *extra_args)@@ -197,7 +197,7 @@ class TestConversationEvents(BaseTest):assert props["status"] == self.ticket.statusassert props["priority"] == self.ticket.priority- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")def test_message_content_truncated_to_1000_chars(self, mock_capture):long_content = "x" * 1500capture_message_sent(self.ticket, "msg-id", long_content, author=self.user)@@ -205,7 +205,7 @@ class TestConversationEvents(BaseTest):call_kwargs = mock_capture.call_args.kwargsassert len(call_kwargs["properties"]["message_content"]) == 1000- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")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@@ -221,7 +221,7 @@ class TestConversationEvents(BaseTest):assert call_kwargs["token"] == self.team.api_tokenassert call_kwargs["token"] != other_team.api_token- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")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@@ -263,7 +263,7 @@ class TestConversationEvents(BaseTest):("empty_distinct_id", False, False, False),])- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")@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@@ -296,7 +296,7 @@ class TestConversationEvents(BaseTest):assert call_kwargs["process_person_profile"] is expect_groupsassert "$groups" not in call_kwargs["properties"]- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")@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@@ -316,7 +316,7 @@ class TestConversationEvents(BaseTest):assert groups["project"] == str(self.team.uuid)assert "instance" in groups- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")@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@@ -343,7 +343,7 @@ class TestConversationEvents(BaseTest):("empty_distinct_id", False, False),])- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")@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@@ -376,7 +376,7 @@ class TestConversationEvents(BaseTest):assert call_kwargs["process_person_profile"] is Falseassert "$groups" not in call_kwargs["properties"]- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")@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")@@ -392,7 +392,7 @@ class TestConversationEvents(BaseTest):("user_has_no_membership", True, False),])- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")@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@@ -410,7 +410,7 @@ class TestConversationEvents(BaseTest):assert call_kwargs["process_person_profile"] is Falseassert "$groups" not in call_kwargs["properties"]- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")@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)@@ -429,7 +429,7 @@ class TestConversationEvents(BaseTest):("email_from_only", "email", None, "[email protected]"),])- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")@patch("products.conversations.backend.person_lookup._get_persons_by_email")@patch("products.conversations.backend.events.get_persons_by_distinct_ids")def test_capture_ticket_created_email_fallback_groups(@@ -478,7 +478,7 @@ class TestConversationEvents(BaseTest):("person_without_membership", True),])- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")@patch("products.conversations.backend.person_lookup._get_persons_by_email")@patch("products.conversations.backend.events.get_persons_by_distinct_ids")def test_capture_ticket_created_email_fallback_no_groups(@@ -512,7 +512,7 @@ class TestConversationEvents(BaseTest):assert call_kwargs["process_person_profile"] is Falseassert "$groups" not in call_kwargs["properties"]- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")@patch("products.conversations.backend.person_lookup._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(@@ -538,7 +538,7 @@ class TestConversationEvents(BaseTest):("github_no_email", "github"),])- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")@patch("products.conversations.backend.person_lookup._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(@@ -578,7 +578,7 @@ class TestConversationEvents(BaseTest):("without_customer", ""),])- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")@patch("posthog.hogql.query.execute_hogql_query")@patch("products.conversations.backend.events.get_group_types_for_project")@patch("products.conversations.backend.events.get_persons_by_distinct_ids")@@ -616,7 +616,7 @@ class TestConversationEvents(BaseTest):("empty_org_key", [["", ""]]),])- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")@patch("posthog.hogql.query.execute_hogql_query")@patch("products.conversations.backend.events.get_group_types_for_project")@patch("products.conversations.backend.events.get_persons_by_distinct_ids")@@ -635,7 +635,7 @@ class TestConversationEvents(BaseTest):assert call_kwargs["process_person_profile"] is Falseassert "$groups" not in call_kwargs["properties"]- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")@patch("posthog.hogql.query.execute_hogql_query")@patch("products.conversations.backend.events.get_persons_by_distinct_ids")def test_capture_ticket_created_membership_hit_skips_analytics_fallback(@@ -655,7 +655,7 @@ class TestConversationEvents(BaseTest):call_kwargs = mock_capture.call_args.kwargsassert call_kwargs["properties"]["$groups"]["organization"] == str(person_org.id)- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")@patch("posthog.hogql.query.execute_hogql_query")@patch("products.conversations.backend.events.get_group_types_for_project")@patch("products.conversations.backend.person_lookup._get_persons_by_email")@@ -695,7 +695,7 @@ class TestConversationEvents(BaseTest):("negative", [], False),])- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")@patch("posthog.hogql.query.execute_hogql_query")@patch("products.conversations.backend.events.get_group_types_for_project")@patch("products.conversations.backend.events.get_persons_by_distinct_ids")@@ -719,7 +719,7 @@ class TestConversationEvents(BaseTest):else:assert "$groups" not in call.kwargs["properties"]- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")def test_capture_ticket_status_changed_system_actor_uses_customer_distinct_id(self, mock_capture):"""System actions (e.g. snooze wake) use the customer's distinct_id, not an actor's."""capture_ticket_status_changed(self.ticket, "on_hold", "open", actor_type="system")@@ -731,7 +731,7 @@ class TestConversationEvents(BaseTest):assert call_kwargs["properties"]["actor_id"] is Noneassert call_kwargs["properties"]["actor_email"] is None- @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.capture_internal")def test_capture_ticket_status_changed_external_actor_uses_customer_distinct_id(self, mock_capture):"""External actions (e.g. GitHub sync) use the customer's distinct_id."""capture_ticket_status_changed(self.ticket, "open", "resolved", actor_type="external")diff --git a/products/conversations/backend/events.py b/products/conversations/backend/events.pyindex d44339db2e9b..a901bc467c8e 100644--- a/products/conversations/backend/events.py+++ b/products/conversations/backend/events.py@@ -10,7 +10,7 @@ from typing import Literalimport structlog-from posthog.api.capture_dispatch import capture_internal_routed+from posthog.api.capture import capture_internalfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.event_usage import groups as build_groupsfrom posthog.models.group_type_mapping import get_group_types_for_project@@ -249,7 +249,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_routed(+ capture_internal(token=team.api_token,event_name="$conversation_ticket_created",event_source=EVENT_SOURCE,@@ -272,7 +272,7 @@ def capture_ticket_status_changed(properties["new_status"] = new_statusproperties.update(_get_actor_properties(actor, actor_type))- capture_internal_routed(+ capture_internal(token=ticket.team.api_token,event_name="$conversation_ticket_status_changed",event_source=EVENT_SOURCE,@@ -294,7 +294,7 @@ def capture_ticket_priority_changed(properties["new_priority"] = new_priorityproperties.update(_get_actor_properties(actor, actor_type))- capture_internal_routed(+ capture_internal(token=ticket.team.api_token,event_name="$conversation_ticket_priority_changed",event_source=EVENT_SOURCE,@@ -316,7 +316,7 @@ def capture_ticket_assigned(properties["assignee_id"] = assignee_idproperties.update(_get_actor_properties(actor, actor_type))- capture_internal_routed(+ capture_internal(token=ticket.team.api_token,event_name="$conversation_ticket_assigned",event_source=EVENT_SOURCE,@@ -340,7 +340,7 @@ def capture_message_sent(properties.update(_get_actor_properties(author, "user"))properties.update(_get_customer_properties(ticket, include_distinct_id=True))- capture_internal_routed(+ capture_internal(token=ticket.team.api_token,event_name="$conversation_message_sent",event_source=EVENT_SOURCE,@@ -367,7 +367,7 @@ def capture_message_received(ticket: Ticket, message_id: str, message_content: sexcept Exception:logger.exception("message_received_person_lookup_failed", team_id=team.id, ticket_id=str(ticket.id))- capture_internal_routed(+ capture_internal(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.pyindex 17b99602fc78..0d7903045894 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, datetimeimport structlogfrom temporalio import activity-from posthog.api.capture_dispatch import capture_internal_routed+from posthog.api.capture import capture_internalfrom posthog.models.team import Teamfrom 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))- result = capture_internal_routed(+ result = capture_internal(token=team.api_token,event_name=_EVENT_NAME,event_source=_EVENT_SOURCE,