Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(capture): route internal capture by $ai_ prefix and mount v1 AI lane locally (#103269)

Eli Reisman4ab469db39ed
diff --git a/bin/start-rust-service b/bin/start-rust-service
index 0b1eaf481147..bbf9dfb38717 100755
--- a/bin/start-rust-service
+++ b/bin/start-rust-service
@@ -101,6 +101,17 @@ case "$RS_SVC" in
export LOG_LEVEL=debug
export DEBUG=1
export DEV_RUST_SVC_OVERRIDE=capture # we want to run the same "capture" binary in a separate mode
+ # v1 sink for `/i/v1/ai/events` (Django's capture_ai_internal). The sink config
+ # requires every topic var; `ai` mode only produces to the AI topic.
+ export CAPTURE_V1_SINKS=${CAPTURE_V1_SINKS:-msk}
+ export CAPTURE_V1_SINK_MSK_KAFKA_HOSTS=${CAPTURE_V1_SINK_MSK_KAFKA_HOSTS:-$DEFAULT_KAFKA}
+ export CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_MAIN=${CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_MAIN:-events_plugin_ingestion_ai}
+ export CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_HISTORICAL=${CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_HISTORICAL:-events_plugin_ingestion_ai}
+ export CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_OVERFLOW=${CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_OVERFLOW:-events_plugin_ingestion_ai}
+ export CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_DLQ=${CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_DLQ:-events_plugin_ingestion_dlq}
+ export CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_EXCEPTION=${CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_EXCEPTION:-ingestion-errortracking-main}
+ export CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_HEATMAP=${CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_HEATMAP:-heatmaps_ingestion}
+ export CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_CLIENT_INGESTION_WARNING=${CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_CLIENT_INGESTION_WARNING:-ingestion-clientwarnings-main-1}
;;
capture-logs)
diff --git a/bin/verify-ai-ingestion-stack b/bin/verify-ai-ingestion-stack
index 2eb45de65283..9f1d8cf43b4a 100755
--- a/bin/verify-ai-ingestion-stack
+++ b/bin/verify-ai-ingestion-stack
@@ -1,40 +1,66 @@
#!/usr/bin/env bash
-# Verifies capture-ai -> Kafka -> combined ingestion's AI consumer (blob offload) -> ClickHouse ai_events.
+# Verifies capture-ai -> Kafka -> combined ingestion's AI consumer (blob offload) -> ClickHouse ai_events,
+# once through the v0 batch endpoint SDKs use and once through the v1 endpoint Django's internal capture uses.
set -euo pipefail
PROXY="${PROXY:-http://localhost:8010}"
API_KEY="${API_KEY:?set API_KEY to a project api_token}"
-TRACE_ID="verify-$(uuidgen | tr '[:upper:]' '[:lower:]')"
# Must stay over AI_BLOB_OFFLOAD_MIN_BASE64_LENGTH (20480) or ingestion leaves the image inline.
BLOB="$(head -c 18750 /dev/urandom | base64 | tr -d '\n' | head -c 25000)"
+CID="$(docker ps -q -f name=clickhouse | head -1)"
+
+lower_uuid() { uuidgen | tr '[:upper:]' '[:lower:]'; }
+
+ai_generation_properties() {
+ local trace_id="$1"
+ printf '{"$ai_trace_id":"%s","$ai_model":"gpt-4o-mini","$ai_provider":"openai","$ai_input":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,%s"}}]}]}' \
+ "$trace_id" "$BLOB"
+}
+
+await_offloaded_row() {
+ local trace_id="$1" label="$2"
+ for _ in $(seq 1 30); do
+ INPUT="$(docker exec "$CID" clickhouse-client -q \
+ "SELECT input FROM posthog.ai_events WHERE trace_id = '$trace_id' LIMIT 1" 2>/dev/null || true)"
+ if [ -n "$INPUT" ]; then
+ case "$INPUT" in
+ *phaiblob://*) echo "PASS ($label): offloaded to a blob pointer"; return 0 ;;
+ *) echo "FAIL ($label): row landed but was not offloaded (no phaiblob:// pointer):"; echo "$INPUT" | head -c 300; return 1 ;;
+ esac
+ fi
+ sleep 2
+ done
+ echo "FAIL ($label): no ai_events row for trace_id=$trace_id after 60s"
+ return 1
+}
-echo "Posting \$ai_generation with trace_id=$TRACE_ID"
+V0_TRACE_ID="verify-v0-$(lower_uuid)"
+echo "Posting \$ai_generation to /i/v0/ai/batch/ with trace_id=$V0_TRACE_ID"
curl -sS -f -X POST "$PROXY/i/v0/ai/batch/" \
-H 'Content-Type: application/json' \
-d "{\"api_key\":\"$API_KEY\",\"batch\":[{
\"event\":\"\$ai_generation\",
\"distinct_id\":\"verify-user\",
- \"properties\":{
- \"\$ai_trace_id\":\"$TRACE_ID\",
- \"\$ai_model\":\"gpt-4o-mini\",
- \"\$ai_provider\":\"openai\",
- \"\$ai_input\":[{\"role\":\"user\",\"content\":[
- {\"type\":\"image_url\",\"image_url\":{\"url\":\"data:image/png;base64,$BLOB\"}}
- ]}]
- }}]}" >/dev/null
+ \"properties\":$(ai_generation_properties "$V0_TRACE_ID")}]}" >/dev/null
+await_offloaded_row "$V0_TRACE_ID" "v0"
-CID="$(docker ps -q -f name=clickhouse | head -1)"
-for _ in $(seq 1 30); do
- INPUT="$(docker exec "$CID" clickhouse-client -q \
- "SELECT input FROM posthog.ai_events WHERE trace_id = '$TRACE_ID' LIMIT 1" 2>/dev/null || true)"
- if [ -n "$INPUT" ]; then
- case "$INPUT" in
- *phaiblob://*) echo "PASS: offloaded to a blob pointer"; exit 0 ;;
- *) echo "FAIL: row landed but was not offloaded (no phaiblob:// pointer):"; echo "$INPUT" | head -c 300; exit 1 ;;
- esac
- fi
- sleep 2
-done
-echo "FAIL: no ai_events row for trace_id=$TRACE_ID after 60s"
-exit 1
+# Same headers Django's capture_ai_internal sends (posthog/api/capture.py _build_v1_headers).
+V1_TRACE_ID="verify-v1-$(lower_uuid)"
+NOW="$(date -u +%Y-%m-%dT%H:%M:%S.000Z)"
+echo "Posting \$ai_generation to /i/v1/ai/events with trace_id=$V1_TRACE_ID"
+curl -sS -f -X POST "$PROXY/i/v1/ai/events" \
+ -H "Authorization: Bearer $API_KEY" \
+ -H 'Content-Type: application/json' \
+ -H 'User-Agent: verify-ai-ingestion-stack/1.0' \
+ -H 'PostHog-Sdk-Info: verify-ai-ingestion-stack/1.0' \
+ -H 'PostHog-Attempt: 1' \
+ -H "PostHog-Request-Id: $(lower_uuid)" \
+ -H "PostHog-Request-Timestamp: $NOW" \
+ -d "{\"created_at\":\"$NOW\",\"batch\":[{
+ \"event\":\"\$ai_generation\",
+ \"uuid\":\"$(lower_uuid)\",
+ \"distinct_id\":\"verify-user\",
+ \"timestamp\":\"$NOW\",
+ \"properties\":$(ai_generation_properties "$V1_TRACE_ID")}]}" >/dev/null
+await_offloaded_row "$V1_TRACE_ID" "v1"
diff --git a/docker-compose.base.yml b/docker-compose.base.yml
index bd162a8f03c9..f83d6f799a0f 100644
--- a/docker-compose.base.yml
+++ b/docker-compose.base.yml
@@ -29,6 +29,8 @@ services:
path /i/v0/ai
path /i/v0/ai/
path /i/v0/ai/*
+ path /i/v1/ai/events
+ path /i/v1/ai/events/
}
@capture {
@@ -421,6 +423,17 @@ services:
# matching the production capture-ai deployment.
CAPTURE_MODE: ai
RUST_LOG: 'info,rdkafka=warn'
+ # v1 sink for `/i/v1/ai/events` (Django's capture_ai_internal). The sink config
+ # requires every topic var; `ai` mode only produces to the AI topic.
+ CAPTURE_V1_SINKS: 'msk'
+ CAPTURE_V1_SINK_MSK_KAFKA_HOSTS: 'kafka:9092'
+ CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_MAIN: 'events_plugin_ingestion_ai'
+ CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_HISTORICAL: 'events_plugin_ingestion_ai'
+ CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_OVERFLOW: 'events_plugin_ingestion_ai'
+ CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_DLQ: 'events_plugin_ingestion_dlq'
+ CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_EXCEPTION: 'ingestion-errortracking-main'
+ CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_HEATMAP: 'heatmaps_ingestion'
+ CAPTURE_V1_SINK_MSK_KAFKA_TOPIC_CLIENT_INGESTION_WARNING: 'ingestion-clientwarnings-main-1'
capture-logs:
image: ghcr.io/posthog/posthog/capture-logs:master
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index c31ba9466657..32ca54beca2f 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -46,6 +46,8 @@ services:
@capture-ai {
path /i/v0/ai
path /i/v0/ai/*
+ path /i/v1/ai/events
+ path /i/v1/ai/events/
}
@capture {
diff --git a/posthog/api/capture.py b/posthog/api/capture.py
index 0003ff32ab62..450c7672ffba 100644
--- a/posthog/api/capture.py
+++ b/posthog/api/capture.py
@@ -55,8 +55,7 @@ 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`.
+# `_capture_batch_impl` sends every event with this prefix to capture-ai.
AI_EVENT_NAME_PREFIX = "$ai_"
# --------------------------------------------------------------------------- #
@@ -93,7 +92,7 @@ CAPTURE_V1_BATCH_SUBMITTED = Counter(
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"],
+ labelnames=["event_source", "lane"],
)
CAPTURE_V1_EVENT_SUBMITTED = Counter(
"capture_v1_internal_event_submitted",
@@ -108,7 +107,7 @@ CAPTURE_V1_EVENT_RESULT = Counter(
CAPTURE_V1_REQUEST_FAILED = Counter(
"capture_v1_internal_request_failed",
"Whole-request failures from capture v1 endpoint.",
- labelnames=["event_source", "status_code"],
+ labelnames=["event_source", "status_code", "lane"],
)
CAPTURE_V1_RESUBMIT = Counter(
"capture_v1_internal_resubmit",
@@ -120,6 +119,11 @@ CAPTURE_V1_OPTION_CONFLICT = Counter(
"Typed option input disagreed with a legacy property; explicit won.",
labelnames=["event_source", "field"],
)
+CAPTURE_V1_EVENTS_REROUTED = Counter(
+ "capture_v1_internal_events_rerouted",
+ "Events whose name put them on the other lane than the entry point the caller used.",
+ labelnames=["event_source", "from_lane"],
+)
# --------------------------------------------------------------------------- #
# Errors & result type
@@ -143,9 +147,25 @@ class CaptureInternalError(Exception):
return self.status_code == HTTPStatus.PAYMENT_REQUIRED
-@dataclass
+@frozen
+class RequestFailure:
+ """One HTTP submission that failed as a whole; its events are in ``unaccounted``."""
+
+ lane: str
+ status_code: int
+ error: dict[str, Any]
+ event_count: int
+
+
+# Mutable on purpose: _submit_batch_chunk and _merge_results build it up in place.
+@dataclass(frozen=False)
class CaptureInternalResult:
- """Aggregated outcome of a (possibly multi-round) v1 batch submission."""
+ """Outcome of one v1 batch submission across all of its requests.
+
+ Every submitted uuid lands in exactly one of ``ok``, ``dropped``, ``warnings``,
+ ``retried`` or ``unaccounted``. A multi-request batch can be partially acked, so
+ retry only ``unaccounted`` and ``retried`` uuids, never the whole batch.
+ """
status_code: int
results: dict[str, dict[str, Any]] = field(default_factory=dict)
@@ -156,6 +176,7 @@ class CaptureInternalResult:
warnings: list[str] = field(default_factory=list)
retried: list[str] = field(default_factory=list)
unaccounted: list[str] = field(default_factory=list)
+ request_failures: list[RequestFailure] = 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
@@ -167,9 +188,13 @@ class CaptureInternalResult:
def raise_for_status(self) -> None:
if self.error:
+ acked = len(self.ok) + len(self.warnings)
+ scope = "partial-request" if acked else "whole-request"
+ lanes = ", ".join(f"{rf.lane} {rf.status_code}" for rf in self.request_failures) or str(self.status_code)
raise CaptureInternalError(
- f"capture internal whole-request failure ({self.status_code}): "
- f"{self.error.get('error', 'unknown')}: {self.error.get('error_description', '')}",
+ f"capture internal {scope} failure ({lanes}): "
+ f"{self.error.get('error', 'unknown')}: {self.error.get('error_description', '')}; "
+ f"{acked} events acked, {len(self.unaccounted)} unaccounted",
status_code=self.status_code,
)
failures = len(self.dropped) + len(self.retried) + len(self.unaccounted)
@@ -321,6 +346,10 @@ def _normalize_options_and_properties(
# --------------------------------------------------------------------------- #
+def _lane_label(ai_lane: bool) -> str:
+ return "ai" if ai_lane else "analytics"
+
+
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"
@@ -340,50 +369,54 @@ def _validate_batch_inputs(
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 client-side rejection lives here so a batch is cleared before its first chunk publishes.
- 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.
+ ``ai_lane`` only names the entry point in error messages; the wire lane is chosen
+ per event from the `$ai_` prefix.
"""
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")
+ event_name = ev.get("event", "")
+ if not isinstance(event_name, str) or not event_name:
+ raise CaptureInternalError(f"{fn} ({event_source}): event name is required and must be a non-empty string")
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 what billing's `is_llm_event` already keys on.
- # Capture's AI endpoint admits a narrower allowlist, so a prefixed name it
- # does not recognise is refused there as `non_ai_event`, which keeps the
- # authority 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"
- )
+ # Normalization would otherwise fail on these inside a worker, after other chunks published.
+ for key in ("properties", "options"):
+ value = ev.get(key)
+ if value is not None and not isinstance(value, dict):
+ raise CaptureInternalError(f"{fn} ({event_source}, {event_name}): {key} must be a dict")
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")
+ raise CaptureInternalError(f"{fn} ({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 _validate_batch_events(events: list[dict[str, Any]], *, event_source: str, ai_lane: bool) -> None:
+ """Validate every event and reject duplicate uuids: results are keyed by uuid, so a
+ duplicate would overwrite one event's outcome."""
+ fn = _lane_fn_name(ai_lane)
+ seen_uuids: set[str] = set()
+ for ev in events:
+ _validate_event(ev, event_source=event_source, ai_lane=ai_lane)
+ event_uuid = ev.get("event_uuid") or ev.get("uuid")
+ if event_uuid:
+ if event_uuid in seen_uuids:
+ raise CaptureInternalError(f"{fn} ({event_source}): duplicate event_uuid {event_uuid!r} in batch")
+ seen_uuids.add(event_uuid)
+
+
def prepare_capture_internal_batch(
events: list[dict[str, Any]],
*,
@@ -398,10 +431,8 @@ def prepare_capture_internal_batch(
Returns ``(payload, ordered_uuids)`` so callers can correlate the
results map.
- ``ai_lane`` selects which lane the batch is bound for and, with it, which
- event names are admissible. Capture's v1 AI endpoint refuses analytics
- traffic with a per-event ``non_ai_event`` drop. Catching it here turns that
- into an immediate, actionable error at the call site instead.
+ ``ai_lane`` only names the entry point in error messages; the envelope is the
+ same on both lanes.
"""
_validate_batch_inputs(events, token=token, event_source=event_source, ai_lane=ai_lane)
@@ -489,6 +520,7 @@ def _submit_batch_chunk(
url = f"{CAPTURE_AI_INTERNAL_URL}{CAPTURE_V1_AI_INTERNAL_ENDPOINT}"
else:
url = f"{CAPTURE_INTERNAL_URL}{CAPTURE_V1_INTERNAL_ENDPOINT}"
+ lane = _lane_label(ai_lane)
CAPTURE_V1_BATCH_SUBMITTED.labels(event_source=event_source).inc()
CAPTURE_V1_EVENT_SUBMITTED.labels(event_source=event_source).inc(len(uuids))
@@ -506,6 +538,10 @@ def _submit_batch_chunk(
for uid in uuid_to_event:
aggregated.setdefault(uid, {"result": "unaccounted"})
result = CaptureInternalResult(status_code=status_code, results=aggregated, error=error)
+ if error is not None:
+ result.request_failures.append(
+ RequestFailure(lane=lane, status_code=status_code, error=error, event_count=len(pending_batch))
+ )
for uid, entry in aggregated.items():
status = entry.get("result", "ok")
if status == "ok":
@@ -542,14 +578,15 @@ def _submit_batch_chunk(
"batch": pending_batch,
}
- CAPTURE_V1_REQUEST_SUBMITTED.labels(event_source=event_source).inc()
+ CAPTURE_V1_REQUEST_SUBMITTED.labels(event_source=event_source, lane=lane).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()
+ CAPTURE_V1_REQUEST_FAILED.labels(event_source=event_source, status_code="transport", lane=lane).inc()
logger.warning(
"capture_internal_transport_error",
event_source=event_source,
+ lane=lane,
request_id=headers.get("PostHog-Request-Id", ""),
batch_size=len(pending_batch),
error=str(exc),
@@ -560,6 +597,7 @@ def _submit_batch_chunk(
CAPTURE_V1_REQUEST_FAILED.labels(
event_source=event_source,
status_code=str(resp.status_code),
+ lane=lane,
).inc()
try:
error_body = resp.json()
@@ -571,6 +609,7 @@ def _submit_batch_chunk(
logger.warning(
"capture_internal_request_failed",
event_source=event_source,
+ lane=lane,
request_id=headers.get("PostHog-Request-Id", ""),
status_code=resp.status_code,
batch_size=len(pending_batch),
@@ -587,14 +626,20 @@ def _submit_batch_chunk(
{"error": "invalid_json", "error_description": "could not parse 200 body"},
)
- results_map: dict[str, Any] = body.get("results", {})
+ results_map = body.get("results", {}) if isinstance(body, dict) else None
+ if not isinstance(results_map, dict):
+ # Raising here would lose this chunk's uuids; _finalize marks them unaccounted.
+ return _finalize(
+ resp.status_code,
+ {"error": "invalid_response", "error_description": "200 body is not a results object"},
+ )
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:
+ if not isinstance(entry, dict):
continue
clamped = entry.get("result", "ok")
if clamped not in _KNOWN_RESULT_STATUSES:
@@ -624,42 +669,61 @@ def _submit_batch_chunk(
def _merge_results(chunk_results: list[CaptureInternalResult]) -> CaptureInternalResult:
- """Merge results from multiple chunk submissions into a single result."""
+ """Merge the results of several requests (chunks, lanes) into one.
+
+ ``error`` comes from the first failed request, rewritten to ``partial_request_failure``
+ when another request was acked so a caller does not resend the acked events.
+ """
merged = CaptureInternalResult(status_code=200)
+ any_acked_request = False
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
+ if cr.error is None:
+ any_acked_request = True
+ merged.request_failures.extend(cr.request_failures)
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)
+ if merged.error is not None and any_acked_request:
+ first = merged.error
+ merged.error = {
+ "error": "partial_request_failure",
+ "error_description": (
+ f"{len(merged.request_failures)} of {len(chunk_results)} requests failed; "
+ f"first: {first.get('error', 'unknown')}: {first.get('error_description', '')}"
+ ),
+ }
return merged
-def _capture_batch_impl(
+def _submit_chunks(
*,
- events: list[dict[str, Any]],
+ lanes: list[tuple[list[dict[str, Any]], bool]],
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.
+ """Submit every lane's chunks over one shared worker pool.
- 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.
+ Lanes go to different deployments, so a mixed batch runs them concurrently; sharing
+ the pool keeps it within the connection budget of a single-lane batch.
"""
- _validate_batch_inputs(events, token=token, event_source=event_source)
-
chunk_size = max(CAPTURE_INTERNAL_BATCH_CHUNK_SIZE, 1)
+ chunks: list[tuple[list[dict[str, Any]], bool]] = [
+ (lane_events[i : i + chunk_size], lane_is_ai)
+ for lane_events, lane_is_ai in lanes
+ for i in range(0, len(lane_events), chunk_size)
+ ]
- def _submit_chunk(chunk_events: list[dict[str, Any]]) -> CaptureInternalResult:
+ def _submit_chunk(chunk_events: list[dict[str, Any]], ai_lane: bool) -> CaptureInternalResult:
return _submit_batch_chunk(
events=chunk_events,
token=token,
@@ -671,51 +735,109 @@ def _capture_batch_impl(
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)
+ # Hot path: one lane, one chunk, so skip the pool.
+ if len(chunks) == 1:
+ return _submit_chunk(*chunks[0])
- # 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),
+ total_events=sum(len(lane_events) for lane_events, _ in lanes),
chunks=len(chunks),
+ events_per_lane={_lane_label(lane_is_ai): len(lane_events) for lane_events, lane_is_ai in lanes},
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)}
+ futures = {
+ executor.submit(_submit_chunk, chunk, ai_lane): (i, ai_lane) for i, (chunk, ai_lane) in enumerate(chunks)
+ }
for future in as_completed(futures):
- chunk_idx = futures[future]
+ chunk_idx, ai_lane = futures[future]
try:
chunk_results.append(future.result())
except Exception as exc:
logger.exception(
"capture_batch_internal_chunk_error",
event_source=event_source,
+ lane=_lane_label(ai_lane),
chunk=chunk_idx,
error=str(exc),
)
+ error = {"error": "chunk_exception", "error_description": str(exc)}
chunk_results.append(
CaptureInternalResult(
status_code=0,
- error={"error": "chunk_exception", "error_description": str(exc)},
+ error=error,
+ request_failures=[
+ RequestFailure(
+ lane=_lane_label(ai_lane),
+ status_code=0,
+ error=error,
+ event_count=len(chunks[chunk_idx][0]),
+ )
+ ],
)
)
return _merge_results(chunk_results)
+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 wire lane follows the event name, not ``ai_lane``: capture-ai drops a non-AI
+ event as `misrouted_event`, and capture-analytics would give an `$ai_*` event person
+ processing. Reroutes are counted so a call site on the wrong entry point is visible.
+ """
+ _validate_batch_inputs(events, token=token, event_source=event_source, ai_lane=ai_lane)
+
+ # Reject the whole batch before either lane publishes a chunk.
+ _validate_batch_events(events, event_source=event_source, ai_lane=ai_lane)
+
+ ai_events = [ev for ev in events if ev["event"].startswith(AI_EVENT_NAME_PREFIX)]
+ analytics_events = [ev for ev in events if not ev["event"].startswith(AI_EVENT_NAME_PREFIX)]
+
+ rerouted = analytics_events if ai_lane else ai_events
+ if rerouted:
+ from_lane = _lane_label(ai_lane)
+ CAPTURE_V1_EVENTS_REROUTED.labels(event_source=event_source, from_lane=from_lane).inc(len(rerouted))
+ logger.info(
+ "capture_internal_rerouted",
+ event_source=event_source,
+ entry_point=_lane_fn_name(ai_lane),
+ from_lane=from_lane,
+ rerouted_events=len(rerouted),
+ total_events=len(events),
+ )
+
+ return _submit_chunks(
+ lanes=[
+ (lane_events, lane_is_ai)
+ for lane_events, lane_is_ai in ((analytics_events, False), (ai_events, True))
+ if lane_events
+ ],
+ token=token,
+ event_source=event_source,
+ historical_migration=historical_migration,
+ process_person_profile=process_person_profile,
+ max_attempts=max_attempts,
+ timeout=timeout,
+ )
+
+
def capture_batch_internal(
*,
events: list[dict[str, Any]],
@@ -748,14 +870,23 @@ def capture_batch_internal(
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.
+ Each chunk gets its own retry budget (``max_attempts``) and its own ``timeout``.
+ If one chunk fails entirely (transport error), its events appear in
+ ``unaccounted``; other chunks' results are preserved and ``error["error"]`` reads
+ ``partial_request_failure``. Retry only ``unaccounted`` and ``retried`` uuids,
+ never the whole batch, or the acked events are ingested twice.
+
+ A batch that mixes `$ai_`-prefixed and other names is one request per lane;
+ both lanes' chunks share the same worker pool and run concurrently.
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.
+ Events with an `$ai_`-prefixed name are sent to the AI lane (see capture_ai_internal)
+ and counted as rerouted; the rest of the batch goes to the analytics lane as usual.
+ A uuid that appears twice in one batch is rejected before anything is sent.
+
event.options reference (typed options replacing legacy $-prefixed properties):
┌─────────────────────────┬────────────────────────────┬──────────────┐
│ options key │ replaces legacy property │ default │
@@ -1018,13 +1149,10 @@ def capture_ai_internal(
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.
+ A non-`$ai_` name passed here goes to the analytics lane, and an `$ai_` name
+ passed to capture_internal goes to the AI lane; each reroute is counted
+ (``capture_v1_internal_events_rerouted``). Prefer the matching entry point: it
+ keeps ``historical_migration`` and ``session_id`` / ``window_id`` off AI events.
``historical_migration`` is not offered: AI backfills do not run through this path.
@@ -1036,8 +1164,7 @@ def capture_ai_internal(
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.
+ CaptureInternalError: on client-side validation failures or HTTP/transport errors.
"""
return _capture_single_impl(
token=token,
@@ -1070,8 +1197,8 @@ def capture_batch_ai_internal(
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.
+ capture_batch_internal's docstring. An event without an `$ai_` prefixed name is
+ sent to the analytics lane instead and counted as rerouted; see capture_ai_internal.
``historical_migration`` is not offered: AI backfills do not run through this path.
"""
diff --git a/posthog/api/test/test_capture_internal.py b/posthog/api/test/test_capture_internal.py
index 4e8217ff7176..5b7a8a7bb1d3 100644
--- a/posthog/api/test/test_capture_internal.py
+++ b/posthog/api/test/test_capture_internal.py
@@ -13,10 +13,13 @@ from requests.adapters import HTTPAdapter
from requests.exceptions import ConnectionError as RequestsConnectionError
from posthog.api.capture import (
+ CAPTURE_V1_EVENTS_REROUTED,
CAPTURE_V1_OPTION_CONFLICT,
+ CAPTURE_V1_REQUEST_FAILED,
CAPTURE_V1_REQUEST_SUBMITTED,
CaptureInternalError,
CaptureInternalResult,
+ RequestFailure,
_build_v1_headers,
_merge_results,
_normalize_options_and_properties,
@@ -348,8 +351,9 @@ class TestPrepareCaptureInternalBatch(SimpleTestCase):
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": {}}]
+ @parameterized.expand([("missing", {}), ("empty", {"event": ""}), ("not_a_string", {"event": 42})])
+ def test_missing_or_non_string_event_name_raises(self, _name: str, event_field: dict[str, Any]) -> None:
+ events = [{"distinct_id": "u1", "properties": {}, **event_field}]
with self.assertRaises(CaptureInternalError) as ctx:
prepare_capture_internal_batch(events, token="tok", event_source="src")
assert "event name" in str(ctx.exception).lower()
@@ -753,6 +757,40 @@ class TestCaptureBatchInternal(SimpleTestCase):
assert result.error["error"] == "invalid_json"
assert not result.succeeded()
+ @parameterized.expand([("array_body", ["ok"]), ("results_not_object", {"results": ["ok"]})])
+ @patch("posthog.api.capture.internal_requests_session")
+ def test_wrong_shaped_200_body_leaves_every_uuid_unaccounted(
+ self, _name: str, body: Any, mock_session_fn: MagicMock
+ ) -> None:
+ uid = str(uuid4())
+ InstallV1Spy(mock_session_fn, [MockResponse(status_code=200, body=body)])
+
+ result = capture_batch_internal(events=[_make_event(event_uuid=uid)], token="tok", event_source="badshape")
+
+ assert result.error is not None
+ assert result.error["error"] == "invalid_response"
+ assert result.unaccounted == [uid]
+ assert result.request_failures[0].event_count == 1
+
+ @patch("posthog.api.capture.time.sleep")
+ @patch("posthog.api.capture.internal_requests_session")
+ def test_failure_after_a_partial_ack_counts_only_the_resubmitted_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")]
+ resp1 = MockResponse(body={"results": {u_ok: {"result": "ok"}, u_retry: {"result": "retry"}}})
+ resp2 = MockResponse(status_code=503, body={"error": "down"})
+ InstallV1Spy(mock_session_fn, [resp1, resp2])
+
+ result = capture_batch_internal(events=events, token="tok", event_source="partial_then_down")
+
+ assert result.ok == [u_ok]
+ assert result.unaccounted == [u_retry]
+ assert result.request_failures == [
+ RequestFailure(lane="analytics", status_code=503, error={"error": "down"}, event_count=1)
+ ]
+
@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:
@@ -906,13 +944,32 @@ class TestCaptureBatchInternal(SimpleTestCase):
resp2 = MockResponse(body=_ok_results(u_retry))
InstallV1Spy(mock_session_fn, [resp1, resp2])
- before = CAPTURE_V1_REQUEST_SUBMITTED.labels(event_source="reqmetric")._value.get()
+ before = CAPTURE_V1_REQUEST_SUBMITTED.labels(event_source="reqmetric", lane="analytics")._value.get()
capture_batch_internal(events=events, token="tok", event_source="reqmetric")
- after = CAPTURE_V1_REQUEST_SUBMITTED.labels(event_source="reqmetric")._value.get()
+ after = CAPTURE_V1_REQUEST_SUBMITTED.labels(event_source="reqmetric", lane="analytics")._value.get()
# Two HTTP POSTs: initial + one retry round.
assert after == before + 2
+ @parameterized.expand(
+ [("analytics", capture_batch_internal, "$pageview"), ("ai", capture_batch_ai_internal, "$ai_span")]
+ )
+ @patch("posthog.api.capture.internal_requests_session")
+ def test_request_metrics_carry_the_lane(
+ self, lane: str, entry_point: Any, event_name: str, mock_session_fn: MagicMock
+ ) -> None:
+ InstallV1Spy(mock_session_fn, [MockResponse(status_code=503, body={"error": "down"})])
+ submitted = CAPTURE_V1_REQUEST_SUBMITTED.labels(event_source="lanemetric", lane=lane)
+ failed = CAPTURE_V1_REQUEST_FAILED.labels(event_source="lanemetric", status_code="503", lane=lane)
+ before = (submitted._value.get(), failed._value.get())
+
+ result = entry_point(events=[_make_event(event=event_name)], token="tok", event_source="lanemetric")
+
+ assert (submitted._value.get(), failed._value.get()) == (before[0] + 1, before[1] + 1)
+ assert result.request_failures == [
+ RequestFailure(lane=lane, status_code=503, error={"error": "down"}, event_count=1)
+ ]
+
class TestParseRetryAfter(SimpleTestCase):
@parameterized.expand(
@@ -1008,8 +1065,26 @@ class TestCaptureInternalResult(SimpleTestCase):
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):
+ with self.assertRaises(CaptureInternalError) as ctx:
+ r.raise_for_status()
+ assert "whole-request failure" in str(ctx.exception)
+
+ def test_raise_for_status_names_a_partial_request_failure(self) -> None:
+ # A caller that reads "whole-request failure" resends everything and
+ # double-ingests the acked half; the message must say some events landed.
+ r = CaptureInternalResult(
+ status_code=0,
+ error={"error": "partial_request_failure", "error_description": "1 of 2 requests failed"},
+ ok=["a"],
+ unaccounted=["b"],
+ request_failures=[
+ RequestFailure(lane="ai", status_code=0, error={"error": "transport_error"}, event_count=1)
+ ],
+ )
+ with self.assertRaises(CaptureInternalError) as ctx:
r.raise_for_status()
+ assert "partial-request failure (ai 0)" in str(ctx.exception)
+ assert "1 events acked, 1 unaccounted" in str(ctx.exception)
@parameterized.expand(
[
@@ -1206,34 +1281,41 @@ class TestBatchChunking(SimpleTestCase):
@parameterized.expand(
[
- ("analytics_lane", "$ai_generation", False),
- ("ai_lane", "$pageview", True),
+ ("analytics_entry", "$pageview", "$ai_generation", False, EXPECTED_URL, EXPECTED_AI_URL),
+ ("ai_entry", "$ai_generation", "$pageview", True, EXPECTED_AI_URL, EXPECTED_URL),
]
)
@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(
+ def test_odd_event_in_a_large_batch_is_rerouted_and_the_rest_still_chunk_once(
self,
_name: str,
- misrouted_event_name: str,
+ majority_name: str,
+ odd_name: str,
ai_lane: bool,
+ majority_url: str,
+ odd_url: str,
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.
+ # 200 events on the entry point's lane fit one chunk; the 201st has a
+ # name from the other lane and must travel alone to the other URL
+ # rather than push the majority over the chunk boundary.
events = _make_batch(201)
- if ai_lane:
- for ev in events[:200]:
- ev["event"] = "$ai_generation"
- events[200]["event"] = misrouted_event_name
+ for ev in events[:200]:
+ ev["event"] = majority_name
+ events[200]["event"] = odd_name
+ uuids = [e["event_uuid"] for e in events]
entry_point = capture_batch_ai_internal if ai_lane else capture_batch_internal
- spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results())])
+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(*uuids))])
- with self.assertRaises(CaptureInternalError):
- entry_point(events=events, token="tok", event_source="mixed_lanes")
+ result = entry_point(events=events, token="tok", event_source="mixed_lanes")
- assert spy.calls == [], "a batch that fails validation must not publish any chunk"
+ assert result.succeeded()
+ by_url = {call["url"]: [e["uuid"] for e in call["json"]["batch"]] for call in spy.calls}
+ assert set(by_url) == {majority_url, odd_url}
+ assert by_url[majority_url] == uuids[:200]
+ assert by_url[odd_url] == uuids[200:]
@patch("posthog.api.capture.CAPTURE_INTERNAL_BATCH_CHUNK_SIZE", 200)
@patch("posthog.api.capture.CAPTURE_INTERNAL_MAX_WORKERS", 8)
@@ -1264,16 +1346,36 @@ class TestMergeResults(SimpleTestCase):
assert set(merged.ok) == {"a", "b"}
assert merged.error is None
- def test_merge_with_one_error(self) -> None:
+ def test_merge_with_one_error_reports_a_partial_request_failure(self) -> None:
+ failure = RequestFailure(lane="analytics", status_code=0, error={"error": "transport_error"}, event_count=1)
r1 = CaptureInternalResult(status_code=200, results={"a": {"result": "ok"}}, ok=["a"])
- r2 = CaptureInternalResult(status_code=0, error={"error": "transport_error", "error_description": "timeout"})
+ r2 = CaptureInternalResult(
+ status_code=0,
+ error={"error": "transport_error", "error_description": "timeout"},
+ unaccounted=["b"],
+ request_failures=[failure],
+ )
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
+ assert merged.ok == ["a"]
+ assert merged.unaccounted == ["b"]
+ assert merged.error == {
+ "error": "partial_request_failure",
+ "error_description": "1 of 2 requests failed; first: transport_error: timeout",
+ }
+ assert merged.request_failures == [failure]
+
+ def test_merge_where_every_request_failed_keeps_the_first_error(self) -> None:
+ r1 = CaptureInternalResult(status_code=503, error={"error": "service_unavailable", "error_description": "a"})
+ r2 = CaptureInternalResult(status_code=0, error={"error": "transport_error", "error_description": "b"})
+
+ merged = _merge_results([r1, r2])
+
+ assert merged.error == {"error": "service_unavailable", "error_description": "a"}
+ assert merged.status_code == 503
def test_merge_mixed_buckets(self) -> None:
r1 = CaptureInternalResult(
@@ -1298,12 +1400,12 @@ class TestMergeResults(SimpleTestCase):
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.
+class TestAiLaneRouting(SimpleTestCase):
+ """The wire lane follows the `$ai_` prefix, whichever entry point the caller used.
- 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.
+ capture-ai drops a non-AI event per event as ``misrouted_event`` and the analytics
+ deployment would give an `$ai_*` event person processing, so a name on the wrong
+ entry point is rerouted, counted, and never lost.
"""
@parameterized.expand(
@@ -1311,46 +1413,214 @@ class TestAiLaneGate(SimpleTestCase):
("$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",),
+ # Prefixed but not a name capture may accept. Django routes on the
+ # prefix alone; capture is the authority on which names it admits.
+ ("$ai_custom_metric",),
+ ("$ai_",),
]
)
- 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)
+ @patch("posthog.api.capture.internal_requests_session")
+ def test_ai_event_names_on_the_analytics_entry_point_go_to_the_ai_lane(
+ self, event_name: str, mock_session_fn: MagicMock
+ ) -> None:
+ uid = str(uuid4())
+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])
+ before = CAPTURE_V1_EVENTS_REROUTED.labels(event_source="src", from_lane="analytics")._value.get()
- @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)
+ result = capture_batch_internal(
+ events=[_make_event(event=event_name, event_uuid=uid)], token="tok", event_source="src"
+ )
- 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 result.succeeded()
+ assert [c["url"] for c in spy.calls] == [EXPECTED_AI_URL]
+ after = CAPTURE_V1_EVENTS_REROUTED.labels(event_source="src", from_lane="analytics")._value.get()
+ assert after - before == 1
+
+ @parameterized.expand([("$pageview",), ("custom_event",), ("$identify",), ("ai_generation",), ("$AI_generation",)])
+ @patch("posthog.api.capture.internal_requests_session")
+ def test_non_ai_event_names_on_the_ai_entry_point_go_to_the_analytics_lane(
+ self, event_name: str, mock_session_fn: MagicMock
+ ) -> None:
+ uid = str(uuid4())
+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])
+ before = CAPTURE_V1_EVENTS_REROUTED.labels(event_source="src", from_lane="ai")._value.get()
+
+ result = capture_batch_ai_internal(
+ events=[_make_event(event=event_name, event_uuid=uid)], token="tok", event_source="src"
)
- 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 result.succeeded()
+ assert [c["url"] for c in spy.calls] == [EXPECTED_URL]
+ after = CAPTURE_V1_EVENTS_REROUTED.labels(event_source="src", from_lane="ai")._value.get()
+ assert after - before == 1
+
+ @parameterized.expand([("analytics_entry", False), ("ai_entry", True)])
+ @patch("posthog.api.capture.internal_requests_session")
+ def test_mixed_batch_is_split_by_name_and_results_merge_by_uuid(
+ self, _name: str, ai_lane: bool, mock_session_fn: MagicMock
+ ) -> None:
+ ai_uid, an_uid, ai_uid2 = str(uuid4()), str(uuid4()), str(uuid4())
+ events = [
+ _make_event(event="$ai_generation", event_uuid=ai_uid),
+ _make_event(event="$pageview", distinct_id="u2", event_uuid=an_uid),
+ _make_event(event="$ai_span", distinct_id="u3", event_uuid=ai_uid2),
+ ]
+ spy = InstallV1Spy(
+ mock_session_fn,
+ [
+ MockResponse(body=_ok_results(an_uid)),
+ MockResponse(body={"results": {ai_uid: {"result": "ok"}, ai_uid2: {"result": "drop"}}}),
+ ],
)
- assert len(uuids) == 1
- assert payload["batch"][0]["event"] == "$pageview"
+ entry_point = capture_batch_ai_internal if ai_lane else capture_batch_internal
- 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)
+ result = entry_point(events=events, token="tok", event_source="src")
+
+ by_url = {call["url"]: [e["uuid"] for e in call["json"]["batch"]] for call in spy.calls}
+ assert by_url == {EXPECTED_URL: [an_uid], EXPECTED_AI_URL: [ai_uid, ai_uid2]}
+ assert set(result.ok) == {an_uid, ai_uid}
+ assert result.dropped == [ai_uid2]
+ assert set(result.results) == {an_uid, ai_uid, ai_uid2}
+
+ @patch("posthog.api.capture.internal_requests_session")
+ def test_a_single_lane_batch_makes_one_request_and_counts_no_reroute(self, mock_session_fn: MagicMock) -> None:
+ uid1, uid2 = str(uuid4()), str(uuid4())
+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid1, uid2))])
+ before = CAPTURE_V1_EVENTS_REROUTED.labels(event_source="src", from_lane="analytics")._value.get()
+
+ capture_batch_internal(
+ events=[_make_event(event_uuid=uid1), _make_event(distinct_id="u2", event_uuid=uid2)],
+ token="tok",
+ event_source="src",
+ )
+
+ assert [c["url"] for c in spy.calls] == [EXPECTED_URL]
+ after = CAPTURE_V1_EVENTS_REROUTED.labels(event_source="src", from_lane="analytics")._value.get()
+ assert after == before
+
+ @patch("posthog.api.capture.internal_requests_session")
+ def test_historical_migration_travels_with_a_rerouted_ai_event(self, mock_session_fn: MagicMock) -> None:
+ # The flag rides the envelope unchanged; capture ignores it on the AI lane.
+ uid = str(uuid4())
+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])
+
+ capture_batch_internal(
+ events=[_make_event(event="$ai_generation", event_uuid=uid)],
+ token="tok",
+ event_source="src",
+ historical_migration=True,
+ )
+
+ assert spy.calls[0]["url"] == EXPECTED_AI_URL
+ assert spy.calls[0]["json"]["historical_migration"] is True
+
+ @parameterized.expand([("properties", ["invalid"]), ("options", "not-a-dict")])
+ @patch("posthog.api.capture.CAPTURE_INTERNAL_BATCH_CHUNK_SIZE", 1)
+ @patch("posthog.api.capture.internal_requests_session")
+ def test_non_dict_event_field_is_rejected_before_any_chunk_publishes(
+ self, key: str, bad_value: Any, mock_session_fn: MagicMock
+ ) -> None:
+ # Normalization runs per chunk inside a worker; a field it cannot read must
+ # fail the whole batch up front, not after an earlier chunk already landed.
+ good_uid = str(uuid4())
+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(good_uid))])
+ events = [
+ _make_event(event="$pageview", event_uuid=good_uid),
+ {**_make_event(event="$ai_generation", distinct_id="u2"), key: bad_value},
+ ]
+
+ with self.assertRaises(CaptureInternalError) as ctx:
+ capture_batch_internal(events=events, token="tok", event_source="src")
+
+ assert f"capture_internal (src, $ai_generation): {key} must be a dict" in str(ctx.exception)
+ assert spy.calls == []
+
+ @parameterized.expand(
+ [("same_lane", "$ai_generation", "$ai_span"), ("across_lanes", "$ai_generation", "$pageview")]
+ )
+ @patch("posthog.api.capture.internal_requests_session")
+ def test_duplicate_uuids_in_one_batch_are_rejected_before_any_request(
+ self, _name: str, first_name: str, second_name: str, mock_session_fn: MagicMock
+ ) -> None:
+ # Results are keyed by uuid, so a duplicate would let one event's outcome
+ # overwrite the other's; across lanes the loser would vanish without a trace.
+ uid = str(uuid4())
+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])
+ events = [
+ _make_event(event=first_name, event_uuid=uid),
+ _make_event(event=second_name, distinct_id="u2", uuid=uid),
+ ]
+
+ with self.assertRaises(CaptureInternalError) as ctx:
+ capture_batch_ai_internal(events=events, token="tok", event_source="src")
+
+ assert f"capture_ai_internal (src): duplicate event_uuid {uid!r}" in str(ctx.exception)
+ assert spy.calls == []
+
+ @patch("posthog.api.capture.internal_requests_session")
+ def test_both_lanes_of_a_mixed_batch_are_in_flight_at_the_same_time(self, mock_session_fn: MagicMock) -> None:
+ # A slow analytics deployment must not delay the AI request behind it.
+ ai_uid, an_uid = str(uuid4()), str(uuid4())
+ both_started = threading.Barrier(2, timeout=5)
+
+ def spy_post(url: str, **kwargs: Any) -> MockResponse:
+ both_started.wait()
+ return MockResponse(body=_ok_results(*[e["uuid"] for e in kwargs["json"]["batch"]]))
+
+ mock_session = MagicMock()
+ mock_session.post.side_effect = spy_post
+ mock_session.mount = MagicMock()
+ mock_session_fn.return_value.__enter__.return_value = mock_session
+ events = [
+ _make_event(event="$ai_generation", event_uuid=ai_uid),
+ _make_event(distinct_id="u2", event_uuid=an_uid),
+ ]
+
+ result = capture_batch_internal(events=events, token="tok", event_source="src")
+
+ assert result.succeeded(), "the barrier would have timed out if the lanes ran one after the other"
+ assert set(result.ok) == {ai_uid, an_uid}
+
+ @patch("posthog.api.capture.internal_requests_session")
+ def test_one_lane_failing_leaves_the_other_lanes_events_acked(self, mock_session_fn: MagicMock) -> None:
+ ai_uid, an_uid = str(uuid4()), str(uuid4())
+
+ def spy_post(url: str, **kwargs: Any) -> MockResponse:
+ if url == EXPECTED_AI_URL:
+ raise RequestsConnectionError("capture-ai unreachable")
+ return MockResponse(body=_ok_results(an_uid))
+
+ mock_session = MagicMock()
+ mock_session.post.side_effect = spy_post
+ mock_session.mount = MagicMock()
+ mock_session_fn.return_value.__enter__.return_value = mock_session
+ events = [
+ _make_event(event="$ai_generation", event_uuid=ai_uid),
+ _make_event(distinct_id="u2", event_uuid=an_uid),
+ ]
+
+ result = capture_batch_internal(events=events, token="tok", event_source="src")
+
+ assert result.ok == [an_uid]
+ assert result.unaccounted == [ai_uid]
+ assert result.error is not None and result.error["error"] == "partial_request_failure"
+ assert [(rf.lane, rf.status_code, rf.event_count) for rf in result.request_failures] == [("ai", 0, 1)]
+ with self.assertRaises(CaptureInternalError) as ctx:
+ result.raise_for_status()
+ assert "partial-request failure (ai 0)" in str(ctx.exception)
+
+ @patch("posthog.api.capture.internal_requests_session")
+ def test_a_rejected_event_stops_both_lanes_before_any_request(self, mock_session_fn: MagicMock) -> None:
+ # Validation runs over the whole batch before partitioning, so the AI
+ # half must not publish when the analytics half carries a bad event.
+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results())])
+ events = [_make_event(event="$ai_generation"), _make_event(event="$snapshot", distinct_id="u2")]
+
+ with self.assertRaises(CaptureInternalError) as ctx:
+ capture_batch_ai_internal(events=events, token="tok", event_source="src")
+
+ assert "capture_ai_internal" in str(ctx.exception), "the error names the entry point the caller used"
+ assert spy.calls == []
class TestCaptureAiInternal(SimpleTestCase):
@@ -1396,17 +1666,22 @@ class TestCaptureAiInternal(SimpleTestCase):
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={})])
+ def test_non_ai_name_on_the_ai_entry_point_posts_to_the_analytics_endpoint(
+ self, mock_session_fn: MagicMock
+ ) -> None:
+ uid = str(uuid4())
+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])
- with self.assertRaises(CaptureInternalError):
- capture_ai_internal(token="tok", event_name="$pageview", event_source="src", distinct_id="user-1")
+ result = capture_ai_internal(
+ token="tok", event_name="$pageview", event_source="src", distinct_id="user-1", event_uuid=uid
+ )
- assert spy.calls == [], "a lane mistake must cost no round trip"
+ assert result.succeeded()
+ assert [c["url"] for c in spy.calls] == [EXPECTED_URL]
@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
+ """Django routes on the prefix; capture applies its own predicate. 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"}}}
@@ -1414,7 +1689,7 @@ class TestCaptureAiInternal(SimpleTestCase):
result = capture_ai_internal(
token="tok",
- event_name="$ai_cache_usage",
+ event_name="$ai_custom_metric",
event_source="ai-src",
distinct_id="user-1",
event_uuid=uid,
@@ -1454,10 +1729,10 @@ class TestLaneErrorMessages(SimpleTestCase):
class TestLaneIsNotAPublicArgument(SimpleTestCase):
- """Callers pick a lane by choosing an entry point, never by passing a flag.
+ """Callers pick an entry point, never a lane 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.
+ The entry point names itself in error messages and decides which options the
+ call offers; a public lane flag would let a call site misreport both.
"""
@parameterized.expand(
diff --git a/posthog/temporal/ai_observability/team_capture.py b/posthog/temporal/ai_observability/team_capture.py
index 7932d9530da5..7d160dccc6eb 100644
--- a/posthog/temporal/ai_observability/team_capture.py
+++ b/posthog/temporal/ai_observability/team_capture.py
@@ -80,8 +80,8 @@ def capture_ai_internal_for_team(
"""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.
+ (`/i/v1/ai/events` on capture-ai). A non-AI event name would be rerouted to the
+ analytics lane and counted, not rejected.
"""
token = get_team_api_token(team_id)
try: