:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(capture): add capture_ai_internal for the AI lane (#95525)
Eli Reisman5723e54276c4
diff --git a/posthog/api/capture.py b/posthog/api/capture.pyindex 80455d97f140..219ab48f4802 100644--- a/posthog/api/capture.py+++ b/posthog/api/capture.py@@ -36,9 +36,11 @@ from requests.exceptions import RequestExceptionfrom posthog.dataclasses import frozenfrom posthog.security.outbound_proxy import internal_requests_sessionfrom posthog.settings.ingestion import (+ CAPTURE_AI_INTERNAL_URL,CAPTURE_INTERNAL_BATCH_CHUNK_SIZE,CAPTURE_INTERNAL_MAX_WORKERS,CAPTURE_INTERNAL_URL,+ CAPTURE_V1_AI_INTERNAL_ENDPOINT,CAPTURE_V1_INTERNAL_ENDPOINT,CAPTURE_V1_INTERNAL_MAX_ATTEMPTS,CAPTURE_V1_INTERNAL_RETRY_AFTER_CAP_SECONDS,@@ -53,6 +55,10 @@ logger = structlog.get_logger(__name__)SESSION_RECORDING_DEDICATED_KAFKA_EVENTS = ("$snapshot_items",)SESSION_RECORDING_EVENT_NAMES = ("$snapshot", "$performance_event", *SESSION_RECORDING_DEDICATED_KAFKA_EVENTS)+# Events whose names carry this prefix belong on the AI lane (capture-ai), not the+# analytics lane. See the lane check in `prepare_capture_internal_batch`.+AI_EVENT_NAME_PREFIX = "$ai_"+# --------------------------------------------------------------------------- ## Constants# --------------------------------------------------------------------------- #@@ -219,6 +225,15 @@ def _resolve_scalar(return legacy+@frozen+class EventIdentity:+ """The two fields the routing checks had to read, kept named so a caller+ cannot swap them: both are strings."""++ event_name: str+ distinct_id: str++@frozenclass NormalizedEventParts:options: dict[str, Any]@@ -227,6 +242,18 @@ class NormalizedEventParts:properties: dict[str, Any]+def _reject_unknown_option_keys(event_dict: dict[str, Any], *, event_source: str) -> None:+ """Refuse option keys the v1 envelope has no field for.++ Split out of normalization so the batch path can run it before publishing+ anything. It is a set difference, so running it in both places is cheaper+ than normalizing an event twice.+ """+ unknown = set((event_dict.get("options") or {}).keys()) - _VALID_OPTION_KEYS+ if unknown:+ raise CaptureInternalError(f"capture_internal ({event_source}): unknown option key(s): {sorted(unknown)}")++def _normalize_options_and_properties(event_dict: dict[str, Any],*,@@ -240,9 +267,7 @@ def _normalize_options_and_properties(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)}")+ _reject_unknown_option_keys(event_dict, event_source=event_source)options: dict[str, Any] = {}@@ -296,14 +321,66 @@ def _normalize_options_and_properties(# --------------------------------------------------------------------------- #-def _validate_batch_inputs(events: list[dict[str, Any]], *, token: str, event_source: str) -> None:+def _lane_fn_name(ai_lane: bool) -> str:+ """Name the entry point the caller actually used, so an error points at their code."""+ return "capture_ai_internal" if ai_lane else "capture_internal"+++def _validate_batch_inputs(+ events: list[dict[str, Any]], *, token: str, event_source: str, ai_lane: bool = False+) -> None:"""Validate required batch-level inputs. Raises CaptureInternalError on failure."""+ fn = _lane_fn_name(ai_lane)if not event_source:- raise CaptureInternalError("capture_internal: event_source is required (identifies the submitting call site)")+ raise CaptureInternalError(f"{fn}: event_source is required (identifies the submitting call site)")if not token:- raise CaptureInternalError(f"capture_internal ({event_source}): API token is required")+ raise CaptureInternalError(f"{fn} ({event_source}): API token is required")if not events:- raise CaptureInternalError(f"capture_internal ({event_source}): at least one event is required")+ raise CaptureInternalError(f"{fn} ({event_source}): at least one event is required")+++def _validate_event(ev: dict[str, Any], *, event_source: str, ai_lane: bool) -> EventIdentity:+ """Run every client-side check on one event, and return the two fields it read.++ Every rejection capture_internal can decide without the server belongs here,+ so `_capture_batch_impl` can clear a whole batch before submitting the first+ chunk. A chunked batch would otherwise publish its early chunks and raise on+ a later one, reporting failure after a partial ingestion.+ """+ fn = _lane_fn_name(ai_lane)++ event_name: str = ev.get("event", "")+ if not event_name:+ raise CaptureInternalError(f"{fn} ({event_source}): event name is required")++ if event_name in SESSION_RECORDING_EVENT_NAMES:+ raise CaptureInternalError(+ f"{fn} ({event_source}): '{event_name}' is a replay event; use the replay capture path"+ )++ # The `$ai_` prefix, matching capture's own v1 rule. A prefixed name capture+ # does not recognise still reaches the AI endpoint and is reported there as+ # `misrouted_event`, so the authority stays server-side.+ is_ai_event_name = event_name.startswith(AI_EVENT_NAME_PREFIX)+ if ai_lane and not is_ai_event_name:+ raise CaptureInternalError(+ f"capture_ai_internal ({event_source}): '{event_name}' is not an AI event; use capture_internal"+ )+ if is_ai_event_name and not ai_lane:+ raise CaptureInternalError(+ f"capture_internal ({event_source}): '{event_name}' is an AI event; use capture_ai_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 CaptureInternalError(f"capture_internal ({event_source}, {event_name}): distinct_id is required")++ _reject_unknown_option_keys(ev, event_source=event_source)++ return EventIdentity(event_name=event_name, distinct_id=distinct_id)def prepare_capture_internal_batch(@@ -313,33 +390,26 @@ def prepare_capture_internal_batch(event_source: str,historical_migration: bool = False,process_person_profile: bool = False,+ ai_lane: 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 theresults map.++ ``ai_lane`` selects which lane the batch is bound for and, with it, which+ event names are admissible. The two lanes are mutually exclusive: capture's+ v1 endpoints each refuse the other's traffic, so sending an event to the+ wrong one earns a per-event ``misrouted_event`` drop. Catching it here+ turns that into an immediate, actionable error at the call site instead."""- _validate_batch_inputs(events, token=token, event_source=event_source)+ _validate_batch_inputs(events, token=token, event_source=event_source, ai_lane=ai_lane)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")+ identity = _validate_event(ev, event_source=event_source, ai_lane=ai_lane)event_uuid: str = ev.get("event_uuid") or ev.get("uuid") or str(uuid4())uuids.append(event_uuid)@@ -359,9 +429,9 @@ def prepare_capture_internal_batch()entry: dict[str, Any] = {- "event": event_name,+ "event": identity.event_name,"uuid": event_uuid,- "distinct_id": distinct_id,+ "distinct_id": identity.distinct_id,"timestamp": timestamp_str,"properties": parts.properties,}@@ -397,6 +467,7 @@ def _submit_batch_chunk(process_person_profile: bool,max_attempts: int,timeout: float,+ ai_lane: bool = False,) -> CaptureInternalResult:"""Submit a single chunk of events to the v1 batch endpoint with retry logic.@@ -409,9 +480,15 @@ def _submit_batch_chunk(event_source=event_source,historical_migration=historical_migration,process_person_profile=process_person_profile,+ ai_lane=ai_lane,)- url = f"{CAPTURE_INTERNAL_URL}{CAPTURE_V1_INTERNAL_ENDPOINT}"+ # A different deployment, not just a different path: `/i/v1/ai/events` is+ # mounted only on capture-ai.+ if ai_lane:+ url = f"{CAPTURE_AI_INTERNAL_URL}{CAPTURE_V1_AI_INTERNAL_ENDPOINT}"+ else:+ 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))@@ -562,6 +639,83 @@ def _merge_results(chunk_results: list[CaptureInternalResult]) -> CaptureInternareturn merged+def _capture_batch_impl(+ *,+ events: list[dict[str, Any]],+ token: str,+ event_source: str,+ historical_migration: bool,+ process_person_profile: bool,+ max_attempts: int,+ timeout: float,+ ai_lane: bool,+) -> CaptureInternalResult:+ """Shared body of capture_batch_internal and capture_batch_ai_internal.++ The lane is not a public argument: callers pick it by choosing an entry point,+ so there is exactly one way to reach each lane.+ """+ _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,+ ai_lane=ai_lane,+ )++ # Hot path: small batch — submit directly, no threading overhead. One chunk+ # validates and posts in that order, so it needs no pre-pass.+ if len(events) <= chunk_size:+ return _submit_chunk(events)++ # Each worker validates only its own chunk, so clear the whole batch first+ # or a rejected event can follow chunks that already published.+ for ev in events:+ _validate_event(ev, event_source=event_source, ai_lane=ai_lane)++ # 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,+ total_events=len(events),+ chunks=len(chunks),+ chunk_size=chunk_size,+ max_workers=CAPTURE_INTERNAL_MAX_WORKERS,+ )++ chunk_results: list[CaptureInternalResult] = []+ with ThreadPoolExecutor(max_workers=CAPTURE_INTERNAL_MAX_WORKERS) as executor:+ 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 _merge_results(chunk_results)++def capture_batch_internal(*,events: list[dict[str, Any]],@@ -670,59 +824,17 @@ def capture_batch_internal((the HTTP status from capture-rs, or 0 for client-side/transport errors)."""# 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",+ return _capture_batch_impl(+ events=events,+ token=token,event_source=event_source,- total_events=len(events),- chunks=len(chunks),- chunk_size=chunk_size,- max_workers=CAPTURE_INTERNAL_MAX_WORKERS,+ historical_migration=historical_migration,+ process_person_profile=process_person_profile,+ max_attempts=max_attempts,+ timeout=timeout,+ ai_lane=False,)- chunk_results: list[CaptureInternalResult] = []- with ThreadPoolExecutor(max_workers=CAPTURE_INTERNAL_MAX_WORKERS) as executor:- 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 _merge_results(chunk_results)-def _parse_retry_after(header_value: Optional[str]) -> float:"""Parse Retry-After header, capped to the configured maximum."""@@ -740,6 +852,56 @@ def _parse_retry_after(header_value: Optional[str]) -> float:# --------------------------------------------------------------------------- #+def _capture_single_impl(+ *,+ token: str,+ event_name: str,+ event_source: str,+ distinct_id: str,+ timestamp: Optional[str | datetime],+ properties: Optional[dict[str, Any]],+ options: Optional[dict[str, Any]],+ session_id: Optional[str],+ window_id: Optional[str],+ event_uuid: Optional[str],+ process_person_profile: bool,+ historical_migration: bool,+ timeout: float,+ ai_lane: bool,+) -> CaptureInternalResult:+ """Shared body of capture_internal and capture_ai_internal.++ The lane is not a public argument: callers pick it by choosing an entry point,+ so there is exactly one way to reach each lane.+ """+ 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_batch_impl(+ events=[event_dict],+ token=token,+ event_source=event_source,+ historical_migration=historical_migration,+ process_person_profile=process_person_profile,+ max_attempts=CAPTURE_V1_INTERNAL_MAX_ATTEMPTS,+ timeout=timeout,+ ai_lane=ai_lane,+ )++def capture_internal(*,token: str,@@ -815,27 +977,111 @@ def capture_internal(``.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,- "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_batch_internal(- events=[event_dict],+ return _capture_single_impl(token=token,+ event_name=event_name,event_source=event_source,+ distinct_id=distinct_id,+ timestamp=timestamp,+ properties=properties,+ options=options,+ session_id=session_id,+ window_id=window_id,+ event_uuid=event_uuid,+ process_person_profile=process_person_profile,historical_migration=historical_migration,+ timeout=timeout,+ ai_lane=False,+ )+++def capture_ai_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,+ event_uuid: Optional[str] = None,+ process_person_profile: bool = False,+ timeout: float = 2,+) -> CaptureInternalResult:+ """+ capture_ai_internal is capture_internal for the AI lane. Use it for every `$ai_*`+ event submitted from the Django app on behalf of a customer team.++ Same arguments, return value, retry behaviour and per-event result semantics as+ capture_internal — see its docstring. The difference is the destination:+ `/i/v1/ai/events` on capture-ai rather than `/i/v1/analytics/events` on+ capture-analytics. That deployment is configured for AI traffic: an 8MiB per-event+ ceiling instead of 983040 bytes, and a direct produce to the AI topic.++ The two lanes are mutually exclusive and each refuses the other's traffic, so:++ * a non-`$ai_` event name here raises CaptureInternalError, and+ * an `$ai_` event name passed to capture_internal raises likewise.++ Both are client-side errors raised before any HTTP call, so a misrouted call site+ fails loudly at the point of the mistake rather than as a per-event drop later.++ ``historical_migration`` is not offered: AI backfills do not run through this path.++ Args:+ see capture_internal. ``session_id`` / ``window_id`` are omitted because they are+ replay concepts and carry no meaning on the AI lane.++ Returns:+ CaptureInternalResult with per-event outcome, exactly as capture_internal.++ Raises:+ CaptureInternalError: on client-side validation failures — including a non-AI+ event name — or HTTP/transport errors.+ """+ return _capture_single_impl(+ token=token,+ event_name=event_name,+ event_source=event_source,+ distinct_id=distinct_id,+ timestamp=timestamp,+ properties=properties,+ options=options,+ session_id=None,+ window_id=None,+ event_uuid=event_uuid,+ process_person_profile=process_person_profile,+ historical_migration=False,+ timeout=timeout,+ ai_lane=True,+ )+++def capture_batch_ai_internal(+ *,+ events: list[dict[str, Any]],+ token: str,+ event_source: str,+ process_person_profile: bool = False,+ max_attempts: int = CAPTURE_V1_INTERNAL_MAX_ATTEMPTS,+ timeout: float = 2,+) -> CaptureInternalResult:+ """+ capture_batch_ai_internal is capture_batch_internal for the AI lane.++ Same chunking, concurrency, retry rounds and per-event result merging — see+ capture_batch_internal's docstring. Every event in the batch must have an `$ai_`+ prefixed name; one that does not raises CaptureInternalError before anything is sent.++ ``historical_migration`` is not offered: AI backfills do not run through this path.+ """+ return _capture_batch_impl(+ events=events,+ token=token,+ event_source=event_source,+ historical_migration=False,process_person_profile=process_person_profile,+ max_attempts=max_attempts,timeout=timeout,+ ai_lane=True,)diff --git a/posthog/api/test/test_capture_internal.py b/posthog/api/test/test_capture_internal.pyindex c3f45aee7418..4e8217ff7176 100644--- a/posthog/api/test/test_capture_internal.py+++ b/posthog/api/test/test_capture_internal.py@@ -1,3 +1,4 @@+import inspectimport threadingfrom datetime import UTC, datetimefrom typing import Any@@ -21,13 +22,21 @@ from posthog.api.capture import (_normalize_options_and_properties,_parse_retry_after,_resolve_scalar,+ capture_ai_internal,+ capture_batch_ai_internal,capture_batch_internal,capture_internal,prepare_capture_internal_batch,)-from posthog.settings.ingestion import CAPTURE_INTERNAL_URL, CAPTURE_V1_INTERNAL_ENDPOINT+from posthog.settings.ingestion import (+ CAPTURE_AI_INTERNAL_URL,+ CAPTURE_INTERNAL_URL,+ CAPTURE_V1_AI_INTERNAL_ENDPOINT,+ CAPTURE_V1_INTERNAL_ENDPOINT,+)EXPECTED_URL = f"{CAPTURE_INTERNAL_URL}{CAPTURE_V1_INTERNAL_ENDPOINT}"+EXPECTED_AI_URL = f"{CAPTURE_AI_INTERNAL_URL}{CAPTURE_V1_AI_INTERNAL_ENDPOINT}"class MockResponse:@@ -1195,6 +1204,53 @@ class TestBatchChunking(SimpleTestCase):assert call["json"]["historical_migration"] is Trueassert call["json"]["capture_internal"] is True+ @parameterized.expand(+ [+ ("analytics_lane", "$ai_generation", False),+ ("ai_lane", "$pageview", True),+ ]+ )+ @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_misrouted_event_in_a_later_chunk_stops_the_whole_batch(+ self,+ _name: str,+ misrouted_event_name: str,+ ai_lane: bool,+ mock_session_fn: MagicMock,+ ) -> None:+ # Without the whole-batch pre-pass the first chunk publishes and the+ # caller is told the batch failed after 200 events already landed.+ events = _make_batch(201)+ if ai_lane:+ for ev in events[:200]:+ ev["event"] = "$ai_generation"+ events[200]["event"] = misrouted_event_name+ entry_point = capture_batch_ai_internal if ai_lane else capture_batch_internal+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results())])++ with self.assertRaises(CaptureInternalError):+ entry_point(events=events, token="tok", event_source="mixed_lanes")++ assert spy.calls == [], "a batch that fails validation must not publish any chunk"++ @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_bad_option_key_in_a_later_chunk_stops_the_whole_batch(self, mock_session_fn: MagicMock) -> None:+ # The routing checks are not the only client-side rejection: an unknown+ # option key is caught during normalization, which runs per chunk.+ events = _make_batch(201)+ events[200]["options"] = {"bogus_key": True}+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results())])++ with self.assertRaises(CaptureInternalError) as ctx:+ capture_batch_internal(events=events, token="tok", event_source="bad_option")++ assert "unknown option key" in str(ctx.exception)+ assert spy.calls == [], "a batch that fails validation must not publish any chunk"+class TestMergeResults(SimpleTestCase):def test_merge_all_success(self) -> None:@@ -1240,3 +1296,196 @@ class TestMergeResults(SimpleTestCase):assert merged.warnings == ["c"]assert merged.retried == ["d"]assert set(merged.results.keys()) == {"a", "b", "c", "d"}+++class TestAiLaneGate(SimpleTestCase):+ """The two lanes are mutually exclusive, and the gate runs before any HTTP call.++ Capture's v1 endpoints each refuse the other lane's traffic, so a misrouted call+ would come back as a per-event ``misrouted_event`` drop. Catching it client-side+ turns that into an error at the call site instead.+ """++ @parameterized.expand(+ [+ ("$ai_generation",),+ ("$ai_span",),+ ("$ai_evaluation",),+ # Prefixed but not a name capture routes to the AI lane. Django gates on+ # the prefix alone, so this still goes to the AI endpoint -- capture is+ # the authority on which names it accepts, and reports the rest as+ # `misrouted_event`.+ ("$ai_cache_usage",),+ ]+ )+ def test_ai_event_names_rejected_on_the_analytics_lane(self, event_name: str) -> None:+ with self.assertRaises(CaptureInternalError) as ctx:+ prepare_capture_internal_batch([_make_event(event=event_name)], token="tok", event_source="src")+ assert "is an AI event" in str(ctx.exception)+ assert "capture_ai_internal" in str(ctx.exception)++ @parameterized.expand([("$pageview",), ("custom_event",), ("$identify",), ("ai_generation",)])+ def test_non_ai_event_names_rejected_on_the_ai_lane(self, event_name: str) -> None:+ with self.assertRaises(CaptureInternalError) as ctx:+ prepare_capture_internal_batch(+ [_make_event(event=event_name)], token="tok", event_source="src", ai_lane=True+ )+ assert "is not an AI event" in str(ctx.exception)+ assert "capture_internal" in str(ctx.exception)++ def test_ai_event_accepted_on_the_ai_lane(self) -> None:+ payload, uuids = prepare_capture_internal_batch(+ [_make_event(event="$ai_generation")], token="tok", event_source="src", ai_lane=True+ )+ assert len(uuids) == 1+ assert payload["batch"][0]["event"] == "$ai_generation"++ def test_non_ai_event_accepted_on_the_analytics_lane(self) -> None:+ payload, uuids = prepare_capture_internal_batch(+ [_make_event(event="$pageview")], token="tok", event_source="src"+ )+ assert len(uuids) == 1+ assert payload["batch"][0]["event"] == "$pageview"++ def test_one_misrouted_event_rejects_the_whole_batch(self) -> None:+ events = [_make_event(event="$ai_generation"), _make_event(event="$pageview", distinct_id="u2")]+ with self.assertRaises(CaptureInternalError):+ prepare_capture_internal_batch(events, token="tok", event_source="src", ai_lane=True)+++class TestCaptureAiInternal(SimpleTestCase):+ @patch("posthog.api.capture.internal_requests_session")+ def test_posts_to_the_ai_endpoint(self, mock_session_fn: MagicMock) -> None:+ uid = str(uuid4())+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])++ result = capture_ai_internal(+ token="tok",+ event_name="$ai_generation",+ event_source="ai-src",+ distinct_id="user-1",+ event_uuid=uid,+ )++ assert result.succeeded()+ assert len(spy.calls) == 1+ assert spy.calls[0]["url"] == EXPECTED_AI_URL, "AI events must not go to the analytics deployment"++ @patch("posthog.api.capture.internal_requests_session")+ def test_analytics_capture_still_posts_to_the_analytics_endpoint(self, mock_session_fn: MagicMock) -> None:+ uid = str(uuid4())+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])++ capture_internal(token="tok", event_name="$pageview", event_source="src", distinct_id="user-1", event_uuid=uid)++ assert spy.calls[0]["url"] == EXPECTED_URL++ @patch("posthog.api.capture.internal_requests_session")+ def test_batch_ai_posts_to_the_ai_endpoint(self, mock_session_fn: MagicMock) -> None:+ uid1, uid2 = str(uuid4()), str(uuid4())+ events = [+ _make_event(event="$ai_generation", event_uuid=uid1),+ _make_event(event="$ai_span", distinct_id="u2", event_uuid=uid2),+ ]+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid1, uid2))])++ result = capture_batch_ai_internal(events=events, token="tok", event_source="ai-src")++ assert result.succeeded()+ assert set(result.ok) == {uid1, uid2}+ assert spy.calls[0]["url"] == EXPECTED_AI_URL++ @patch("posthog.api.capture.internal_requests_session")+ def test_rejects_before_any_http_call(self, mock_session_fn: MagicMock) -> None:+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body={})])++ with self.assertRaises(CaptureInternalError):+ capture_ai_internal(token="tok", event_name="$pageview", event_source="src", distinct_id="user-1")++ assert spy.calls == [], "a lane mistake must cost no round trip"++ @patch("posthog.api.capture.internal_requests_session")+ def test_server_side_misrouted_drop_surfaces_per_event(self, mock_session_fn: MagicMock) -> None:+ """Django gates on the prefix; capture gates on its own allowlist. A prefixed+ name capture does not accept comes back as a per-event drop, not an error."""+ uid = str(uuid4())+ body = {"results": {uid: {"result": "drop", "details": "misrouted_event"}}}+ InstallV1Spy(mock_session_fn, [MockResponse(body=body)])++ result = capture_ai_internal(+ token="tok",+ event_name="$ai_cache_usage",+ event_source="ai-src",+ distinct_id="user-1",+ event_uuid=uid,+ )++ assert not result.succeeded()+ assert result.dropped == [uid]+ assert result.results[uid]["details"] == "misrouted_event"+ with self.assertRaises(CaptureInternalError):+ result.raise_for_status()+++class TestLaneErrorMessages(SimpleTestCase):+ """An error must name the entry point the caller actually used, or it sends them+ looking at the wrong function."""++ def test_analytics_lane_errors_name_capture_internal(self) -> None:+ with self.assertRaises(CaptureInternalError) as ctx:+ prepare_capture_internal_batch([_make_event()], token="", event_source="src")+ assert "capture_internal (src)" in str(ctx.exception)+ assert "capture_ai_internal" not in str(ctx.exception)++ def test_ai_lane_errors_name_capture_ai_internal(self) -> None:+ with self.assertRaises(CaptureInternalError) as ctx:+ prepare_capture_internal_batch(+ [_make_event(event="$ai_generation")], token="", event_source="src", ai_lane=True+ )+ assert "capture_ai_internal (src)" in str(ctx.exception)++ def test_ai_lane_replay_rejection_names_the_ai_entry_point(self) -> None:+ with self.assertRaises(CaptureInternalError) as ctx:+ prepare_capture_internal_batch(+ [_make_event(event="$snapshot")], token="tok", event_source="src", ai_lane=True+ )+ assert "capture_ai_internal" in str(ctx.exception)+ assert "replay event" in str(ctx.exception)+++class TestLaneIsNotAPublicArgument(SimpleTestCase):+ """Callers pick a lane by choosing an entry point, never by passing a flag.++ Two ways to reach one lane would let a call site bypass the intended function,+ and the error messages — which name the entry point — would then misreport it.+ """++ @parameterized.expand(+ [+ ("capture_internal", capture_internal),+ ("capture_batch_internal", capture_batch_internal),+ ("capture_ai_internal", capture_ai_internal),+ ("capture_batch_ai_internal", capture_batch_ai_internal),+ ]+ )+ def test_public_senders_take_no_lane_flag(self, name: str, fn: Any) -> None:+ params = inspect.signature(fn).parameters+ assert "ai_lane" not in params, f"{name} must not expose the lane as an argument"++ @parameterized.expand(+ [+ ("capture_internal", capture_internal, EXPECTED_URL),+ ("capture_ai_internal", capture_ai_internal, EXPECTED_AI_URL),+ ]+ )+ @patch("posthog.api.capture.internal_requests_session")+ def test_each_entry_point_reaches_exactly_one_lane(+ self, name: str, fn: Any, expected_url: str, mock_session_fn: MagicMock+ ) -> None:+ uid = str(uuid4())+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])+ event_name = "$ai_generation" if "ai" in name.split("_") else "$pageview"++ fn(token="tok", event_name=event_name, event_source="src", distinct_id="u1", event_uuid=uid)++ assert spy.calls[0]["url"] == expected_urldiff --git a/posthog/settings/ingestion.py b/posthog/settings/ingestion.pyindex b83424e773da..19fe6f8c8290 100644--- a/posthog/settings/ingestion.py+++ b/posthog/settings/ingestion.py@@ -52,6 +52,10 @@ 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")+# The AI lane is a different capture deployment (capture-ai), not just a different path:+# `/i/v1/ai/events` is mounted only on CaptureMode::Ai, and capture-analytics refuses+# AI-lane event names. In the clusters this is capture-ai.capture-ai.svc.cluster.local.+CAPTURE_AI_INTERNAL_URL = os.getenv("CAPTURE_AI_INTERNAL_URL", "http://localhost:8010")# Internal OTLP/HTTP endpoint for first-party log emission into Logs (the `capture-logs` service,# path `/i/v1/logs`). The OTLP Bearer (a project token) routes records to a team's Logs. Defaults to@@ -79,6 +83,7 @@ NEW_ANALYTICS_CAPTURE_ENDPOINT = os.getenv("NEW_CAPTURE_ENDPOINT", "/i/v0/e/")CAPTURE_V1_INTERNAL_ENDPOINT = os.getenv("CAPTURE_V1_INTERNAL_ENDPOINT", "/i/v1/analytics/events")+CAPTURE_V1_AI_INTERNAL_ENDPOINT = os.getenv("CAPTURE_V1_AI_INTERNAL_ENDPOINT", "/i/v1/ai/events")CAPTURE_V1_INTERNAL_MAX_ATTEMPTS = get_from_env("CAPTURE_V1_INTERNAL_MAX_ATTEMPTS", type_cast=int, default=4)CAPTURE_V1_INTERNAL_RETRY_AFTER_CAP_SECONDS = get_from_env("CAPTURE_V1_INTERNAL_RETRY_AFTER_CAP_SECONDS", type_cast=float, default=5.0diff --git a/posthog/temporal/ai_observability/evaluation_workflow_activities.py b/posthog/temporal/ai_observability/evaluation_workflow_activities.pyindex 94e726b888d6..377271e1d712 100644--- a/posthog/temporal/ai_observability/evaluation_workflow_activities.py+++ b/posthog/temporal/ai_observability/evaluation_workflow_activities.py@@ -24,7 +24,7 @@ from posthog.temporal.ai_observability.evaluation_llm_judge import DEFAULT_JUDGEfrom posthog.temporal.ai_observability.evaluation_sentiment import run_sentiment_evalfrom posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResultfrom posthog.temporal.ai_observability.metrics import increment_emit_event_outcome-from posthog.temporal.ai_observability.team_capture import capture_internal_for_team+from posthog.temporal.ai_observability.team_capture import capture_ai_internal_for_teamfrom products.ai_observability.backend.models.evaluations import Evaluation, EvaluationStatusfrom products.ai_observability.backend.models.provider_keys import LLMProviderKey@@ -354,7 +354,7 @@ async def emit_generation_evaluation_event(inputs: EmitEvaluationEventInputs) ->if source_props.get(property_name) is not None:properties[property_name] = source_props[property_name]- capture_internal_for_team(+ capture_ai_internal_for_team(team_id=event_data["team_id"],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 963b563cd161..d5117e9ed0f1 100644--- a/posthog/temporal/ai_observability/run_tagger.py+++ b/posthog/temporal/ai_observability/run_tagger.py@@ -16,7 +16,7 @@ from posthog.temporal.ai_observability.evaluation_event_io import extract_event_from posthog.temporal.ai_observability.evaluation_workflow_activities import update_key_state_activityfrom posthog.temporal.ai_observability.message_utils import extract_text_from_messagesfrom posthog.temporal.ai_observability.model_resolution import model_spec-from posthog.temporal.ai_observability.team_capture import capture_internal_for_team+from posthog.temporal.ai_observability.team_capture import capture_ai_internal_for_teamfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.scoped import scoped_temporal@@ -513,7 +513,7 @@ async def emit_tagger_event_activity(inputs: EmitTaggerEventInputs) -> None:})- capture_internal_for_team(+ capture_ai_internal_for_team(team_id=event_data["team_id"],event_name="$ai_tag",event_source="llm_analytics_tagger",diff --git a/posthog/temporal/ai_observability/run_trace_evaluation.py b/posthog/temporal/ai_observability/run_trace_evaluation.pyindex fbedbe859422..62d479b886e1 100644--- a/posthog/temporal/ai_observability/run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/run_trace_evaluation.py@@ -69,7 +69,7 @@ from posthog.temporal.ai_observability.run_evaluation import (handle_llm_judge_activity_error,handle_terminal_user_error_result,)-from posthog.temporal.ai_observability.team_capture import capture_internal_for_team+from posthog.temporal.ai_observability.team_capture import capture_ai_internal_for_teamfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.utils import close_db_connections@@ -698,7 +698,7 @@ async def emit_trace_evaluation_event_activity(inputs: EmitTraceEvaluationEventIelse:timestamp = datetime.now(UTC)- capture_internal_for_team(+ capture_ai_internal_for_team(team_id=inputs.team_id,event_name="$ai_evaluation",event_source="llm_analytics_evaluation",diff --git a/posthog/temporal/ai_observability/team_capture.py b/posthog/temporal/ai_observability/team_capture.pyindex ae46688eb511..7932d9530da5 100644--- a/posthog/temporal/ai_observability/team_capture.py+++ b/posthog/temporal/ai_observability/team_capture.py@@ -1,7 +1,7 @@"""Emitting AI observability events on behalf of a team, without a Postgres read per event.Every emitted `$ai_evaluation` / `$ai_tag` event needs the team's `api_token` to call-`capture_internal`. Those emit closures run under `database_sync_to_async(thread_sensitive=False)`,+`capture_ai_internal`. Those emit closures run under `database_sync_to_async(thread_sensitive=False)`,so each one lands on a fresh executor thread and grabs a pooled Postgres connection for asingle-row read — under pool pressure pgbouncer answers with `query_wait_timeout` instead.`api_token` is effectively static, so cache it per worker process and only pay for the query@@ -14,7 +14,7 @@ from datetime import datetimefrom http import HTTPStatusfrom typing import Any-from posthog.api.capture import CaptureInternalError, capture_internal+from posthog.api.capture import CaptureInternalError, capture_ai_internalfrom posthog.models.team import Team# Also bounds how long emits keep using a rotated token: capture-rs accepts stale tokens at@@ -66,7 +66,7 @@ def clear_team_api_token_cache() -> None:_cache.clear()-def capture_internal_for_team(+def capture_ai_internal_for_team(*,team_id: int,event_name: str,@@ -77,10 +77,15 @@ def capture_internal_for_team(process_person_profile: bool = True,event_uuid: str | None = None,) -> None:- """Capture one event for a team, raising on a non-2xx capture response."""+ """Capture one AI event for a team, raising on a non-2xx capture response.++ Every caller here emits `$ai_*` events, so this goes to the AI lane+ (`/i/v1/ai/events` on capture-ai). `capture_ai_internal` rejects a non-AI event+ name client-side, before any HTTP call.+ """token = get_team_api_token(team_id)try:- result = capture_internal(+ result = capture_ai_internal(token=token,event_name=event_name,event_source=event_source,diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex 23328ffd94e3..675dc737fcf0 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -480,7 +480,7 @@ class TestRunEvaluationWorkflow:}with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token") as mock_team_get:- with patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture:+ with patch("posthog.temporal.ai_observability.team_capture.capture_ai_internal") as mock_capture:mock_team_get.return_value = team.api_tokenmock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())@@ -530,7 +530,7 @@ class TestRunEvaluationWorkflow:}with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token", return_value=team.api_token):- with patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture:+ with patch("posthog.temporal.ai_observability.team_capture.capture_ai_internal") as mock_capture:mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())await emit_evaluation_event_activity(@@ -597,7 +597,7 @@ class TestRunEvaluationWorkflow:return_value=team.api_token,):with patch(- "posthog.temporal.ai_observability.team_capture.capture_internal",+ "posthog.temporal.ai_observability.team_capture.capture_ai_internal",return_value=capture_result,):if should_raise:@@ -638,7 +638,7 @@ class TestRunEvaluationWorkflow:}with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token") as mock_team_get:- with patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture:+ with patch("posthog.temporal.ai_observability.team_capture.capture_ai_internal") as mock_capture:mock_team_get.return_value = team.api_tokenmock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())@@ -694,7 +694,7 @@ class TestRunEvaluationWorkflow:}with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token") as mock_team_get:- with patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture:+ with patch("posthog.temporal.ai_observability.team_capture.capture_ai_internal") as mock_capture:mock_team_get.return_value = team.api_tokenmock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())@@ -739,7 +739,7 @@ class TestRunEvaluationWorkflow:}with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token") as mock_team_get:- with patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture:+ with patch("posthog.temporal.ai_observability.team_capture.capture_ai_internal") as mock_capture:mock_team_get.return_value = team.api_tokenmock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())@@ -848,7 +848,7 @@ class TestRunEvaluationWorkflow:with (patch(HYDRATE_FETCH, return_value=full_event) as mock_fetch,patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_for_team"+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_ai_internal_for_team") as mock_capture,):await emit_evaluation_event_activity(@@ -1486,7 +1486,7 @@ class TestRunEvaluationWorkflow:}with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token") as mock_team_get:- with patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture:+ with patch("posthog.temporal.ai_observability.team_capture.capture_ai_internal") as mock_capture:mock_team_get.return_value = team.api_tokenmock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())@@ -1529,7 +1529,7 @@ class TestRunEvaluationWorkflow:}with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token") as mock_team_get:- with patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture:+ with patch("posthog.temporal.ai_observability.team_capture.capture_ai_internal") as mock_capture:mock_team_get.return_value = team.api_tokenmock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())@@ -2780,7 +2780,7 @@ class TestRunLocalEvaluationActivity:)with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_for_team"+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_ai_internal_for_team") as mock_capture:await run_local_evaluation_activity(inputs)@@ -2804,7 +2804,7 @@ class TestRunLocalEvaluationActivity:start_time = self.START_TIMEwith patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_for_team"+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_ai_internal_for_team") as mock_capture:outcome = await run_local_evaluation_activity(self._inputs(evaluation, team, start_time))@@ -2825,7 +2825,7 @@ class TestRunLocalEvaluationActivity:evaluation = await sync_to_async(self._create_hog_evaluation)(team, "return 42")with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_for_team"+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_ai_internal_for_team") as mock_capture:outcome = await run_local_evaluation_activity(self._inputs(evaluation, team, self.START_TIME))@@ -2841,7 +2841,7 @@ class TestRunLocalEvaluationActivity:team = setup_data["team"]with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_for_team"+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_ai_internal_for_team") as mock_capture:outcome = await run_local_evaluation_activity(self._inputs(evaluation, team, self.START_TIME))@@ -2876,7 +2876,7 @@ class TestRunLocalEvaluationActivity:)with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_for_team"+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_ai_internal_for_team") as mock_capture:outcome = await run_local_evaluation_activity(inputs)@@ -2899,7 +2899,7 @@ class TestRunLocalEvaluationActivity:evaluation = await sync_to_async(self._create_hog_evaluation)(team, "return true")with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_for_team"+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_ai_internal_for_team") as mock_capture:mock_capture.side_effect = Exception("capture down")with pytest.raises(ApplicationError) as exc_info:@@ -2918,7 +2918,7 @@ class TestRunLocalEvaluationActivity:env = ActivityEnvironment()with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_for_team"+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_ai_internal_for_team") as mock_capture:await env.run(run_local_evaluation_activity, inputs)await env.run(run_local_evaluation_activity, inputs)diff --git a/posthog/temporal/ai_observability/test_run_tagger.py b/posthog/temporal/ai_observability/test_run_tagger.pyindex b2dbae0684ab..665ee3c67c9d 100644--- a/posthog/temporal/ai_observability/test_run_tagger.py+++ b/posthog/temporal/ai_observability/test_run_tagger.py@@ -392,7 +392,7 @@ class TestRunTaggerWorkflow:event_data = create_mock_event_data(team.id, properties={})with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token") as mock_team_get:- with patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture:+ with patch("posthog.temporal.ai_observability.team_capture.capture_ai_internal") as mock_capture:mock_team_get.return_value = team.api_tokenmock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())@@ -459,7 +459,9 @@ class TestRunTaggerWorkflow:)with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token", return_value=team.api_token):- with patch("posthog.temporal.ai_observability.team_capture.capture_internal", return_value=capture_result):+ with patch(+ "posthog.temporal.ai_observability.team_capture.capture_ai_internal", return_value=capture_result+ ):if should_raise:with pytest.raises(CaptureInternalError):await emit_tagger_event_activity(inputs)diff --git a/posthog/temporal/ai_observability/test_run_trace_evaluation.py b/posthog/temporal/ai_observability/test_run_trace_evaluation.pyindex 29b95a8e8ad4..824409fbaee4 100644--- a/posthog/temporal/ai_observability/test_run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_trace_evaluation.py@@ -663,7 +663,7 @@ class TestEmitTraceEvaluationEventActivity:}with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token", return_value=team.api_token):- with patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture:+ with patch("posthog.temporal.ai_observability.team_capture.capture_ai_internal") as mock_capture:mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())await emit_trace_evaluation_event_activity(@@ -719,7 +719,7 @@ class TestEmitTraceEvaluationEventActivity:with (time_machine.travel(FROZEN_NOW, tick=False),patch("posthog.temporal.ai_observability.team_capture.get_team_api_token", return_value=team.api_token),- patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture,+ patch("posthog.temporal.ai_observability.team_capture.capture_ai_internal") as mock_capture,):mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())@@ -790,7 +790,9 @@ class TestEmitTraceEvaluationEventActivity:)with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token", return_value=team.api_token):- with patch("posthog.temporal.ai_observability.team_capture.capture_internal", return_value=capture_result):+ with patch(+ "posthog.temporal.ai_observability.team_capture.capture_ai_internal", return_value=capture_result+ ):if should_raise:with pytest.raises(CaptureInternalError):await emit_trace_evaluation_event_activity(inputs)@@ -823,7 +825,7 @@ class TestEmitSessionEvaluationEvent:with (patch("posthog.temporal.ai_observability.team_capture.get_team_api_token", return_value="phc_test"),- patch("posthog.temporal.ai_observability.team_capture.capture_internal", side_effect=_capture),+ patch("posthog.temporal.ai_observability.team_capture.capture_ai_internal", side_effect=_capture),):async_to_sync(emit_trace_evaluation_event_activity)(EmitTraceEvaluationEventInputs(@@ -860,7 +862,7 @@ class TestEmitSessionEvaluationEvent:with (patch("posthog.temporal.ai_observability.team_capture.get_team_api_token", return_value="phc_test"),- patch("posthog.temporal.ai_observability.team_capture.capture_internal", side_effect=_capture),+ patch("posthog.temporal.ai_observability.team_capture.capture_ai_internal", side_effect=_capture),):async_to_sync(emit_trace_evaluation_event_activity)(EmitTraceEvaluationEventInputs(diff --git a/posthog/temporal/ai_observability/test_team_capture.py b/posthog/temporal/ai_observability/test_team_capture.pyindex 48012ecacd6b..e4b68ee62003 100644--- a/posthog/temporal/ai_observability/test_team_capture.py+++ b/posthog/temporal/ai_observability/test_team_capture.py@@ -11,13 +11,13 @@ from posthog.models.team import Teamfrom posthog.temporal.ai_observability.team_capture import (TOKEN_CACHE_TTL_SECONDS,TeamNotFound,- capture_internal_for_team,+ capture_ai_internal_for_team,get_team_api_token,)def _emit(team_id: int) -> None:- capture_internal_for_team(+ capture_ai_internal_for_team(team_id=team_id,event_name="$ai_evaluation",event_source="llm_analytics_evaluation",@@ -51,14 +51,14 @@ class TestTeamCapture(BaseTest):def test_auth_rejection_invalidates_the_cached_token(self):get_team_api_token(self.team.id)with patch(- "posthog.temporal.ai_observability.team_capture.capture_internal",+ "posthog.temporal.ai_observability.team_capture.capture_ai_internal",side_effect=CaptureInternalError("unauthorized", status_code=401),):with self.assertRaises(CaptureInternalError):_emit(self.team.id)with patch(- "posthog.temporal.ai_observability.team_capture.capture_internal",+ "posthog.temporal.ai_observability.team_capture.capture_ai_internal",return_value=MagicMock(raise_for_status=MagicMock()),) as mock_capture:with self.assertNumQueries(1):@@ -75,14 +75,14 @@ class TestTeamCapture(BaseTest):def test_non_auth_capture_failure_keeps_the_cached_token(self, _name, error):get_team_api_token(self.team.id)with patch(- "posthog.temporal.ai_observability.team_capture.capture_internal",+ "posthog.temporal.ai_observability.team_capture.capture_ai_internal",side_effect=error,):with self.assertRaises(CaptureInternalError):_emit(self.team.id)with patch(- "posthog.temporal.ai_observability.team_capture.capture_internal",+ "posthog.temporal.ai_observability.team_capture.capture_ai_internal",return_value=MagicMock(raise_for_status=MagicMock()),):with self.assertNumQueries(0):