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(ingestion): admit and enrich every $ai_* event in the AI pipeline (#103253)

Eli Reisman7f9a07afdc6f
diff --git a/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx b/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx
index 0899167f1906..ec0ce8555dc0 100644
--- a/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx
+++ b/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx
@@ -65,6 +65,7 @@ export const WARNING_TYPE_TO_DESCRIPTION: Record<string, string> = {
invalid_ai_event: 'Discarded an AI event with an unsupported event name or no $ai_model',
invalid_ai_payload: 'Rejected a malformed AI or OpenTelemetry request',
no_ai_spans_ingested: 'Accepted an OpenTelemetry export with no AI spans, so nothing was ingested',
+ misrouted_event: 'Discarded a non-AI event sent to the LLM analytics capture endpoint',
// Emitted by the capture service for its session replay endpoint
missing_session_id: 'Discarded a session replay batch with no $session_id',
invalid_session_id: 'Discarded a session replay batch with an invalid $session_id',
@@ -92,6 +93,7 @@ export const WARNING_TYPE_TO_DOCS_ANCHOR: Record<string, string> = {
invalid_heatmap_data: 'invalid-heatmap-data',
high_volume_distinct_id: 'skipped-person-profile-processing-for-a-high-volume-distinct-id',
cookieless_team_disabled: 'discarded-cookieless-event-because-cookieless-tracking-is-disabled',
+ misrouted_event: 'discarded-ai-events',
}
export const WARNING_TYPE_RENDERER = {
diff --git a/nodejs/src/ingestion/common/ai-event-types.ts b/nodejs/src/ingestion/common/ai-event-types.ts
index 83728202b7a9..a1228c128079 100644
--- a/nodejs/src/ingestion/common/ai-event-types.ts
+++ b/nodejs/src/ingestion/common/ai-event-types.ts
@@ -1,10 +1,14 @@
-// AI event type names accepted by the ai lane.
-// The Python query-routing list in posthog/hogql_queries/ai/ai_table_resolver.py
-// intentionally lists only the core types: ai_events lacks full history for the
-// meta-events, so their queries must stay on the shared events table to avoid the
-// resolver misreading the missing rows as expired data.
+// Capture routes on this prefix too, so any `$ai_*` name is admitted here. The query-routing
+// list in posthog/hogql_queries/ai/ai_table_resolver.py stays exact: ai_events lacks history
+// for anything but the core types.
+export const AI_EVENT_NAME_PREFIX = '$ai_'
+
+export function isAiEventName(event: string): boolean {
+ return event.startsWith(AI_EVENT_NAME_PREFIX)
+}
+
+// Billing only (billable-events.ts); ingestion uses `isAiEventName`.
export const AI_EVENT_TYPES = new Set([
- // Core AI telemetry, enriched by process-ai-event.ts (costs, model params, tool calls).
'$ai_generation',
'$ai_embedding',
'$ai_evaluation',
@@ -12,9 +16,6 @@ export const AI_EVENT_TYPES = new Set([
'$ai_trace',
'$ai_metric',
'$ai_feedback',
- // Internal meta-events emitted about AI telemetry (taggers, summarization, eval
- // reports). Cost and model-param enrichment gates on the exact core names above,
- // so these only get trace-property normalization and the ai_events double-write.
'$ai_tag',
'$ai_generation_summary',
'$ai_trace_summary',
diff --git a/nodejs/src/ingestion/common/ingestion-warning-types.ts b/nodejs/src/ingestion/common/ingestion-warning-types.ts
index fa52a76d8f15..79ac3609ab57 100644
--- a/nodejs/src/ingestion/common/ingestion-warning-types.ts
+++ b/nodejs/src/ingestion/common/ingestion-warning-types.ts
@@ -76,6 +76,9 @@ export const INGESTION_WARNING_TYPES = {
// rather than a JSON batch.
invalid_ai_event: { category: 'event', severity: 'error', captureProduced: true },
invalid_ai_payload: { category: 'event', severity: 'error', captureProduced: true },
+ // Non-AI event sent to /i/v1/ai/events. capture-ai can only write the AI topic,
+ // so it drops that event and keeps the rest of the batch.
+ misrouted_event: { category: 'event', severity: 'error', captureProduced: true },
// Severity is 'warning', not 'error': the OTLP export succeeded and only
// non-AI spans were in it, so nothing the AI pipeline owns was dropped. The
// customer still needs to know their export produced no AI events.
diff --git a/nodejs/src/ingestion/common/steps/allow-events.test.ts b/nodejs/src/ingestion/common/steps/allow-events.test.ts
index 34013c1b7dcc..01f6acfec9fb 100644
--- a/nodejs/src/ingestion/common/steps/allow-events.test.ts
+++ b/nodejs/src/ingestion/common/steps/allow-events.test.ts
@@ -1,7 +1,7 @@
import { dlq, ok } from '~/ingestion/framework/results'
import { createTestEventHeaders } from '~/tests/helpers/event-headers'
-import { createAllowEventsStep } from './allow-events'
+import { createAllowEventPrefixStep, createAllowEventsStep } from './allow-events'
function makeInput(eventName: string | undefined) {
return {
@@ -48,4 +48,27 @@ describe('createAllowEventsStep', () => {
expect(result).toEqual(dlq('event_not_in_allowlist'))
})
+
+ describe('createAllowEventPrefixStep', () => {
+ const prefixStep = createAllowEventPrefixStep('$ai_')
+
+ it.each(['$ai_generation', '$ai_custom_metric', '$ai_'])('passes through %s', async (eventName) => {
+ const input = makeInput(eventName)
+
+ expect(await prefixStep(input)).toEqual(ok(input))
+ })
+
+ it.each(['$pageview', 'ai_generation', '$AI_generation', ' $ai_generation', '$ai'])(
+ 'DLQs %s with the prefix mismatch reason',
+ async (eventName) => {
+ expect(await prefixStep(makeInput(eventName))).toEqual(dlq('event_name_prefix_mismatch'))
+ }
+ )
+
+ it('passes through events with no event header (no name to match)', async () => {
+ const input = makeInput(undefined)
+
+ expect(await prefixStep(input)).toEqual(ok(input))
+ })
+ })
})
diff --git a/nodejs/src/ingestion/common/steps/allow-events.ts b/nodejs/src/ingestion/common/steps/allow-events.ts
index 094446af59b0..b1773792ad8f 100644
--- a/nodejs/src/ingestion/common/steps/allow-events.ts
+++ b/nodejs/src/ingestion/common/steps/allow-events.ts
@@ -22,3 +22,14 @@ export function createAllowEventsStep<T extends { headers: EventHeaders }>(
return Promise.resolve(dlq('event_not_in_allowlist'))
}
}
+
+/** Prefix form of {@link createAllowEventsStep}: same header-only contract, same pass-through when the header is absent. */
+export function createAllowEventPrefixStep<T extends { headers: EventHeaders }>(prefix: string): ProcessingStep<T, T> {
+ return function allowEventPrefixStep(input) {
+ const name = input.headers.event
+ if (name === undefined || name.startsWith(prefix)) {
+ return Promise.resolve(ok(input))
+ }
+ return Promise.resolve(dlq('event_name_prefix_mismatch'))
+ }
+}
diff --git a/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.ts b/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.ts
index 154439ea984b..d806904d3260 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.ts
@@ -7,6 +7,7 @@ import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'
import { MessageSizeTooLarge } from '~/common/utils/db/error'
import { safeClickhouseString } from '~/common/utils/db/utils'
import { castTimestampOrNow, castTimestampToClickhouseFormat } from '~/common/utils/utils'
+import { isAiEventName } from '~/ingestion/common/ai-event-types'
import { emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'
import { eventProcessedAndIngestedCounter } from '~/ingestion/common/metrics'
import { EventUsageRecord } from '~/ingestion/common/steps/usage-records-steps'
@@ -152,5 +153,5 @@ export function serializeEvent(event: ProcessedEvent): RawKafkaEvent {
}
export function productTrackHeader(event: ProcessedEvent): string {
- return event.event.startsWith('$ai_') ? 'llma' : 'general'
+ return isAiEventName(event.event) ? 'llma' : 'general'
}
diff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts
index 5a38f0af8278..9f583615849b 100644
--- a/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts
@@ -217,7 +217,30 @@ describe('AiIngestionPipeline', () => {
expect(parseJSON(emitted.properties).$ai_input_tokens).toBeNull()
})
- it.each(['$pageview', '$autocapture', '$identify', '$exception', 'custom_event'])(
+ it('admits an unlisted $ai_* event and splits, strips and bills it like a listed one', async () => {
+ await runPipeline([
+ createMessage('$ai_custom_step', {
+ $ai_input: 'large input',
+ $ai_model: 'gpt-4',
+ $set: { plan: 'pro' },
+ }),
+ ])
+
+ expect(producedForTopic(DLQ_TOPIC)).toHaveLength(0)
+ const [eventsCopy] = producedForTopic(EVENTS_TOPIC)
+ const [aiCopy] = producedForTopic(AI_EVENTS_TOPIC)
+ expect(eventsCopy.event).toBe('$ai_custom_step')
+ expect(aiCopy.event).toBe('$ai_custom_step')
+ // Large AI properties live only on ai_events; person updates never leave this pipeline.
+ expect(parseJSON(eventsCopy.properties).$ai_input).toBeUndefined()
+ expect(parseJSON(aiCopy.properties).$ai_input).toBe('large input')
+ expect(parseJSON(eventsCopy.properties).$set).toBeUndefined()
+ expect(parseJSON(aiCopy.properties).$set).toBeUndefined()
+ expect(ingestedUsage).toHaveLength(1)
+ expect(ingestedUsage[0].usageKey).toBe('ai_events')
+ })
+
+ it.each(['$pageview', '$autocapture', '$identify', '$exception', 'custom_event', 'ai_generation'])(
'DLQs non-AI %s events instead of processing them',
async (eventName) => {
await runPipeline([createMessage(eventName)])
diff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.ts
index 5b44f30a4778..87fd0d14a87d 100644
--- a/nodejs/src/ingestion/pipelines/ai/pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.ts
@@ -10,12 +10,12 @@ import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion
import { EventSchemaEnforcementManager } from '~/common/utils/event-schema-enforcement-manager'
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
import { TeamManager } from '~/common/utils/team-manager'
-import { AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'
+import { AI_EVENT_NAME_PREFIX } from '~/ingestion/common/ai-event-types'
import { newCommonIngestionPipeline } from '~/ingestion/common/common-ingestion-pipeline'
import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
import { EventFilterManager } from '~/ingestion/common/event-filters'
import { OverflowRedirectService } from '~/ingestion/common/overflow-redirect/overflow-redirect-service'
-import { createAllowEventsStep } from '~/ingestion/common/steps/allow-events'
+import { createAllowEventPrefixStep } from '~/ingestion/common/steps/allow-events'
import {
createApplyEventFiltersStep,
createEventFiltersBatchAppMetricsBeforeBatchStep,
@@ -157,7 +157,7 @@ export function createAiIngestionPipeline<
)
// Header-only steps: allow only AI events, apply token restrictions.
.parseHeaders()
- .pipe(createAllowEventsStep([...AI_EVENT_TYPES]))
+ .pipe(createAllowEventPrefixStep(AI_EVENT_NAME_PREFIX))
.pipe(
createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {
overflowMode,
diff --git a/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts b/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts
index f68d0cf38d93..45f1e31ebd24 100644
--- a/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts
+++ b/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts
@@ -2584,6 +2584,29 @@ describe('processAiEvent() trace normalization', () => {
expect(result.properties!.$ai_total_cost_usd).toBeUndefined()
})
+ it('normalizes trace properties on an unlisted $ai_* event without adding costs', () => {
+ const event: PluginEvent = {
+ event: '$ai_custom_step',
+ properties: {
+ $ai_trace_id: 123,
+ $ai_parent_id: 456,
+ $ai_model: 'gpt-4',
+ $ai_input_tokens: 10,
+ },
+ ip: '',
+ site_url: '',
+ team_id: 0,
+ now: '',
+ distinct_id: '',
+ uuid: '',
+ timestamp: '',
+ }
+ const result = processAiEvent(event)
+ expect(result.properties!.$ai_trace_id).toBe('123')
+ expect(result.properties!.$ai_parent_id).toBe('456')
+ expect(result.properties!.$ai_total_cost_usd).toBeUndefined()
+ })
+
it('does not normalize non-AI events', () => {
const event: PluginEvent = {
event: '$pageview',
diff --git a/nodejs/src/ingestion/pipelines/ai/process-ai-event.ts b/nodejs/src/ingestion/pipelines/ai/process-ai-event.ts
index a46cec21bb12..73553657e8c1 100644
--- a/nodejs/src/ingestion/pipelines/ai/process-ai-event.ts
+++ b/nodejs/src/ingestion/pipelines/ai/process-ai-event.ts
@@ -8,7 +8,7 @@
* - Model parameter extraction (for generation/embedding/evaluation events)
*/
import { logger } from '~/common/utils/logger'
-import { AI_EVENT_TYPES, COSTED_AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'
+import { COSTED_AI_EVENT_TYPES, isAiEventName } from '~/ingestion/common/ai-event-types'
import { PluginEvent } from '~/plugin-scaffold'
import { convertRawEvent } from './convert-raw-event'
@@ -42,7 +42,7 @@ export const processAiEvent = (event: PluginEvent): PluginEvent | EventWithPrope
}
// Normalize trace properties for all AI events.
- const normalized: EventWithProperties = AI_EVENT_TYPES.has(event.event) ? normalizeTraceProperties(event) : event
+ const normalized: EventWithProperties = isAiEventName(event.event) ? normalizeTraceProperties(event) : event
// Normalize error messages for all AI events with errors.
const withErrorNormalization = processAiErrorNormalization(normalized)
diff --git a/nodejs/src/ingestion/pipelines/ai/steps/process-ai-event-step.test.ts b/nodejs/src/ingestion/pipelines/ai/steps/process-ai-event-step.test.ts
index f1b83a30bad8..3678bce9f8d4 100644
--- a/nodejs/src/ingestion/pipelines/ai/steps/process-ai-event-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/ai/steps/process-ai-event-step.test.ts
@@ -56,6 +56,8 @@ describe('processAiEventStep', () => {
'$ai_generation_summary',
'$ai_trace_summary',
'$ai_evaluation_report',
+ // Any `$ai_*` name is an AI event, including ones this code has never seen.
+ '$ai_custom_metric',
])('calls processAiEvent for %s event', async (eventName) => {
const event = createTestEvent({ event: eventName, properties: { $ai_model: 'gpt-4' } })
const step = createProcessAiEventStep()
@@ -70,16 +72,19 @@ describe('processAiEventStep', () => {
}
})
- it.each(['$pageview', '$autocapture', 'custom_event', '$$heatmap'])('sends %s event to DLQ', async (eventName) => {
- const event = createTestEvent({ event: eventName })
- const step = createProcessAiEventStep()
- const input = { normalizedEvent: event }
+ it.each(['$pageview', '$autocapture', 'custom_event', '$$heatmap', 'ai_generation', '$AI_generation'])(
+ 'sends %s event to DLQ',
+ async (eventName) => {
+ const event = createTestEvent({ event: eventName })
+ const step = createProcessAiEventStep()
+ const input = { normalizedEvent: event }
- const result = await step(input)
+ const result = await step(input)
- expect(result.type).toBe(PipelineResultType.DLQ)
- expect(mockedProcessAiEvent).not.toHaveBeenCalled()
- })
+ expect(result.type).toBe(PipelineResultType.DLQ)
+ expect(mockedProcessAiEvent).not.toHaveBeenCalled()
+ }
+ )
it('passes through unchanged on processAiEvent error', async () => {
const event = createTestEvent({ event: '$ai_generation' })
diff --git a/nodejs/src/ingestion/pipelines/ai/steps/process-ai-event-step.ts b/nodejs/src/ingestion/pipelines/ai/steps/process-ai-event-step.ts
index 28fa3a1df121..1b1276506535 100644
--- a/nodejs/src/ingestion/pipelines/ai/steps/process-ai-event-step.ts
+++ b/nodejs/src/ingestion/pipelines/ai/steps/process-ai-event-step.ts
@@ -1,6 +1,6 @@
import { logger } from '~/common/utils/logger'
import { captureException } from '~/common/utils/posthog'
-import { AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'
+import { isAiEventName } from '~/ingestion/common/ai-event-types'
import { dlq, ok } from '~/ingestion/framework/results'
import { ProcessingStep } from '~/ingestion/framework/steps'
import { processAiEvent } from '~/ingestion/pipelines/ai/process-ai-event'
@@ -12,7 +12,7 @@ type ProcessAiEventInput = {
export function createProcessAiEventStep<TInput extends ProcessAiEventInput>(): ProcessingStep<TInput, TInput> {
return function processAiEventStep(input) {
- if (!AI_EVENT_TYPES.has(input.normalizedEvent.event)) {
+ if (!isAiEventName(input.normalizedEvent.event)) {
return Promise.resolve(
dlq(
'non-AI event routed to AI subpipeline',
diff --git a/nodejs/src/ingestion/pipelines/ai/steps/split-ai-events-step.test.ts b/nodejs/src/ingestion/pipelines/ai/steps/split-ai-events-step.test.ts
index 8bc6c8d88375..1d6e66aaf177 100644
--- a/nodejs/src/ingestion/pipelines/ai/steps/split-ai-events-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/ai/steps/split-ai-events-step.test.ts
@@ -98,23 +98,48 @@ describe('split-ai-events-step', () => {
expect(eventsToEmit[1].output).toBe(AI_EVENTS_OUTPUT)
})
- it.each(['$ai_feedback', '$ai_evaluation', '$ai_generation', '$ai_span', '$ai_trace', '$ai_embedding'])(
- 'should send %s without large properties to both outputs',
- async (eventName) => {
- const event = createProcessedEvent({ $ai_model: 'gpt-4' }, { event: eventName })
+ it('should strip large properties from the events copy of an unlisted $ai_* event', async () => {
+ const event = createProcessedEvent(
+ { $ai_input: 'large input', $ai_model: 'gpt-4' },
+ { event: '$ai_custom_step' }
+ )
- const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
+ const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
+ expect(isOkResult(result)).toBe(true)
+ if (!isOkResult(result)) {
+ return
+ }
- const { eventsToEmit } = result.value
- expect(eventsToEmit).toHaveLength(2)
- expect(eventsToEmit[0].output).toBe(EVENTS_OUTPUT)
- expect(eventsToEmit[1].output).toBe(AI_EVENTS_OUTPUT)
+ const { eventsToEmit } = result.value
+ expect(eventsToEmit).toHaveLength(2)
+ expect(eventsToEmit[0].output).toBe(EVENTS_OUTPUT)
+ expect(eventsToEmit[0].event.properties).toEqual({ $ai_model: 'gpt-4' })
+ expect(eventsToEmit[1].output).toBe(AI_EVENTS_OUTPUT)
+ expect(eventsToEmit[1].event.properties).toEqual({ $ai_input: 'large input', $ai_model: 'gpt-4' })
+ })
+
+ it.each([
+ '$ai_feedback',
+ '$ai_evaluation',
+ '$ai_generation',
+ '$ai_span',
+ '$ai_trace',
+ '$ai_embedding',
+ '$ai_custom_step',
+ ])('should send %s without large properties to both outputs', async (eventName) => {
+ const event = createProcessedEvent({ $ai_model: 'gpt-4' }, { event: eventName })
+
+ const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
+ expect(isOkResult(result)).toBe(true)
+ if (!isOkResult(result)) {
+ return
}
- )
+
+ const { eventsToEmit } = result.value
+ expect(eventsToEmit).toHaveLength(2)
+ expect(eventsToEmit[0].output).toBe(EVENTS_OUTPUT)
+ expect(eventsToEmit[1].output).toBe(AI_EVENTS_OUTPUT)
+ })
it.each([
{ props: { $browser: 'Chrome' }, desc: 'without large AI properties' },
diff --git a/nodejs/src/ingestion/pipelines/ai/steps/split-ai-events-step.ts b/nodejs/src/ingestion/pipelines/ai/steps/split-ai-events-step.ts
index 976fbb5c7667..f3338e610f31 100644
--- a/nodejs/src/ingestion/pipelines/ai/steps/split-ai-events-step.ts
+++ b/nodejs/src/ingestion/pipelines/ai/steps/split-ai-events-step.ts
@@ -1,5 +1,5 @@
import { AI_EVENTS_OUTPUT, AiEventOutput, EventOutput } from '~/common/outputs'
-import { AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'
+import { isAiEventName } from '~/ingestion/common/ai-event-types'
import { EventToEmit } from '~/ingestion/common/steps/event-processing/emit-event-step'
import { ok } from '~/ingestion/framework/results'
import { ProcessingStep } from '~/ingestion/framework/steps'
@@ -27,7 +27,7 @@ function hasLargeAiProperties(properties: Record<string, unknown>): boolean {
function splitAiEvent(entry: EventToEmit<EventOutput>): EventToEmit<EventOutput | AiEventOutput>[] {
const properties = entry.event.properties ?? {}
- if (!AI_EVENT_TYPES.has(entry.event.event)) {
+ if (!isAiEventName(entry.event.event)) {
return [entry]
}
diff --git a/nodejs/src/ingestion/pipelines/ai/steps/validate-ai-event-tokens.test.ts b/nodejs/src/ingestion/pipelines/ai/steps/validate-ai-event-tokens.test.ts
index f52db61d3a7a..85d2e8d7927c 100644
--- a/nodejs/src/ingestion/pipelines/ai/steps/validate-ai-event-tokens.test.ts
+++ b/nodejs/src/ingestion/pipelines/ai/steps/validate-ai-event-tokens.test.ts
@@ -53,9 +53,17 @@ const TOKEN_PROPERTIES = [
'$ai_cache_creation_1h_input_tokens',
] as const
-const AI_EVENT_TYPES = ['$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback']
+const AI_EVENT_TYPES = [
+ '$ai_generation',
+ '$ai_embedding',
+ '$ai_span',
+ '$ai_trace',
+ '$ai_metric',
+ '$ai_feedback',
+ '$ai_custom_step',
+]
-const NON_AI_EVENT_TYPES = ['$pageview', '$identify', 'custom_event', '$exception']
+const NON_AI_EVENT_TYPES = ['$pageview', '$identify', 'custom_event', '$exception', 'ai_generation']
describe('createValidateAiEventTokensStep', () => {
const step = createValidateAiEventTokensStep()
diff --git a/nodejs/src/ingestion/pipelines/ai/steps/validate-ai-event-tokens.ts b/nodejs/src/ingestion/pipelines/ai/steps/validate-ai-event-tokens.ts
index eb2593136319..2a88597a7f12 100644
--- a/nodejs/src/ingestion/pipelines/ai/steps/validate-ai-event-tokens.ts
+++ b/nodejs/src/ingestion/pipelines/ai/steps/validate-ai-event-tokens.ts
@@ -1,4 +1,4 @@
-import { AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'
+import { isAiEventName } from '~/ingestion/common/ai-event-types'
import { PipelineWarning } from '~/ingestion/framework/pipeline.interface'
import { ok } from '~/ingestion/framework/results'
import { ProcessingStep } from '~/ingestion/framework/steps'
@@ -60,7 +60,7 @@ export function createValidateAiEventTokensStep<T extends { event: PipelineEvent
return async function validateAiEventTokensStep(input) {
const { event } = input
- if (!AI_EVENT_TYPES.has(event.event)) {
+ if (!isAiEventName(event.event)) {
return Promise.resolve(ok(input))
}
diff --git a/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md b/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md
index 634c62e7695e..ae31451d6a48 100644
--- a/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md
+++ b/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md
@@ -78,11 +78,12 @@ Those decisions come only from this skill's guidance and your own reasoning.
Emitted by capture for its two dedicated AI endpoints, `/i/v0/ai` (a single event per request, sent multipart) and `/i/v0/ai/otel` (OTLP traces). These reject at the edge, so the events never reach the pipeline and appear nowhere else. Read the `path` detail to tell the endpoints apart: it carries the request path, so `/i/v0/ai` or `/i/v0/ai/otel`.
-| Type | What happened | Fix |
-| ---------------------- | ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `invalid_ai_event` | Event rejected: the name isn't one of the six `$ai_*` types, or `$ai_model` is missing or not a string | Read [references/fixing-ai-endpoint-rejections.md](references/fixing-ai-endpoint-rejections.md) — usually ordinary analytics pointed at the AI endpoint |
-| `invalid_ai_payload` | Request rejected: malformed multipart or OTLP body, or too many spans in one export | Read [references/fixing-ai-endpoint-rejections.md](references/fixing-ai-endpoint-rejections.md) — `format`, `stage`, and `part` details name which check failed |
-| `no_ai_spans_ingested` | OTLP export accepted with a 200 but contained no AI spans, so nothing was ingested | Read [references/fixing-ai-endpoint-rejections.md](references/fixing-ai-endpoint-rejections.md) — instrumentation is emitting spans no AI provider convention matches |
+| Type | What happened | Fix |
+| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `invalid_ai_event` | Event rejected: the name isn't one of the six `$ai_*` types, or `$ai_model` is missing or not a string | Read [references/fixing-ai-endpoint-rejections.md](references/fixing-ai-endpoint-rejections.md) — usually ordinary analytics pointed at the AI endpoint |
+| `invalid_ai_payload` | Request rejected: malformed multipart or OTLP body, or too many spans in one export | Read [references/fixing-ai-endpoint-rejections.md](references/fixing-ai-endpoint-rejections.md) — `format`, `stage`, and `part` details name which check failed |
+| `no_ai_spans_ingested` | OTLP export accepted with a 200 but contained no AI spans, so nothing was ingested | Read [references/fixing-ai-endpoint-rejections.md](references/fixing-ai-endpoint-rejections.md) — instrumentation is emitting spans no AI provider convention matches |
+| `misrouted_event` | An event whose name does not start with `$ai_` reached the AI batch endpoint (`/i/v1/ai/events`); only that event was discarded, the rest of the batch landed | Read [references/fixing-ai-endpoint-rejections.md](references/fixing-ai-endpoint-rejections.md) — `eventName` names the offender; send it through the standard capture endpoint |
### Heatmaps (`event`)
diff --git a/products/ingestion/skills/resolving-ingestion-warnings/references/fixing-ai-endpoint-rejections.md b/products/ingestion/skills/resolving-ingestion-warnings/references/fixing-ai-endpoint-rejections.md
index 6ed7de3acd2c..99348b201c63 100644
--- a/products/ingestion/skills/resolving-ingestion-warnings/references/fixing-ai-endpoint-rejections.md
+++ b/products/ingestion/skills/resolving-ingestion-warnings/references/fixing-ai-endpoint-rejections.md
@@ -1,13 +1,14 @@
# Fixing AI endpoint rejections
-Covers `invalid_ai_event`, `invalid_ai_payload`, and `no_ai_spans_ingested`.
+Covers `invalid_ai_event`, `invalid_ai_payload`, `no_ai_spans_ingested`, and `misrouted_event`.
-These come from capture's two dedicated LLM analytics endpoints, not from the ingestion pipeline:
+These come from capture's dedicated LLM analytics endpoints, not from the ingestion pipeline:
- `/i/v0/ai` — one event per request, sent as multipart with an `event` part and an optional `event.properties` part. Warnings carry `path: ai_events`.
- `/i/v0/ai/otel` — OTLP trace export, protobuf or JSON. Warnings carry `path: ai_otel`.
+- `/i/v1/ai/events` — JSON batch, the same request shape as the standard v1 capture endpoint. Only `misrouted_event` comes from here.
-Both reject at the edge, so a rejected event reaches nothing downstream. It is not in `events`, not in any insight, and has no other trace beyond the warning. `count` is the number of events or spans that didn't land.
+All three reject at the edge, so a rejected event reaches nothing downstream. The v0 endpoints refuse the whole request; `/i/v1/ai/events` drops only the offending event and accepts the rest of the batch. It is not in `events`, not in any insight, and has no other trace beyond the warning. `count` is the number of events or spans that didn't land.
Check `lib` and `libVersion` first on every one of these. A rejection concentrated on one SDK version is an upgrade, not a payload problem.
@@ -57,3 +58,11 @@ Almost always one of:
To see what is actually arriving, pull the spans' attribute keys from your own tracing backend rather than from PostHog. Nothing reached PostHog to inspect.
A mixed batch that contains at least one AI span does **not** warn, so a team seeing this occasionally alongside successful ingestion is sending some batches with no AI activity in them. That is usually benign. Sustained firing with no AI events landing is the case worth acting on.
+
+## `misrouted_event`
+
+A batch sent to `/i/v1/ai/events` contained an event whose name does not start with `$ai_`. That deployment can only write to the LLM analytics topic, so it drops the offending event and accepts the rest of the batch. `eventName` and `eventUuid` identify the dropped event; the response body lists it under `details` as `misrouted_event`.
+
+This is always a routing mistake on the sending side: a proxy rule, a host override, or an SDK configured to send all events through its AI capture method. Send ordinary analytics events through the standard capture endpoint. Nothing about the event itself needs to change.
+
+The reverse case (an `$ai_*` event sent to the standard endpoint) does not warn. Capture routes AI-lane names to the LLM analytics pipeline.
diff --git a/rust/common/ingestion_warnings/src/registry.rs b/rust/common/ingestion_warnings/src/registry.rs
index 68171e699a20..887e044d0f5b 100644
--- a/rust/common/ingestion_warnings/src/registry.rs
+++ b/rust/common/ingestion_warnings/src/registry.rs
@@ -44,12 +44,13 @@ impl WarningType {
/// This list exists so the trust-allowlist invariant below can still be
/// airtight: `captureProduced` must equal "reachable by one of capture's two
/// emit routes", and without this the direct route would be invisible to it.
- pub const DIRECT_EMIT: [Self; 8] = [
+ pub const DIRECT_EMIT: [Self; 9] = [
Self::HighVolumeDistinctId,
Self::DistinctIdTruncated,
Self::InvalidAiEvent,
Self::InvalidAiPayload,
Self::NoAiSpansIngested,
+ Self::MisroutedEvent,
Self::MissingSessionId,
Self::InvalidSessionId,
Self::MissingSnapshotData,
diff --git a/rust/common/ingestion_warnings/warning_types.generated.json b/rust/common/ingestion_warnings/warning_types.generated.json
index 088e7416e310..f4492ab5cc7f 100644
--- a/rust/common/ingestion_warnings/warning_types.generated.json
+++ b/rust/common/ingestion_warnings/warning_types.generated.json
@@ -247,6 +247,12 @@
"severity": "warning",
"captureProduced": false
},
+ {
+ "type": "misrouted_event",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": true
+ },
{
"type": "missing_distinct_id",
"category": "event",