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): add dedicated AI ingestion pipeline (#64817)

Paweł Ledwoń840af12e8d0e
diff --git a/nodejs/src/common/hog-transformations/hog-transformer-component.ts b/nodejs/src/common/hog-transformations/hog-transformer-component.ts
new file mode 100644
index 000000000000..be2cf37ae240
--- /dev/null
+++ b/nodejs/src/common/hog-transformations/hog-transformer-component.ts
@@ -0,0 +1,17 @@
+import { HogTransformer } from './hog-transformer.interface'
+
+/**
+ * Scope owner for a hog transformer: starts it on `start()` and stops it on
+ * `stop()`, so its lifetime is tied to the owning scope. The concrete
+ * transformer is supplied by the caller via a factory (the implementation
+ * lives in cdp), so ingestion scopes own its lifecycle without importing cdp.
+ */
+export class HogTransformerComponent {
+ constructor(private readonly create: () => HogTransformer) {}
+
+ async start(): Promise<{ value: HogTransformer; stop: () => Promise<void> }> {
+ const hogTransformer = this.create()
+ await hogTransformer.start()
+ return { value: hogTransformer, stop: () => hogTransformer.stop() }
+ }
+}
diff --git a/nodejs/src/common/personhog/personhog-client-component.ts b/nodejs/src/common/personhog/personhog-client-component.ts
new file mode 100644
index 000000000000..f9d7fa517524
--- /dev/null
+++ b/nodejs/src/common/personhog/personhog-client-component.ts
@@ -0,0 +1,28 @@
+import { PersonHogClient } from './client'
+import { PersonHogConfig, createPersonHogClient } from './index'
+
+/**
+ * Scope owner for a PersonHog gRPC client: builds the client on `start()` and
+ * closes the connection on `stop()`, so its lifetime is tied to the owning
+ * scope. Throws if personhog isn't configured — read-only lanes (AI, error
+ * tracking) read person and group data through it.
+ */
+export class PersonHogClientComponent {
+ constructor(private readonly config: PersonHogConfig) {}
+
+ start(): Promise<{ value: PersonHogClient; stop: () => Promise<void> }> {
+ const client = createPersonHogClient(this.config)
+ if (!client) {
+ throw new Error(
+ 'PersonHog client is required but not configured — set PERSONHOG_ENABLED=true and PERSONHOG_ADDR'
+ )
+ }
+ return Promise.resolve({
+ value: client,
+ stop: () => {
+ client.close()
+ return Promise.resolve()
+ },
+ })
+ }
+}
diff --git a/nodejs/src/common/utils/event-ingestion-restrictions/manager.ts b/nodejs/src/common/utils/event-ingestion-restrictions/manager.ts
index ed67aabe61db..c7dd792b7094 100644
--- a/nodejs/src/common/utils/event-ingestion-restrictions/manager.ts
+++ b/nodejs/src/common/utils/event-ingestion-restrictions/manager.ts
@@ -7,7 +7,13 @@ import { logger } from '../logger'
import { REDIS_KEY_PREFIX, RedisRestrictionArraySchema, RedisRestrictionType, toRestrictionRule } from './redis-schema'
import { EventContext, RestrictionFilters, RestrictionMap, RestrictionRule, RestrictionType } from './rules'
-export type IngestionPipeline = 'analytics' | 'session_recordings' | 'errortracking' | 'clientwarnings' | 'heatmaps'
+export type IngestionPipeline =
+ | 'analytics'
+ | 'session_recordings'
+ | 'errortracking'
+ | 'clientwarnings'
+ | 'heatmaps'
+ | 'ai'
const EMPTY_RESTRICTIONS: ReadonlySet<RestrictionType> = new Set()
diff --git a/nodejs/src/common/utils/event-ingestion-restrictions/redis-schema.ts b/nodejs/src/common/utils/event-ingestion-restrictions/redis-schema.ts
index 59f893527495..2e8e91d3ebc6 100644
--- a/nodejs/src/common/utils/event-ingestion-restrictions/redis-schema.ts
+++ b/nodejs/src/common/utils/event-ingestion-restrictions/redis-schema.ts
@@ -14,7 +14,7 @@ export const REDIS_KEY_PREFIX = 'event_ingestion_restriction_dynamic_config'
// Base schema for common fields
const pipelinesSchema = z
- .array(z.enum(['analytics', 'session_recordings', 'errortracking', 'clientwarnings', 'heatmaps']))
+ .array(z.enum(['analytics', 'session_recordings', 'errortracking', 'clientwarnings', 'heatmaps', 'ai']))
.optional()
// Redis schema v0 (legacy) - single identifier per entry, no version field
diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/overflow-lane-ttl-refresh-step.test.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/overflow-lane-ttl-refresh-step.test.ts
index 60e77b3a81c7..0c2dbf64da76 100644
--- a/nodejs/src/ingestion/common/steps/event-preprocessing/overflow-lane-ttl-refresh-step.test.ts
+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/overflow-lane-ttl-refresh-step.test.ts
@@ -46,7 +46,7 @@ describe('createOverflowLaneTTLRefreshStep', () => {
await step(events)
- expect(service.handleEventBatch).toHaveBeenCalledWith('events', [
+ expect(service.handleEventBatch).toHaveBeenCalledWith([
{ key: { token: 'token1', distinctId: 'user1' }, eventCount: 2, firstTimestamp: baseTime.getTime() },
{ key: { token: 'token1', distinctId: 'user2' }, eventCount: 1, firstTimestamp: baseTime.getTime() },
])
diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/overflow-lane-ttl-refresh-step.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/overflow-lane-ttl-refresh-step.ts
index 9bad39934177..d5c81c1cca91 100644
--- a/nodejs/src/ingestion/common/steps/event-preprocessing/overflow-lane-ttl-refresh-step.ts
+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/overflow-lane-ttl-refresh-step.ts
@@ -52,7 +52,7 @@ export function createOverflowLaneTTLRefreshStep<T extends OverflowLaneTTLRefres
// TTL refresh doesn't affect routing, so attach it as a pipeline side effect
// instead of blocking the pipeline on a Redis write.
- const refreshPromise = overflowRedirectService.handleEventBatch('events', batches)
+ const refreshPromise = overflowRedirectService.handleEventBatch(batches)
return Promise.resolve(inputs.map((input) => ok(input, [refreshPromise])))
}
diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.test.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.test.ts
index 81835d87ed92..ab36b1e9a592 100644
--- a/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.test.ts
+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.test.ts
@@ -111,7 +111,7 @@ describe('createRateLimitToOverflowStep', () => {
await step(events)
- expect(service.handleEventBatch).toHaveBeenCalledWith('events', [
+ expect(service.handleEventBatch).toHaveBeenCalledWith([
{ key: { token: 'token1', distinctId: 'user1' }, eventCount: 2, firstTimestamp: baseTime.getTime() },
{ key: { token: 'token2', distinctId: 'user2' }, eventCount: 1, firstTimestamp: baseTime.getTime() },
])
@@ -146,7 +146,7 @@ describe('createRateLimitToOverflowStep', () => {
// Service should be called with 3 unique keys
expect(service.handleEventBatch).toHaveBeenCalledTimes(1)
- const batches = (service.handleEventBatch as jest.Mock).mock.calls[0][1]
+ const batches = (service.handleEventBatch as jest.Mock).mock.calls[0][0]
expect(batches).toHaveLength(3)
})
@@ -359,13 +359,12 @@ describe('createSkipCookielessRateLimitToOverflowStep', () => {
await step(events)
expect(service.handleEventBatch).toHaveBeenCalledWith(
- 'events',
expect.arrayContaining([
expect.objectContaining({ key: { token: 'token1', distinctId: 'user1' }, eventCount: 1 }),
expect.objectContaining({ key: { token: 'token1', distinctId: 'user2' }, eventCount: 1 }),
])
)
- const batches = (service.handleEventBatch as jest.Mock).mock.calls[0][1]
+ const batches = (service.handleEventBatch as jest.Mock).mock.calls[0][0]
expect(batches).toHaveLength(2)
})
@@ -412,7 +411,7 @@ describe('createOnlyCookielessRateLimitToOverflowStep', () => {
await step(events)
- const batches = (service.handleEventBatch as jest.Mock).mock.calls[0][1]
+ const batches = (service.handleEventBatch as jest.Mock).mock.calls[0][0]
expect(batches).toHaveLength(2)
expect(batches).toEqual(
expect.arrayContaining([
diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.ts
index 9fa90c7df6ce..93fb5d71f4ff 100644
--- a/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.ts
+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.ts
@@ -60,7 +60,7 @@ async function applyOverflowRedirect<T extends { headers: EventHeaders }>(
firstTimestamp,
})
)
- const keysToRedirect = await overflowRedirectService.handleEventBatch('events', batches)
+ const keysToRedirect = await overflowRedirectService.handleEventBatch(batches)
return inputs.map((input, index) => {
const eventKey = perInputKeys[index]
diff --git a/nodejs/src/ingestion/pipelines/errortracking/person-properties-step.test.ts b/nodejs/src/ingestion/common/steps/event-processing/fetch-person-batch-step.test.ts
similarity index 91%
rename from nodejs/src/ingestion/pipelines/errortracking/person-properties-step.test.ts
rename to nodejs/src/ingestion/common/steps/event-processing/fetch-person-batch-step.test.ts
index c2bb554c0a52..06a9b19b24c5 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/person-properties-step.test.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/fetch-person-batch-step.test.ts
@@ -6,7 +6,7 @@ import { createTestPluginEvent } from '~/tests/helpers/plugin-event'
import { createTestTeam } from '~/tests/helpers/team'
import { InternalPerson } from '~/types'
-import { createFetchPersonBatchStep } from './person-properties-step'
+import { createFetchPersonBatchStep } from './fetch-person-batch-step'
describe('createFetchPersonBatchStep', () => {
let mockPersonRepository: jest.Mocked<PersonReadRepository>
@@ -87,11 +87,11 @@ describe('createFetchPersonBatchStep', () => {
{ teamId: 123, distinctId: 'user-1' },
{ teamId: 123, distinctId: 'user-2' },
],
- 'error-tracking/person-properties'
+ 'fetch-person-batch-step'
)
})
- it('returns null person when person not found', async () => {
+ it('returns undefined person when person not found', async () => {
const event = createTestPluginEvent({
distinct_id: 'unknown-user',
event: '$exception',
@@ -106,11 +106,11 @@ describe('createFetchPersonBatchStep', () => {
expect(results[0].type).toBe(PipelineResultType.OK)
if (isOkResult(results[0])) {
expect(results[0].value.event.properties).toEqual({ existing: 'property' })
- expect(results[0].value.person).toBeNull()
+ expect(results[0].value.person).toBeUndefined()
}
})
- it('returns null person when distinct_id is missing', async () => {
+ it('returns undefined person when distinct_id is missing', async () => {
const event = createTestPluginEvent({
distinct_id: '',
event: '$exception',
@@ -123,7 +123,7 @@ describe('createFetchPersonBatchStep', () => {
expect(results[0].type).toBe(PipelineResultType.OK)
if (isOkResult(results[0])) {
expect(results[0].value.event.properties).toEqual({ existing: 'property' })
- expect(results[0].value.person).toBeNull()
+ expect(results[0].value.person).toBeUndefined()
}
expect(mockPersonRepository.fetchPersonsByDistinctIds).not.toHaveBeenCalled()
})
@@ -151,10 +151,10 @@ describe('createFetchPersonBatchStep', () => {
expect(results).toHaveLength(2)
if (isOkResult(results[0])) {
- expect(results[0].value.person).not.toBeNull()
+ expect(results[0].value.person).toBeDefined()
}
if (isOkResult(results[1])) {
- expect(results[1].value.person).toBeNull()
+ expect(results[1].value.person).toBeUndefined()
}
})
@@ -181,15 +181,15 @@ describe('createFetchPersonBatchStep', () => {
expect(results).toHaveLength(2)
if (isOkResult(results[0])) {
- expect(results[0].value.person).not.toBeNull()
+ expect(results[0].value.person).toBeDefined()
}
if (isOkResult(results[1])) {
- expect(results[1].value.person).toBeNull()
+ expect(results[1].value.person).toBeUndefined()
}
// Should only query for the event with distinct_id
expect(mockPersonRepository.fetchPersonsByDistinctIds).toHaveBeenCalledWith(
[{ teamId: 123, distinctId: 'user-123' }],
- 'error-tracking/person-properties'
+ 'fetch-person-batch-step'
)
})
diff --git a/nodejs/src/ingestion/pipelines/errortracking/person-properties-step.ts b/nodejs/src/ingestion/common/steps/event-processing/fetch-person-batch-step.ts
similarity index 58%
rename from nodejs/src/ingestion/pipelines/errortracking/person-properties-step.ts
rename to nodejs/src/ingestion/common/steps/event-processing/fetch-person-batch-step.ts
index e5edf40b0eed..90c8d3f159b0 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/person-properties-step.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/fetch-person-batch-step.ts
@@ -4,17 +4,22 @@ import { PipelineResult, ok } from '~/ingestion/framework/results'
import { PluginEvent } from '~/plugin-scaffold'
import { Person, Team } from '~/types'
-export interface PersonPropertiesInput {
+export interface FetchPersonBatchStepInput {
event: PluginEvent
team: Team
}
+// Query name forwarded to the repository (the "what query" half of the personhog
+// read tag). The "who" half — pipeline/lane — is the repository's client label.
+const QUERY_NAME = 'fetch-person-batch-step'
+
function personKey(teamId: number, distinctId: string): string {
return `${teamId}:${distinctId}`
}
/**
- * Creates a batch step that fetches person data for error tracking events.
+ * Creates a batch step that fetches person data for read-only pipelines
+ * (error tracking, AI).
*
* This is a read-only step that fetches person data from the database
* and passes it downstream. It does not create or update persons, and
@@ -25,11 +30,15 @@ function personKey(teamId: number, distinctId: string): string {
* fields on the ClickHouse event.
*
* This is a batch step to avoid N+1 queries when processing multiple events.
+ * The per-pipeline identity (client name) comes from the repository's client
+ * label; this step only tags the query.
*/
-export function createFetchPersonBatchStep<T extends PersonPropertiesInput>(
+export function createFetchPersonBatchStep<T extends FetchPersonBatchStepInput>(
personRepository: PersonReadRepository
-): BatchProcessingStep<T, T & { person: Person | null }> {
- return async function fetchPersonBatchStep(inputs: T[]): Promise<PipelineResult<T & { person: Person | null }>[]> {
+): BatchProcessingStep<T, T & { person: Person | undefined }> {
+ return async function fetchPersonBatchStep(
+ inputs: T[]
+ ): Promise<PipelineResult<T & { person: Person | undefined }>[]> {
if (inputs.length === 0) {
return []
}
@@ -40,19 +49,17 @@ export function createFetchPersonBatchStep<T extends PersonPropertiesInput>(
.map((input) => ({ teamId: input.team.id, distinctId: input.event.distinct_id }))
// Batch fetch all persons in a single query
- const persons =
- lookups.length > 0
- ? await personRepository.fetchPersonsByDistinctIds(lookups, 'error-tracking/person-properties')
- : []
+ const persons = lookups.length > 0 ? await personRepository.fetchPersonsByDistinctIds(lookups, QUERY_NAME) : []
// Build lookup map
const personMap = new Map(persons.map((p) => [personKey(p.team_id, p.distinct_id), p as Person]))
- // Map results back to inputs
+ // Map results back to inputs. `undefined` (not `null`) for not-found, matching
+ // the optional `person?` that createCreateEventStep / createEvent expect.
return inputs.map((input) => {
const person = input.event.distinct_id
- ? (personMap.get(personKey(input.team.id, input.event.distinct_id)) ?? null)
- : null
+ ? personMap.get(personKey(input.team.id, input.event.distinct_id))
+ : undefined
return ok({ ...input, person })
})
}
diff --git a/nodejs/src/ingestion/common/steps/event-processing/flush-hog-transformer-step.ts b/nodejs/src/ingestion/common/steps/event-processing/flush-hog-transformer-step.ts
new file mode 100644
index 000000000000..64e6130ad9ff
--- /dev/null
+++ b/nodejs/src/ingestion/common/steps/event-processing/flush-hog-transformer-step.ts
@@ -0,0 +1,29 @@
+import { Histogram } from 'prom-client'
+
+import { HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'
+import { PipelineResult, ok } from '~/ingestion/framework/results'
+import { ProcessingStep } from '~/ingestion/framework/steps'
+
+const backgroundTaskHogTransformerDuration = new Histogram({
+ name: 'ingestion_background_task_hog_transformer_duration_seconds',
+ help: 'Time waiting for hog transformer invocation results in the background task',
+ buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],
+})
+
+/**
+ * afterBatch step that drains the hog transformer's accumulated invocation
+ * results once per batch. `transformEventAndProduceMessages` buffers results
+ * on every call; without a per-batch drain that buffer grows unbounded over the
+ * consumer's lifetime. Returns the drain as a side effect so it's awaited
+ * alongside the batch's other scheduled work rather than blocking the pipeline,
+ * timing it on the way out so the duration stays observable.
+ */
+export function createFlushHogTransformerStep<T>(
+ hogTransformer: Pick<HogTransformer, 'processInvocationResults'>
+): ProcessingStep<T, T> {
+ return function flushHogTransformerStep(input: T): Promise<PipelineResult<T>> {
+ const stopTimer = backgroundTaskHogTransformerDuration.startTimer()
+ const drain = hogTransformer.processInvocationResults().finally(stopTimer)
+ return Promise.resolve(ok(input, [drain]))
+ }
+}
diff --git a/nodejs/src/ingestion/common/steps/event-processing/strip-person-update-properties-step.test.ts b/nodejs/src/ingestion/common/steps/event-processing/strip-person-update-properties-step.test.ts
new file mode 100644
index 000000000000..2ecf344e9248
--- /dev/null
+++ b/nodejs/src/ingestion/common/steps/event-processing/strip-person-update-properties-step.test.ts
@@ -0,0 +1,87 @@
+import { PipelineResultType } from '~/ingestion/framework/results'
+import { PluginEvent } from '~/plugin-scaffold'
+import { createTestPluginEvent } from '~/tests/helpers/plugin-event'
+
+import { createStripPersonUpdatePropertiesStep } from './strip-person-update-properties-step'
+
+describe('stripPersonUpdatePropertiesStep', () => {
+ const step = createStripPersonUpdatePropertiesStep()
+
+ const inputWithProperties = (properties: PluginEvent['properties']) => ({
+ normalizedEvent: createTestPluginEvent({ properties }),
+ })
+
+ it('strips both $set and $set_once while keeping other properties', async () => {
+ const input = inputWithProperties({
+ $set: { email: '[email protected]' },
+ $set_once: { initial_referrer: 'google' },
+ $current_url: 'http://example.com',
+ foo: 'bar',
+ })
+
+ const result = await step(input)
+
+ expect(result.type).toBe(PipelineResultType.OK)
+ if (result.type === PipelineResultType.OK) {
+ expect(result.value.normalizedEvent.properties).toEqual({
+ $current_url: 'http://example.com',
+ foo: 'bar',
+ })
+ }
+ })
+
+ it.each(['$set', '$set_once'])('strips %s when it is the only update property present', async (key) => {
+ const input = inputWithProperties({ [key]: { email: '[email protected]' }, kept: 'value' })
+
+ const result = await step(input)
+
+ expect(result.type).toBe(PipelineResultType.OK)
+ if (result.type === PipelineResultType.OK) {
+ expect(result.value.normalizedEvent.properties).not.toHaveProperty(key)
+ expect(result.value.normalizedEvent.properties).toEqual({ kept: 'value' })
+ }
+ })
+
+ it('leaves properties untouched when neither $set nor $set_once is present', async () => {
+ const input = inputWithProperties({ $current_url: 'http://example.com', foo: 'bar' })
+
+ const result = await step(input)
+
+ expect(result.type).toBe(PipelineResultType.OK)
+ if (result.type === PipelineResultType.OK) {
+ expect(result.value.normalizedEvent.properties).toEqual({
+ $current_url: 'http://example.com',
+ foo: 'bar',
+ })
+ }
+ })
+
+ it('handles an event with no properties without throwing', async () => {
+ const input = { normalizedEvent: createTestPluginEvent({ properties: undefined }) }
+
+ const result = await step(input)
+
+ expect(result.type).toBe(PipelineResultType.OK)
+ if (result.type === PipelineResultType.OK) {
+ expect(result.value.normalizedEvent.properties).toBeUndefined()
+ }
+ })
+
+ it('mutates the event in place and passes through other input fields', async () => {
+ const stepWithExtra = createStripPersonUpdatePropertiesStep<{ normalizedEvent: PluginEvent; extra: string }>()
+ const normalizedEvent = createTestPluginEvent({
+ properties: { $set: { email: '[email protected]' }, foo: 'bar' },
+ })
+ const input = { normalizedEvent, extra: 'preserved' }
+
+ const result = await stepWithExtra(input)
+
+ expect(result.type).toBe(PipelineResultType.OK)
+ if (result.type === PipelineResultType.OK) {
+ expect(result.value).toBe(input)
+ expect(result.value.normalizedEvent).toBe(normalizedEvent)
+ expect(result.value.normalizedEvent.properties).toEqual({ foo: 'bar' })
+ expect(result.value.extra).toBe('preserved')
+ }
+ })
+})
diff --git a/nodejs/src/ingestion/common/steps/event-processing/strip-person-update-properties-step.ts b/nodejs/src/ingestion/common/steps/event-processing/strip-person-update-properties-step.ts
new file mode 100644
index 000000000000..b7c537b65ff1
--- /dev/null
+++ b/nodejs/src/ingestion/common/steps/event-processing/strip-person-update-properties-step.ts
@@ -0,0 +1,28 @@
+import { ok } from '~/ingestion/framework/results'
+import { ProcessingStep } from '~/ingestion/framework/steps'
+import { PluginEvent } from '~/plugin-scaffold'
+
+export interface StripPersonUpdatePropertiesStepInput {
+ normalizedEvent: PluginEvent
+}
+
+/**
+ * Strips `$set` / `$set_once` from the normalized event for read-only pipelines
+ * (e.g. AI). These pipelines never write the person, so createEvent merging
+ * `$set` into person_properties (when processPerson is true) would put values on
+ * the emitted event that were never persisted. Mutation is safe — the event is
+ * consumed downstream.
+ */
+export function createStripPersonUpdatePropertiesStep<T extends StripPersonUpdatePropertiesStepInput>(): ProcessingStep<
+ T,
+ T
+> {
+ return function stripPersonUpdatePropertiesStep(input) {
+ const properties = input.normalizedEvent.properties
+ if (properties) {
+ delete properties.$set
+ delete properties.$set_once
+ }
+ return Promise.resolve(ok(input))
+ }
+}
diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.ts
index 63bf6817d7e4..1eda59e016c9 100644
--- a/nodejs/src/ingestion/ingestion-consumer.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.ts
@@ -108,13 +108,6 @@ const backgroundTaskProducesDuration = new Histogram({
buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],
})
-const backgroundTaskHogTransformerDuration = new Histogram({
- name: 'ingestion_background_task_hog_transformer_duration_seconds',
- help: 'Time waiting for hog transformer invocation results in the background task',
- labelNames: ['groupId'],
- buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],
-})
-
export class IngestionConsumer {
protected name = 'ingestion-consumer'
protected groupId: string
@@ -192,6 +185,7 @@ export class IngestionConsumer {
bucketCapacity: this.config.EVENT_OVERFLOW_BUCKET_CAPACITY,
replenishRate: this.config.EVENT_OVERFLOW_BUCKET_REPLENISH_RATE,
statefulEnabled: this.config.INGESTION_STATEFUL_OVERFLOW_ENABLED,
+ overflowType: 'events',
})
}
@@ -199,6 +193,7 @@ export class IngestionConsumer {
if (this.config.INGESTION_LANE === 'overflow' && this.config.INGESTION_STATEFUL_OVERFLOW_ENABLED) {
this.overflowLaneTTLRefreshService = new OverflowLaneOverflowRedirect({
redisRepository: overflowRedisRepository,
+ overflowType: 'events',
})
}
@@ -424,12 +419,9 @@ export class IngestionConsumer {
return {
backgroundTask: this.runInstrumented('awaitScheduledWork', async () => {
const labels = { groupId: this.groupId }
- await Promise.all([
- timedHistogram(backgroundTaskProducesDuration, labels, () => this.promiseScheduler.waitForAll()),
- timedHistogram(backgroundTaskHogTransformerDuration, labels, () =>
- this.hogTransformer.processInvocationResults()
- ),
- ])
+ // Drains scheduled produces and the hog transformer invocation results, which
+ // the pipeline's afterBatch flush step schedules as a side effect.
+ await timedHistogram(backgroundTaskProducesDuration, labels, () => this.promiseScheduler.waitForAll())
}),
}
}
diff --git a/nodejs/src/ingestion/pipelines/ai/consumer.test.ts b/nodejs/src/ingestion/pipelines/ai/consumer.test.ts
new file mode 100644
index 000000000000..a791e7dd6fa7
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/ai/consumer.test.ts
@@ -0,0 +1,91 @@
+import { HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'
+import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'
+import { PersonHogConfig } from '~/common/personhog'
+import { PostgresRouter } from '~/common/utils/db/postgres'
+import { TeamManagerComponent } from '~/common/utils/team-manager'
+import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
+import { ProducerName } from '~/ingestion/common/producers'
+import { newScope } from '~/ingestion/common/scopes'
+import { IngestionConsumerConfig, IngestionOutputsConfig } from '~/ingestion/config'
+import { RedisPool } from '~/types'
+
+import { AiConsumerConfig, AiOutputs, AiSharedScope, createAiConsumer } from './consumer'
+import * as pipelineModule from './pipeline'
+
+jest.mock('./pipeline')
+
+describe('createAiConsumer', () => {
+ function makeConfig(): AiConsumerConfig {
+ return {
+ INGESTION_CONSUMER_GROUP_ID: 'g',
+ INGESTION_CONSUMER_CONSUME_TOPIC: 't',
+ INGESTION_PIPELINE: 'ai',
+ INGESTION_LANE: 'main',
+ KAFKA_BATCH_START_LOGGING_ENABLED: false,
+ INGESTION_CONSUMER_OVERFLOW_TOPIC: '',
+ INGESTION_OVERFLOW_PRESERVE_PARTITION_LOCALITY: false,
+ INGESTION_WORKER_CONCURRENT_BATCHES: 1,
+ DROP_EVENTS_BY_TOKEN_DISTINCT_ID: '',
+ SKIP_PERSONS_PROCESSING_BY_TOKEN_DISTINCT_ID: '',
+ INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID: '',
+ EVENT_SCHEMA_ENFORCEMENT_ENABLED: false,
+ CDP_HOG_WATCHER_SAMPLE_RATE: 1,
+ ...({} as Pick<
+ IngestionConsumerConfig,
+ | 'INGESTION_STATEFUL_OVERFLOW_ENABLED'
+ | 'INGESTION_STATEFUL_OVERFLOW_REDIS_TTL_SECONDS'
+ | 'INGESTION_STATEFUL_OVERFLOW_LOCAL_CACHE_TTL_SECONDS'
+ | 'EVENT_OVERFLOW_BUCKET_CAPACITY'
+ | 'EVENT_OVERFLOW_BUCKET_REPLENISH_RATE'
+ >),
+ ...({} as IngestionOutputsConfig),
+ ...({} as PersonHogConfig),
+ }
+ }
+
+ function makeSharedScope(): AiSharedScope {
+ // The consumer factory extends this scope but doesn't start it (start happens
+ // at the caller), so the shape only has to be type-correct.
+ return newScope('shared-test', (b) =>
+ b
+ .add('postgres', {
+ start: () => Promise.resolve({ value: {} as PostgresRouter, stop: () => Promise.resolve() }),
+ })
+ .add('redisPool', {
+ start: () => Promise.resolve({ value: {} as RedisPool, stop: () => Promise.resolve() }),
+ })
+ .add('teamManager', new TeamManagerComponent({} as PostgresRouter))
+ .add('cookielessManager', {
+ start: () => Promise.resolve({ value: {} as CookielessManager, stop: () => Promise.resolve() }),
+ })
+ .add('producerRegistry', {
+ start: () =>
+ Promise.resolve({
+ value: {} as KafkaProducerRegistry<ProducerName>,
+ stop: () => Promise.resolve(),
+ }),
+ })
+ .add('hogTransformer', {
+ start: () => Promise.resolve({ value: {} as HogTransformer, stop: () => Promise.resolve() }),
+ })
+ .add('outputs', {
+ start: () => Promise.resolve({ value: {} as AiOutputs, stop: () => Promise.resolve() }),
+ })
+ )
+ }
+
+ beforeEach(() => {
+ ;(pipelineModule.createAiIngestionPipeline as jest.Mock) = jest.fn().mockReturnValue({
+ feed: jest.fn(),
+ next: jest.fn(),
+ })
+ })
+
+ it('defers pipeline construction until scope.start()', () => {
+ createAiConsumer(makeConfig(), makeSharedScope())
+
+ // The pipeline factory runs inside the extend callback at start time, after the
+ // scope's services come up — not at consumer construction time.
+ expect(pipelineModule.createAiIngestionPipeline).not.toHaveBeenCalled()
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/ai/consumer.ts b/nodejs/src/ingestion/pipelines/ai/consumer.ts
new file mode 100644
index 000000000000..acb31103f6d9
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/ai/consumer.ts
@@ -0,0 +1,183 @@
+import { CommonConfig } from '~/common/config'
+import { ReadOnlyGroupTypeManager } from '~/common/groups/readonly-group-type-manager'
+import { HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'
+import {
+ AiEventOutput,
+ AppMetricsOutput,
+ DlqOutput,
+ EventOutput,
+ IngestionWarningsOutput,
+ OverflowOutput,
+ TophogOutput,
+} from '~/common/outputs'
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'
+import { PersonHogConfig } from '~/common/personhog'
+import { PersonHogClientComponent } from '~/common/personhog/personhog-client-component'
+import { PersonHogGroupReadRepository } from '~/common/personhog/personhog-group-read-repository'
+import { PersonHogPersonReadRepository } from '~/common/personhog/personhog-person-read-repository'
+import { PostgresRouter } from '~/common/utils/db/postgres'
+import { EventIngestionRestrictionManagerComponent } from '~/common/utils/event-ingestion-restrictions'
+import { EventSchemaEnforcementManager } from '~/common/utils/event-schema-enforcement-manager'
+import { TeamManager } from '~/common/utils/team-manager'
+import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
+import { EventFilterManagerComponent } from '~/ingestion/common/event-filters'
+import { CommonIngestionConsumerConfig, CommonIngestionConsumerScope } from '~/ingestion/common/ingestion-consumer'
+import { ProducerName } from '~/ingestion/common/producers'
+import { Scope, extend } from '~/ingestion/common/scopes'
+import { PromiseSchedulerComponent } from '~/ingestion/common/utils/promise-scheduler'
+import { IngestionConsumerConfig, IngestionOutputsConfig } from '~/ingestion/config'
+import { createTopHogWrapper } from '~/ingestion/framework/extensions/tophog'
+import { TopHog } from '~/ingestion/framework/tophog'
+import { DisabledOverflowRedirectComponent } from '~/ingestion/utils/overflow-redirect/disabled-overflow-redirect'
+import { MainLaneOverflowRedirectComponent } from '~/ingestion/utils/overflow-redirect/main-lane-overflow-redirect'
+import { OverflowLaneOverflowRedirectComponent } from '~/ingestion/utils/overflow-redirect/overflow-lane-overflow-redirect'
+import { RedisOverflowRepositoryComponent } from '~/ingestion/utils/overflow-redirect/overflow-redis-repository'
+import { RedisPool } from '~/types'
+
+import { createAiIngestionPipeline } from './pipeline'
+
+export type AiConsumerConfig = CommonIngestionConsumerConfig &
+ IngestionOutputsConfig &
+ PersonHogConfig &
+ Pick<
+ IngestionConsumerConfig,
+ | 'INGESTION_CONSUMER_OVERFLOW_TOPIC'
+ | 'INGESTION_STATEFUL_OVERFLOW_ENABLED'
+ | 'INGESTION_STATEFUL_OVERFLOW_REDIS_TTL_SECONDS'
+ | 'INGESTION_STATEFUL_OVERFLOW_LOCAL_CACHE_TTL_SECONDS'
+ | 'EVENT_OVERFLOW_BUCKET_CAPACITY'
+ | 'EVENT_OVERFLOW_BUCKET_REPLENISH_RATE'
+ | 'INGESTION_OVERFLOW_PRESERVE_PARTITION_LOCALITY'
+ | 'INGESTION_WORKER_CONCURRENT_BATCHES'
+ | 'DROP_EVENTS_BY_TOKEN_DISTINCT_ID'
+ | 'SKIP_PERSONS_PROCESSING_BY_TOKEN_DISTINCT_ID'
+ | 'INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID'
+ | 'EVENT_SCHEMA_ENFORCEMENT_ENABLED'
+ > &
+ Pick<CommonConfig, 'CDP_HOG_WATCHER_SAMPLE_RATE'>
+
+/** Outputs the AI pipeline emits to. The same instance backs the hog transformer's
+ * monitoring (app_metrics + log_entries), wired up server-side. */
+export type AiOutputs = IngestionOutputs<
+ EventOutput | AiEventOutput | IngestionWarningsOutput | DlqOutput | OverflowOutput | AppMetricsOutput | TophogOutput
+>
+
+/**
+ * Services shared from the server scope. Extends the base shared scope with the
+ * hog transformer and outputs, which the server must build because the lane can't
+ * construct the cdp-owned transformer (boundary) and the same outputs instance
+ * backs the transformer's monitoring. The personhog client is owned by the AI
+ * scope (created from common, tagged for this pipeline), not shared in here.
+ */
+export type AiSharedScope = Scope<{
+ postgres: PostgresRouter
+ redisPool: RedisPool
+ teamManager: TeamManager
+ cookielessManager: CookielessManager
+ producerRegistry: KafkaProducerRegistry<ProducerName>
+ hogTransformer: HogTransformer
+ outputs: AiOutputs
+}>
+
+export function createAiConsumer(config: AiConsumerConfig, sharedScope: AiSharedScope) {
+ const splitTokens = (value: string): string[] => value.split(',').filter((x) => !!x)
+ const overflowEnabled =
+ !!config.INGESTION_CONSUMER_OVERFLOW_TOPIC &&
+ config.INGESTION_CONSUMER_OVERFLOW_TOPIC !== config.INGESTION_CONSUMER_CONSUME_TOPIC
+ const overflowLaneEnabled = config.INGESTION_LANE === 'overflow' && config.INGESTION_STATEFUL_OVERFLOW_ENABLED
+ const preservePartitionLocality = config.INGESTION_OVERFLOW_PRESERVE_PARTITION_LOCALITY
+ // Client name for personhog read metrics: pipeline + lane (e.g. "ai/main").
+ // The query name is supplied per call (e.g. "person-properties").
+ const clientLabel = `ai/${config.INGESTION_LANE ?? 'main'}`
+
+ // Parent scope: the overflow Redis repository, shared by the main-lane and
+ // overflow-lane redirect services below (set up here, not inline per service).
+ const overflowScope = extend(sharedScope, 'ai-overflow', (container, builder) =>
+ builder.add(
+ 'overflowRedisRepository',
+ new RedisOverflowRepositoryComponent(
+ container.redisPool,
+ config.INGESTION_STATEFUL_OVERFLOW_REDIS_TTL_SECONDS
+ )
+ )
+ )
+
+ const scope = extend(overflowScope, 'ai', (container, builder) =>
+ builder
+ .add('promiseScheduler', new PromiseSchedulerComponent())
+ .add(
+ 'eventIngestionRestrictionManager',
+ new EventIngestionRestrictionManagerComponent(container.redisPool, {
+ pipeline: 'ai',
+ staticDropEventTokens: splitTokens(config.DROP_EVENTS_BY_TOKEN_DISTINCT_ID),
+ staticSkipPersonTokens: splitTokens(config.SKIP_PERSONS_PROCESSING_BY_TOKEN_DISTINCT_ID),
+ staticForceOverflowTokens: splitTokens(config.INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID),
+ })
+ )
+ .add('eventFilterManager', new EventFilterManagerComponent(container.postgres))
+ // Dedicated 'ai' keyspace so AI overflow never affects analytics.
+ .add(
+ 'overflowRedirectService',
+ overflowEnabled
+ ? new MainLaneOverflowRedirectComponent({
+ redisRepository: container.overflowRedisRepository,
+ localCacheTTLSeconds: config.INGESTION_STATEFUL_OVERFLOW_LOCAL_CACHE_TTL_SECONDS,
+ bucketCapacity: config.EVENT_OVERFLOW_BUCKET_CAPACITY,
+ replenishRate: config.EVENT_OVERFLOW_BUCKET_REPLENISH_RATE,
+ statefulEnabled: config.INGESTION_STATEFUL_OVERFLOW_ENABLED,
+ overflowType: 'ai',
+ })
+ : new DisabledOverflowRedirectComponent()
+ )
+ .add(
+ 'overflowLaneTTLRefreshService',
+ overflowLaneEnabled
+ ? new OverflowLaneOverflowRedirectComponent({
+ redisRepository: container.overflowRedisRepository,
+ overflowType: 'ai',
+ })
+ : new DisabledOverflowRedirectComponent()
+ )
+ // Personhog client owned by the AI scope (created from common, torn down with it).
+ .add('personhogClient', new PersonHogClientComponent(config))
+ // TopHog metrics registry for this lane's outputs (drains per-team/partition counters).
+ .add('topHog', {
+ start: () => {
+ const topHog = new TopHog({
+ outputs: container.outputs,
+ pipeline: config.INGESTION_PIPELINE ?? 'unknown',
+ lane: config.INGESTION_LANE ?? 'unknown',
+ })
+ topHog.start()
+ return Promise.resolve({ value: topHog, stop: () => topHog.stop() })
+ },
+ })
+ )
+
+ return new CommonIngestionConsumerScope('ai', config, scope, ({ container }) =>
+ createAiIngestionPipeline({
+ outputs: container.outputs,
+ teamManager: container.teamManager,
+ eventIngestionRestrictionManager: container.eventIngestionRestrictionManager,
+ eventFilterManager: container.eventFilterManager,
+ cookielessManager: container.cookielessManager,
+ promiseScheduler: container.promiseScheduler,
+ hogTransformer: container.hogTransformer,
+ // Read-only person/group access — read through personhog, never written.
+ personRepository: new PersonHogPersonReadRepository(container.personhogClient, clientLabel),
+ groupTypeManager: new ReadOnlyGroupTypeManager(
+ new PersonHogGroupReadRepository(container.personhogClient, clientLabel)
+ ),
+ overflowEnabled,
+ preservePartitionLocality,
+ overflowRedirectService: container.overflowRedirectService,
+ overflowLaneTTLRefreshService: container.overflowLaneTTLRefreshService,
+ concurrentBatches: config.INGESTION_WORKER_CONCURRENT_BATCHES,
+ cdpHogWatcherSampleRate: config.CDP_HOG_WATCHER_SAMPLE_RATE,
+ eventSchemaEnforcementEnabled: config.EVENT_SCHEMA_ENFORCEMENT_ENABLED,
+ eventSchemaEnforcementManager: new EventSchemaEnforcementManager(container.postgres),
+ topHog: createTopHogWrapper(container.topHog),
+ })
+ )
+}
diff --git a/nodejs/src/ingestion/pipelines/ai/index.ts b/nodejs/src/ingestion/pipelines/ai/index.ts
index bc42ef2996f9..b9220e7d3380 100644
--- a/nodejs/src/ingestion/pipelines/ai/index.ts
+++ b/nodejs/src/ingestion/pipelines/ai/index.ts
@@ -1,3 +1,5 @@
export { normalizeTraceProperties, processAiEvent, type EventWithProperties } from './process-ai-event'
export { AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'
export { createAiEventSubpipeline, type AiEventSubpipelineConfig } from './pipelines/ai-event-subpipeline'
+export { createAiIngestionPipeline, type AiIngestionPipelineConfig } from './pipeline'
+export { createAiConsumer, type AiConsumerConfig, type AiSharedScope } from './consumer'
diff --git a/nodejs/src/ingestion/pipelines/ai/outputs/index.ts b/nodejs/src/ingestion/pipelines/ai/outputs/index.ts
new file mode 100644
index 000000000000..8e907c85bfcc
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/ai/outputs/index.ts
@@ -0,0 +1 @@
+export { AI_EVENTS_OUTPUT, EVENTS_OUTPUT, type AiEventOutput, type EventOutput } from '~/common/outputs'
diff --git a/nodejs/src/ingestion/pipelines/ai/outputs/registry.ts b/nodejs/src/ingestion/pipelines/ai/outputs/registry.ts
new file mode 100644
index 000000000000..596347c01b0d
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/ai/outputs/registry.ts
@@ -0,0 +1,56 @@
+import {
+ AI_EVENTS_OUTPUT,
+ APP_METRICS_OUTPUT,
+ DLQ_OUTPUT,
+ EVENTS_OUTPUT,
+ INGESTION_WARNINGS_OUTPUT,
+ LOG_ENTRIES_OUTPUT,
+ OVERFLOW_OUTPUT,
+ TOPHOG_OUTPUT,
+} from '~/common/outputs'
+import { IngestionOutputsBuilder } from '~/common/outputs/ingestion-outputs-builder'
+
+/**
+ * Register the outputs the AI pipeline produces to. Like the analytics AI
+ * branch, AI events are double-written to both the events output (main events
+ * table) and the dedicated ai_events output. No persons/groups outputs — the
+ * AI pipeline reads person/group data but never writes it. app_metrics +
+ * log_entries back the hog-function monitoring path (the transformer runs in
+ * this lane). Call `.build(registry, config)` to resolve against the shared
+ * producer registry.
+ */
+export function createOutputsRegistry() {
+ return new IngestionOutputsBuilder()
+ .register(EVENTS_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_EVENTS_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_EVENTS_PRODUCER',
+ })
+ .register(AI_EVENTS_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_AI_EVENTS_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_AI_EVENTS_PRODUCER',
+ })
+ .register(INGESTION_WARNINGS_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_INGESTION_WARNINGS_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_INGESTION_WARNINGS_PRODUCER',
+ })
+ .register(DLQ_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_DLQ_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_DLQ_PRODUCER',
+ })
+ .register(OVERFLOW_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_OVERFLOW_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_OVERFLOW_PRODUCER',
+ })
+ .register(APP_METRICS_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_APP_METRICS_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_APP_METRICS_PRODUCER',
+ })
+ .register(LOG_ENTRIES_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_LOG_ENTRIES_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_LOG_ENTRIES_PRODUCER',
+ })
+ .register(TOPHOG_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_TOPHOG_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_TOPHOG_PRODUCER',
+ })
+}
diff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts
new file mode 100644
index 000000000000..91cc0e5c344b
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts
@@ -0,0 +1,225 @@
+import { Message } from 'node-rdkafka'
+
+import { ReadOnlyGroupTypeManager } from '~/common/groups/readonly-group-type-manager'
+import { HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'
+import { KafkaProducerWrapper } from '~/common/kafka/producer'
+import { APP_METRICS_OUTPUT, DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT, OVERFLOW_OUTPUT } from '~/common/outputs'
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
+import { PersonReadRepository } from '~/common/persons/repositories/person-repository'
+import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'
+import { EventSchemaEnforcementManager } from '~/common/utils/event-schema-enforcement-manager'
+import { parseJSON } from '~/common/utils/json-parse'
+import { PromiseScheduler } from '~/common/utils/promise-scheduler'
+import { TeamManager } from '~/common/utils/team-manager'
+import { UUIDT } from '~/common/utils/utils'
+import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
+import { TopHogWrapper } from '~/ingestion/framework/extensions/tophog'
+import { createOkContext } from '~/ingestion/framework/helpers'
+import { ok } from '~/ingestion/framework/results'
+import { DisabledOverflowRedirect } from '~/ingestion/utils/overflow-redirect/disabled-overflow-redirect'
+import { createTestTeam } from '~/tests/helpers/team'
+
+import { AI_EVENTS_OUTPUT, EVENTS_OUTPUT } from './outputs'
+import { AiIngestionPipelineConfig, createAiIngestionPipeline } from './pipeline'
+
+jest.mock('~/common/utils/logger', () => ({
+ logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },
+}))
+
+const EVENTS_TOPIC = 'clickhouse_events_json_test'
+const AI_EVENTS_TOPIC = 'clickhouse_ai_events_json_test'
+const DLQ_TOPIC = 'events_plugin_ingestion_dlq_test'
+
+describe('AiIngestionPipeline', () => {
+ let mockKafkaProducer: jest.Mocked<KafkaProducerWrapper>
+ let mockTeamManager: jest.Mocked<TeamManager>
+ let mockEventIngestionRestrictionManager: jest.Mocked<EventIngestionRestrictionManager>
+ let mockEventFilterManager: { getFilter: jest.Mock }
+ let mockCookielessManager: jest.Mocked<CookielessManager>
+ let mockHogTransformer: jest.Mocked<
+ Pick<
+ HogTransformer,
+ 'transformEventAndProduceMessages' | 'processInvocationResults' | 'prefetchTransformationStatesForTeams'
+ >
+ >
+ let mockPersonRepository: jest.Mocked<PersonReadRepository>
+ let mockGroupTypeManager: jest.Mocked<ReadOnlyGroupTypeManager>
+ let promiseScheduler: PromiseScheduler
+ let config: AiIngestionPipelineConfig
+
+ const team = createTestTeam({ id: 123, api_token: 'token-123' })
+
+ const createMessage = (event: string, properties: Record<string, any> = {}): Message => {
+ const distinctId = 'user-1'
+ const eventData = {
+ event,
+ distinct_id: distinctId,
+ uuid: new UUIDT().toString(),
+ timestamp: '2024-01-01T00:00:00Z',
+ properties: { $ai_trace_id: 'trace-1', ...properties },
+ }
+ return {
+ value: Buffer.from(
+ JSON.stringify({ token: team.api_token, data: JSON.stringify(eventData), ...eventData })
+ ),
+ headers: [
+ { token: Buffer.from(team.api_token) },
+ { distinct_id: Buffer.from(distinctId) },
+ // Capture sets the event-name header; the allow-list reads it before the body is parsed.
+ { event: Buffer.from(event) },
+ ],
+ topic: 'ai_ingestion',
+ partition: 0,
+ offset: 0,
+ size: 0,
+ key: Buffer.from(distinctId),
+ } as Message
+ }
+
+ const runPipeline = async (messages: Message[]): Promise<void> => {
+ const pipeline = createAiIngestionPipeline(config)
+ const batch = messages.map((message) => createOkContext({ message }, { message }))
+ await pipeline.feed(batch)
+ let result = await pipeline.next()
+ while (result !== null) {
+ for (const sideEffect of result.sideEffects ?? []) {
+ void promiseScheduler.schedule(sideEffect)
+ }
+ result = await pipeline.next()
+ }
+ await promiseScheduler.waitForAll()
+ }
+
+ const producedForTopic = (topic: string): any[] =>
+ mockKafkaProducer.produce.mock.calls
+ .map((call) => call[0])
+ .filter((arg: any) => arg.topic === topic)
+ .map((arg: any) => parseJSON(arg.value!.toString()))
+
+ beforeEach(() => {
+ mockKafkaProducer = {
+ produce: jest.fn().mockResolvedValue(undefined),
+ queueMessages: jest.fn().mockResolvedValue(undefined),
+ flush: jest.fn().mockResolvedValue(undefined),
+ } as unknown as jest.Mocked<KafkaProducerWrapper>
+
+ mockTeamManager = {
+ getTeamByToken: jest.fn().mockResolvedValue(team),
+ getTeam: jest.fn().mockResolvedValue(team),
+ } as unknown as jest.Mocked<TeamManager>
+
+ mockEventIngestionRestrictionManager = {
+ getAppliedRestrictions: jest.fn().mockReturnValue(new Set()),
+ forceRefresh: jest.fn(),
+ } as unknown as jest.Mocked<EventIngestionRestrictionManager>
+
+ mockEventFilterManager = { getFilter: jest.fn().mockReturnValue(undefined) }
+
+ mockCookielessManager = {
+ doBatch: jest.fn().mockImplementation((events: any[]) => Promise.resolve(events.map((e) => ok(e)))),
+ } as unknown as jest.Mocked<CookielessManager>
+
+ mockHogTransformer = {
+ transformEventAndProduceMessages: jest
+ .fn()
+ .mockImplementation((event) => Promise.resolve({ event, invocationResults: [] })),
+ processInvocationResults: jest.fn().mockResolvedValue(undefined),
+ prefetchTransformationStatesForTeams: jest.fn().mockResolvedValue(undefined),
+ } as unknown as jest.Mocked<
+ Pick<
+ HogTransformer,
+ 'transformEventAndProduceMessages' | 'processInvocationResults' | 'prefetchTransformationStatesForTeams'
+ >
+ >
+
+ mockPersonRepository = {
+ fetchPerson: jest.fn(),
+ fetchPersonsByDistinctIds: jest.fn().mockResolvedValue([]),
+ fetchPersonsByPersonIds: jest.fn(),
+ fetchDistinctIdsForPersons: jest.fn().mockResolvedValue({}),
+ } as unknown as jest.Mocked<PersonReadRepository>
+
+ mockGroupTypeManager = {
+ fetchGroupTypes: jest.fn().mockResolvedValue({}),
+ fetchGroupTypesForProjects: jest.fn().mockResolvedValue({}),
+ } as unknown as jest.Mocked<ReadOnlyGroupTypeManager>
+
+ promiseScheduler = new PromiseScheduler()
+
+ const single = (output: string, topic: string) =>
+ new SingleIngestionOutput(output, topic, mockKafkaProducer, 'test')
+
+ config = {
+ outputs: new IngestionOutputs({
+ [EVENTS_OUTPUT]: single(EVENTS_OUTPUT, EVENTS_TOPIC),
+ [AI_EVENTS_OUTPUT]: single(AI_EVENTS_OUTPUT, AI_EVENTS_TOPIC),
+ [DLQ_OUTPUT]: single(DLQ_OUTPUT, DLQ_TOPIC),
+ [INGESTION_WARNINGS_OUTPUT]: single(INGESTION_WARNINGS_OUTPUT, 'clickhouse_ingestion_warnings_test'),
+ [OVERFLOW_OUTPUT]: single(OVERFLOW_OUTPUT, 'events_plugin_ingestion_overflow_test'),
+ [APP_METRICS_OUTPUT]: single(APP_METRICS_OUTPUT, 'clickhouse_app_metrics2_test'),
+ }),
+ teamManager: mockTeamManager,
+ eventIngestionRestrictionManager: mockEventIngestionRestrictionManager,
+ eventFilterManager: mockEventFilterManager as any,
+ cookielessManager: mockCookielessManager,
+ promiseScheduler,
+ hogTransformer: mockHogTransformer as unknown as HogTransformer,
+ personRepository: mockPersonRepository,
+ groupTypeManager: mockGroupTypeManager,
+ overflowEnabled: false,
+ preservePartitionLocality: false,
+ overflowRedirectService: new DisabledOverflowRedirect(),
+ overflowLaneTTLRefreshService: new DisabledOverflowRedirect(),
+ concurrentBatches: 1,
+ cdpHogWatcherSampleRate: 1,
+ eventSchemaEnforcementEnabled: false,
+ eventSchemaEnforcementManager: {} as unknown as EventSchemaEnforcementManager,
+ // No-op metrics wrapper — these tests assert pipeline output, not topHog counters.
+ topHog: ((step) => step) as TopHogWrapper,
+ }
+ })
+
+ it('double-writes AI events to both the events and ai_events outputs', async () => {
+ await runPipeline([createMessage('$ai_generation')])
+
+ expect(producedForTopic(EVENTS_TOPIC)).toHaveLength(1)
+ expect(producedForTopic(AI_EVENTS_TOPIC)).toHaveLength(1)
+ expect(producedForTopic(DLQ_TOPIC)).toHaveLength(0)
+ })
+
+ it.each(['$pageview', '$autocapture', '$identify', '$exception', 'custom_event'])(
+ 'DLQs non-AI %s events instead of processing them',
+ async (eventName) => {
+ await runPipeline([createMessage(eventName)])
+
+ expect(producedForTopic(DLQ_TOPIC)).toHaveLength(1)
+ expect(producedForTopic(EVENTS_TOPIC)).toHaveLength(0)
+ expect(producedForTopic(AI_EVENTS_TOPIC)).toHaveLength(0)
+ }
+ )
+
+ it('fetches person data read-only and never writes persons or groups', async () => {
+ await runPipeline([createMessage('$ai_generation')])
+
+ expect(mockPersonRepository.fetchPersonsByDistinctIds).toHaveBeenCalledTimes(1)
+ expect(mockPersonRepository.fetchPersonsByDistinctIds).toHaveBeenCalledWith(
+ [{ teamId: 123, distinctId: 'user-1' }],
+ 'fetch-person-batch-step'
+ )
+ })
+
+ it('drains hog transformer invocation results once per batch', async () => {
+ await runPipeline([createMessage('$ai_generation'), createMessage('$ai_span')])
+
+ expect(mockHogTransformer.processInvocationResults).toHaveBeenCalledTimes(1)
+ })
+
+ it('prefetches hog transformation states for the batch teams before transforming', async () => {
+ await runPipeline([createMessage('$ai_generation'), createMessage('$ai_span')])
+
+ // Without this prefetch the transformer can't see Hog watcher's disabled state,
+ // so disabled transformations would still run.
+ expect(mockHogTransformer.prefetchTransformationStatesForTeams).toHaveBeenCalledWith([123])
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.ts
new file mode 100644
index 000000000000..a2b7c6766879
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.ts
@@ -0,0 +1,306 @@
+import { Message } from 'node-rdkafka'
+
+import { ReadOnlyGroupTypeManager } from '~/common/groups/readonly-group-type-manager'
+import { HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'
+import { AppMetricsOutput, DlqOutput, IngestionWarningsOutput, OverflowOutput } from '~/common/outputs'
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import { PersonReadRepository } from '~/common/persons/repositories/person-repository'
+import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'
+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 { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
+import { EventFilterManager } from '~/ingestion/common/event-filters'
+import { createAllowEventsStep } from '~/ingestion/common/steps/allow-events'
+import {
+ EventFiltersBatchContext,
+ createApplyEventFiltersStep,
+ createEventFiltersBatchAppMetricsBeforeBatchStep,
+ createFlushEventFiltersBatchAppMetricsStep,
+} from '~/ingestion/common/steps/event-filters-steps'
+import {
+ createApplyCookielessProcessingStep,
+ createApplyEventRestrictionsStep,
+ createApplyPersonProcessingRestrictionsStep,
+ createOnlyCookielessRateLimitToOverflowStep,
+ createOverflowLaneTTLRefreshStep,
+ createParseHeadersStep,
+ createParseKafkaMessageStep,
+ createResolveTeamStep,
+ createSkipCookielessRateLimitToOverflowStep,
+ createValidateAiEventTokensStep,
+ createValidateEventMetadataStep,
+ createValidateEventPropertiesStep,
+ createValidateEventSchemaStep,
+ createValidateHistoricalMigrationStep,
+} from '~/ingestion/common/steps/event-preprocessing'
+import { createCreateEventStep } from '~/ingestion/common/steps/event-processing/create-event-step'
+import { createDropOldEventsStep } from '~/ingestion/common/steps/event-processing/drop-old-events-step'
+import { EmitEventStepOutput, createEmitEventStep } from '~/ingestion/common/steps/event-processing/emit-event-step'
+import { createFetchPersonBatchStep } from '~/ingestion/common/steps/event-processing/fetch-person-batch-step'
+import { createFlushHogTransformerStep } from '~/ingestion/common/steps/event-processing/flush-hog-transformer-step'
+import { createHogTransformEventStep } from '~/ingestion/common/steps/event-processing/hog-transform-event-step'
+import { createNormalizeEventStep } from '~/ingestion/common/steps/event-processing/normalize-event-step'
+import { createNormalizeProcessPersonFlagStep } from '~/ingestion/common/steps/event-processing/normalize-process-person-flag-step'
+import { createPrefetchHogFunctionsStep } from '~/ingestion/common/steps/event-processing/prefetch-hog-functions-step'
+import { createPrepareEventStep } from '~/ingestion/common/steps/event-processing/prepare-event-step'
+import { createReadOnlyProcessGroupsStep } from '~/ingestion/common/steps/event-processing/readonly-process-groups-step'
+import { createSplitAiEventsStep } from '~/ingestion/common/steps/event-processing/split-ai-events-step'
+import { createStripPersonUpdatePropertiesStep } from '~/ingestion/common/steps/event-processing/strip-person-update-properties-step'
+import { createRecordIngestionLagStep } from '~/ingestion/common/steps/record-ingestion-lag'
+import { addTeamToContext } from '~/ingestion/common/subpipelines/helpers'
+import { newBatchingPipeline } from '~/ingestion/framework/builders'
+import { TopHogWrapper, sum, sumOk, sumResult } from '~/ingestion/framework/extensions/tophog'
+import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'
+import { isDropResult } from '~/ingestion/framework/results'
+import { OverflowRedirectService } from '~/ingestion/utils/overflow-redirect/overflow-redirect-service'
+
+import { AiEventOutput, EVENTS_OUTPUT, EventOutput } from './outputs'
+import { createProcessAiEventStep } from './pipelines/steps/process-ai-event-step'
+
+export interface AiIngestionPipelineConfig {
+ outputs: IngestionOutputs<
+ EventOutput | AiEventOutput | IngestionWarningsOutput | DlqOutput | OverflowOutput | AppMetricsOutput
+ >
+ teamManager: TeamManager
+ eventIngestionRestrictionManager: EventIngestionRestrictionManager
+ eventFilterManager: EventFilterManager
+ cookielessManager: CookielessManager
+ promiseScheduler: PromiseScheduler
+ hogTransformer: HogTransformer
+ // Read-only person/group access — the AI pipeline never writes persons or groups.
+ personRepository: PersonReadRepository
+ groupTypeManager: ReadOnlyGroupTypeManager
+ overflowEnabled: boolean
+ preservePartitionLocality: boolean
+ overflowRedirectService: OverflowRedirectService
+ overflowLaneTTLRefreshService: OverflowRedirectService
+ concurrentBatches: number
+ cdpHogWatcherSampleRate: number
+ eventSchemaEnforcementEnabled: boolean
+ eventSchemaEnforcementManager: EventSchemaEnforcementManager
+ topHog: TopHogWrapper
+}
+
+interface AiIngestionPipelineInput {
+ message: Message
+}
+
+interface AiIngestionPipelineContext {
+ message: Message
+}
+
+/**
+ * Standalone AI ingestion pipeline. Mirrors the AI branch of the analytics
+ * joined pipeline, but:
+ * - only AI events flow through (everything else is DLQ'd by the allow step),
+ * - person and group data are read-only (fetched, never written), like error
+ * tracking — so there are no person/group batch stores or per-distinct-id
+ * ordering, just a batch person fetch + sequential per-event processing,
+ * - overflow uses the dedicated `'ai'` keyspace (wired at service construction),
+ * so AI overflow can never affect analytics.
+ *
+ * AI events are still double-written to both the events output and the
+ * ai_events output (via the split step), keeping it a drop-in for the analytics
+ * AI branch once capture-side routing switches over.
+ */
+export function createAiIngestionPipeline<
+ TInput extends AiIngestionPipelineInput,
+ TContext extends AiIngestionPipelineContext,
+>(config: AiIngestionPipelineConfig) {
+ const {
+ outputs,
+ teamManager,
+ eventIngestionRestrictionManager,
+ eventFilterManager,
+ cookielessManager,
+ promiseScheduler,
+ hogTransformer,
+ personRepository,
+ groupTypeManager,
+ overflowEnabled,
+ preservePartitionLocality,
+ overflowRedirectService,
+ overflowLaneTTLRefreshService,
+ concurrentBatches,
+ cdpHogWatcherSampleRate,
+ eventSchemaEnforcementEnabled,
+ eventSchemaEnforcementManager,
+ topHog,
+ } = config
+
+ const pipelineConfig: PipelineConfig<OverflowOutput> = {
+ outputs,
+ promiseScheduler,
+ }
+
+ return newBatchingPipeline<
+ TInput,
+ EmitEventStepOutput,
+ TContext,
+ EventFiltersBatchContext,
+ TContext,
+ OverflowOutput
+ >(
+ (beforeBatch) => beforeBatch.pipe(createEventFiltersBatchAppMetricsBeforeBatchStep(outputs)),
+ (batch) =>
+ batch
+ .messageAware((b) =>
+ b
+ // Header-only steps: parse headers, allow only AI events, apply token restrictions.
+ .sequentially((b) =>
+ b
+ .pipe(createParseHeadersStep())
+ .pipe(createAllowEventsStep([...AI_EVENT_TYPES]))
+ .pipe(
+ createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {
+ overflowEnabled,
+ preservePartitionLocality,
+ })
+ )
+ )
+ // Rate-limit non-cookieless events to overflow before parsing the body.
+ // Cookieless events pass through and are handled post-cookieless below.
+ .pipeBatch(
+ createSkipCookielessRateLimitToOverflowStep(
+ preservePartitionLocality,
+ overflowRedirectService
+ )
+ )
+ // Body parse, team resolution, and AI token validation.
+ .sequentially((b) =>
+ b
+ .pipe(createParseKafkaMessageStep())
+ .pipe(createResolveTeamStep(teamManager))
+ .pipe(createValidateHistoricalMigrationStep())
+ .pipe(createValidateAiEventTokensStep())
+ )
+ .filterMap(addTeamToContext, (b) =>
+ b
+ .teamAware((b) =>
+ b
+ .sequentially((b) => {
+ const validated = b
+ .pipe(createValidateEventMetadataStep())
+ .pipe(createValidateEventPropertiesStep())
+ // Schema enforcement is opt-in (same as analytics); only
+ // applied when enabled so AI events match that path.
+ const schemaChecked = eventSchemaEnforcementEnabled
+ ? validated.pipe(
+ createValidateEventSchemaStep(eventSchemaEnforcementManager)
+ )
+ : validated
+ return schemaChecked
+ .pipe(
+ createApplyPersonProcessingRestrictionsStep(
+ eventIngestionRestrictionManager
+ )
+ )
+ .pipe(createDropOldEventsStep())
+ .pipe(createApplyEventFiltersStep(eventFilterManager))
+ })
+ // Cookieless processing rewrites distinct_id; person fetch keys on the
+ // final distinct_id, so it must run after this batch step.
+ .gather()
+ .pipeBatch(createApplyCookielessProcessingStep(cookielessManager))
+ .pipeBatch(
+ createOnlyCookielessRateLimitToOverflowStep(
+ preservePartitionLocality,
+ overflowRedirectService
+ )
+ )
+ .pipeBatch(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))
+ // Read-only batch person fetch (no person writes).
+ .pipeBatch(createFetchPersonBatchStep(personRepository))
+ // Prefetch hog functions for the batch's teams so the transformer
+ // honors Hog watcher's disabled-function state (mirrors analytics).
+ .pipeBatch(
+ createPrefetchHogFunctionsStep(hogTransformer, cdpHogWatcherSampleRate)
+ )
+ .sequentially((b) =>
+ // Retry the per-event chain on transient failures (hog
+ // transform, group-type fetch, emit), matching the
+ // analytics per-distinct-id retry.
+ b.retry(
+ (e) =>
+ e
+ .pipe(createNormalizeProcessPersonFlagStep())
+ .pipe(
+ topHog(createHogTransformEventStep(hogTransformer), [
+ sumOk(
+ 'transformations_run',
+ (output) => ({ team_id: String(output.team.id) }),
+ (output) => output.transformationsRun
+ ),
+ sumOk(
+ 'transformations_run_per_partition',
+ (output, input) => ({
+ team_id: String(output.team.id),
+ partition: String(input.message.partition),
+ }),
+ (output) => output.transformationsRun
+ ),
+ sumResult(
+ 'events_dropped_by_transformation',
+ (_result, input) => ({
+ team_id: String(input.team.id),
+ }),
+ (result) => (isDropResult(result) ? 1 : 0)
+ ),
+ sumResult(
+ 'events_dropped_by_transformation_per_partition',
+ (_result, input) => ({
+ team_id: String(input.team.id),
+ partition: String(input.message.partition),
+ }),
+ (result) => (isDropResult(result) ? 1 : 0)
+ ),
+ ])
+ )
+ .pipe(createNormalizeEventStep())
+ .pipe(createProcessAiEventStep())
+ // Read-only: drop person-update props so they don't
+ // leak into person_properties (person is never written).
+ .pipe(createStripPersonUpdatePropertiesStep())
+ .pipe(createPrepareEventStep())
+ // Read-only group-type resolution (no new group types created).
+ .pipe(createReadOnlyProcessGroupsStep(groupTypeManager))
+ .pipe(createCreateEventStep(EVENTS_OUTPUT))
+ // Double-write to events + ai_events outputs.
+ .pipe(createSplitAiEventsStep())
+ .pipe(
+ topHog(createEmitEventStep({ outputs }), [
+ sum(
+ 'emitted_events',
+ (input) => ({ team_id: String(input.teamId) }),
+ (input) => input.eventsToEmit.length
+ ),
+ sum(
+ 'emitted_events_per_partition',
+ (input) => ({
+ team_id: String(input.teamId),
+ partition: String(input.message.partition),
+ }),
+ (input) => input.eventsToEmit.length
+ ),
+ ])
+ )
+ .pipe(createRecordIngestionLagStep()),
+ { tries: 5, sleepMs: 100, name: 'ai_event' }
+ )
+ )
+ )
+ .handleIngestionWarnings(outputs)
+ )
+ )
+ .handleResults(pipelineConfig)
+ .handleSideEffects(promiseScheduler, { await: false }),
+ (afterBatch) =>
+ afterBatch
+ .pipe(createFlushEventFiltersBatchAppMetricsStep())
+ // Drain hog transformer invocation results once per batch.
+ .pipe(createFlushHogTransformerStep(hogTransformer)),
+ { concurrentBatches }
+ )
+}
diff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
index 6494a0977cab..613afe4180d3 100644
--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
@@ -32,6 +32,7 @@ import {
import { EmitEventStepOutput } from '~/ingestion/common/steps/event-processing/emit-event-step'
import { EventPipelineRunnerOptions } from '~/ingestion/common/steps/event-processing/event-pipeline-options'
import { createFlushBatchStoresStep } from '~/ingestion/common/steps/event-processing/flush-batch-stores-step'
+import { createFlushHogTransformerStep } from '~/ingestion/common/steps/event-processing/flush-hog-transformer-step'
import {
GroupStoreBatchContext,
createGroupStoreBeforeBatchStep,
@@ -278,7 +279,8 @@ export function createJoinedIngestionPipeline<
(afterBatch) =>
afterBatch
.pipe(createFlushBatchStoresStep({ personsStore, groupStore, outputs }))
- .pipe(createFlushEventFiltersBatchAppMetricsStep()),
+ .pipe(createFlushEventFiltersBatchAppMetricsStep())
+ .pipe(createFlushHogTransformerStep(hogTransformer)),
// Batch stores are singleton persistent caches, but each batch receives a
// batch-bound view so entries can be reference-counted and released after
// that batch's flush lifecycle completes. The Rust consumer's per-worker
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts
index 9a4afcea8470..ce5af833a7bb 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts
@@ -181,6 +181,7 @@ export class ErrorTrackingConsumer {
bucketCapacity: config.overflowBucketCapacity,
replenishRate: config.overflowBucketReplenishRate,
statefulEnabled: config.statefulOverflowEnabled,
+ overflowType: 'errortracking',
})
}
@@ -188,6 +189,7 @@ export class ErrorTrackingConsumer {
if (config.lane === 'overflow' && config.statefulOverflowEnabled) {
this.overflowLaneTTLRefreshService = new OverflowLaneOverflowRedirect({
redisRepository: overflowRedisRepository,
+ overflowType: 'errortracking',
})
}
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts
index f6dc9467cc0d..d35be33b2c7d 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts
@@ -29,6 +29,7 @@ import {
} from '~/ingestion/common/steps/event-preprocessing'
import { createCreateEventStep } from '~/ingestion/common/steps/event-processing/create-event-step'
import { EmitEventStepOutput, createEmitEventStep } from '~/ingestion/common/steps/event-processing/emit-event-step'
+import { createFetchPersonBatchStep } from '~/ingestion/common/steps/event-processing/fetch-person-batch-step'
import { createHogTransformEventStep } from '~/ingestion/common/steps/event-processing/hog-transform-event-step'
import { createReadOnlyProcessGroupsStep } from '~/ingestion/common/steps/event-processing/readonly-process-groups-step'
import { createRecordIngestionLagStep } from '~/ingestion/common/steps/record-ingestion-lag'
@@ -47,7 +48,6 @@ import { CymbalClient } from './cymbal/client'
import { ErrorTrackingHogTransformer } from './error-tracking-consumer'
import { KeyedRateLimiterStepOptions, createKeyedRateLimiterStep } from './keyed-rate-limiter-step'
import { createLoadErrorTrackingSettingsStep } from './load-error-tracking-settings-step'
-import { createFetchPersonBatchStep } from './person-properties-step'
import { createErrorTrackingPrepareEventStep } from './prepare-event-step'
export interface ErrorTrackingPipelineInput {
diff --git a/nodejs/src/ingestion/pipelines/errortracking/index.ts b/nodejs/src/ingestion/pipelines/errortracking/index.ts
index e0d6ecb23deb..97be86052144 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/index.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/index.ts
@@ -17,4 +17,3 @@ export type {
// Steps
export { createCymbalProcessingStep } from './cymbal-processing-step'
-export { createFetchPersonBatchStep } from './person-properties-step'
diff --git a/nodejs/src/ingestion/pipelines/errortracking/prepare-event-step.test.ts b/nodejs/src/ingestion/pipelines/errortracking/prepare-event-step.test.ts
index 242683451b62..d67794706654 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/prepare-event-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/prepare-event-step.test.ts
@@ -69,7 +69,7 @@ describe('createErrorTrackingPrepareEventStep', () => {
it('returns undefined person when person is null', async () => {
const event = createTestPluginEvent({ event: '$exception' })
- const result = await step({ event, team, person: null, headers: createTestEventHeaders() })
+ const result = await step({ event, team, person: undefined, headers: createTestEventHeaders() })
expect(result.type).toBe(PipelineResultType.OK)
if (isOkResult(result)) {
@@ -90,7 +90,7 @@ describe('createErrorTrackingPrepareEventStep', () => {
expect(isOkResult(resultWithPerson) && resultWithPerson.value.processPerson).toBe(true)
// Without person
- const resultWithoutPerson = await step({ event, team, person: null, headers: createTestEventHeaders() })
+ const resultWithoutPerson = await step({ event, team, person: undefined, headers: createTestEventHeaders() })
expect(isOkResult(resultWithoutPerson) && resultWithoutPerson.value.processPerson).toBe(true)
})
@@ -100,7 +100,7 @@ describe('createErrorTrackingPrepareEventStep', () => {
const result = await step({
event,
team,
- person: null,
+ person: undefined,
headers: createTestEventHeaders({ historical_migration: true }),
})
@@ -113,7 +113,7 @@ describe('createErrorTrackingPrepareEventStep', () => {
it('defaults historical_migration to false when not in headers', async () => {
const event = createTestPluginEvent({ event: '$exception' })
- const result = await step({ event, team, person: null, headers: createTestEventHeaders() })
+ const result = await step({ event, team, person: undefined, headers: createTestEventHeaders() })
expect(result.type).toBe(PipelineResultType.OK)
if (isOkResult(result)) {
@@ -129,7 +129,7 @@ describe('createErrorTrackingPrepareEventStep', () => {
timestamp: '2024-01-20T12:00:00.000Z',
})
- const result = await step({ event, team, person: null, headers: createTestEventHeaders() })
+ const result = await step({ event, team, person: undefined, headers: createTestEventHeaders() })
expect(result.type).toBe(PipelineResultType.OK)
if (isOkResult(result)) {
@@ -143,7 +143,7 @@ describe('createErrorTrackingPrepareEventStep', () => {
properties: null as any,
})
- const result = await step({ event, team, person: null, headers: createTestEventHeaders() })
+ const result = await step({ event, team, person: undefined, headers: createTestEventHeaders() })
expect(result.type).toBe(PipelineResultType.OK)
if (isOkResult(result)) {
@@ -158,7 +158,7 @@ describe('createErrorTrackingPrepareEventStep', () => {
})
const anonymizedTeam = createTestTeam({ id: 123, project_id: 456 as any, anonymize_ips: true })
- const result = await step({ event, team: anonymizedTeam, person: null, headers: createTestEventHeaders() })
+ const result = await step({ event, team: anonymizedTeam, person: undefined, headers: createTestEventHeaders() })
expect(result.type).toBe(PipelineResultType.OK)
if (isOkResult(result)) {
@@ -177,7 +177,7 @@ describe('createErrorTrackingPrepareEventStep', () => {
},
})
- const result = await step({ event, team, person: null, headers: createTestEventHeaders() })
+ const result = await step({ event, team, person: undefined, headers: createTestEventHeaders() })
expect(result.type).toBe(PipelineResultType.OK)
if (isOkResult(result)) {
@@ -193,7 +193,7 @@ describe('createErrorTrackingPrepareEventStep', () => {
properties: { $ip: '1.2.3.4' },
})
- const result = await step({ event, team, person: null, headers: createTestEventHeaders() })
+ const result = await step({ event, team, person: undefined, headers: createTestEventHeaders() })
expect(result.type).toBe(PipelineResultType.OK)
if (isOkResult(result)) {
@@ -215,7 +215,7 @@ describe('createErrorTrackingPrepareEventStep', () => {
},
})
- const result = await step({ event, team, person: null, headers: createTestEventHeaders() })
+ const result = await step({ event, team, person: undefined, headers: createTestEventHeaders() })
expect(result.type).toBe(PipelineResultType.OK)
if (isOkResult(result)) {
@@ -237,7 +237,7 @@ describe('createErrorTrackingPrepareEventStep', () => {
},
})
- const result = await step({ event, team, person: null, headers: createTestEventHeaders() })
+ const result = await step({ event, team, person: undefined, headers: createTestEventHeaders() })
expect(result.type).toBe(PipelineResultType.OK)
if (isOkResult(result)) {
@@ -259,7 +259,7 @@ describe('createErrorTrackingPrepareEventStep', () => {
},
})
- const result = await step({ event, team, person: null, headers: createTestEventHeaders() })
+ const result = await step({ event, team, person: undefined, headers: createTestEventHeaders() })
expect(result.type).toBe(PipelineResultType.OK)
if (isOkResult(result)) {
@@ -278,7 +278,7 @@ describe('createErrorTrackingPrepareEventStep', () => {
const inputWithExtras = {
event,
team,
- person: null,
+ person: undefined,
headers: createTestEventHeaders(),
message: { topic: 'test-topic', partition: 0 } as any,
customField: 'should-be-preserved',
@@ -301,7 +301,7 @@ describe('createErrorTrackingPrepareEventStep', () => {
it('removes event from output but preserves team and adds preparedEvent', async () => {
const event = createTestPluginEvent({ event: '$exception' })
- const result = await step({ event, team, person: null, headers: createTestEventHeaders() })
+ const result = await step({ event, team, person: undefined, headers: createTestEventHeaders() })
expect(result.type).toBe(PipelineResultType.OK)
if (isOkResult(result)) {
diff --git a/nodejs/src/ingestion/pipelines/errortracking/prepare-event-step.ts b/nodejs/src/ingestion/pipelines/errortracking/prepare-event-step.ts
index b043e0cdfa91..f8d682ea4629 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/prepare-event-step.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/prepare-event-step.ts
@@ -7,7 +7,7 @@ import { EventHeaders, ISOTimestamp, Person, PreIngestionEvent, Team } from '~/t
export interface ErrorTrackingPrepareEventInput {
event: PluginEvent
team: Team
- person: Person | null
+ person: Person | undefined
headers: EventHeaders
}
diff --git a/nodejs/src/ingestion/utils/overflow-redirect/disabled-overflow-redirect.ts b/nodejs/src/ingestion/utils/overflow-redirect/disabled-overflow-redirect.ts
new file mode 100644
index 000000000000..c0de255f7a33
--- /dev/null
+++ b/nodejs/src/ingestion/utils/overflow-redirect/disabled-overflow-redirect.ts
@@ -0,0 +1,31 @@
+import { Component } from '~/ingestion/common/scopes'
+import { HealthCheckResult, HealthCheckResultOk } from '~/types'
+
+import { OverflowRedirectService } from './overflow-redirect-service'
+
+/**
+ * No-op overflow redirect for lanes where overflow is disabled. Never
+ * redirects and holds no state, so callers can always depend on a service
+ * being present instead of branching on `undefined`.
+ */
+export class DisabledOverflowRedirect implements OverflowRedirectService {
+ handleEventBatch(): Promise<Set<string>> {
+ return Promise.resolve(new Set())
+ }
+
+ healthCheck(): Promise<HealthCheckResult> {
+ return Promise.resolve(new HealthCheckResultOk())
+ }
+
+ shutdown(): Promise<void> {
+ return Promise.resolve()
+ }
+}
+
+/** Scope component for the no-op overflow redirect (overflow disabled for the lane). */
+export class DisabledOverflowRedirectComponent implements Component<OverflowRedirectService> {
+ start(): Promise<{ value: OverflowRedirectService; stop: () => Promise<void> }> {
+ const service = new DisabledOverflowRedirect()
+ return Promise.resolve({ value: service, stop: () => service.shutdown() })
+ }
+}
diff --git a/nodejs/src/ingestion/utils/overflow-redirect/main-lane-overflow-redirect.test.ts b/nodejs/src/ingestion/utils/overflow-redirect/main-lane-overflow-redirect.test.ts
index 59acf75e4756..86e75f5f0ec0 100644
--- a/nodejs/src/ingestion/utils/overflow-redirect/main-lane-overflow-redirect.test.ts
+++ b/nodejs/src/ingestion/utils/overflow-redirect/main-lane-overflow-redirect.test.ts
@@ -33,6 +33,7 @@ describe('MainLaneOverflowRedirect', () => {
bucketCapacity: 10,
replenishRate: 1,
statefulEnabled: true,
+ overflowType: 'events',
...overrides,
})
}
@@ -46,7 +47,7 @@ describe('MainLaneOverflowRedirect', () => {
it('returns empty set when no events exceed rate limit', async () => {
const batch = [createBatch('token1', 'user1', 5)]
- const result = await service.handleEventBatch('events', batch)
+ const result = await service.handleEventBatch(batch)
expect(result.size).toBe(0)
})
@@ -55,7 +56,7 @@ describe('MainLaneOverflowRedirect', () => {
// Bucket capacity is 10, so 15 events should exceed
const batch = [createBatch('token1', 'user1', 15)]
- const result = await service.handleEventBatch('events', batch)
+ const result = await service.handleEventBatch(batch)
expect(result.size).toBe(1)
expect(result.has('token1:user1')).toBe(true)
@@ -64,7 +65,7 @@ describe('MainLaneOverflowRedirect', () => {
it('flags newly rate-limited keys in Redis', async () => {
const batch = [createBatch('token1', 'user1', 15)]
- await service.handleEventBatch('events', batch)
+ await service.handleEventBatch(batch)
expect(mockRepository.batchFlag).toHaveBeenCalledWith('events', [{ token: 'token1', distinctId: 'user1' }])
})
@@ -72,7 +73,7 @@ describe('MainLaneOverflowRedirect', () => {
it('checks Redis for keys not in local cache', async () => {
const batch = [createBatch('token1', 'user1', 5)]
- await service.handleEventBatch('events', batch)
+ await service.handleEventBatch(batch)
expect(mockRepository.batchCheck).toHaveBeenCalledWith('events', [{ token: 'token1', distinctId: 'user1' }])
})
@@ -82,7 +83,7 @@ describe('MainLaneOverflowRedirect', () => {
const batch = [createBatch('token1', 'user1', 1)]
- const result = await service.handleEventBatch('events', batch)
+ const result = await service.handleEventBatch(batch)
expect(result.size).toBe(1)
expect(result.has('token1:user1')).toBe(true)
@@ -93,14 +94,14 @@ describe('MainLaneOverflowRedirect', () => {
mockRepository.batchCheck.mockResolvedValue(new Map([['token1:user1', true]]))
const batch1 = [createBatch('token1', 'user1', 1)]
- await service.handleEventBatch('events', batch1)
+ await service.handleEventBatch(batch1)
// Reset mock
mockRepository.batchCheck.mockClear()
// Second call: should use cache, not repository
const batch2 = [createBatch('token1', 'user1', 1)]
- const result = await service.handleEventBatch('events', batch2)
+ const result = await service.handleEventBatch(batch2)
expect(result.size).toBe(1)
expect(result.has('token1:user1')).toBe(true)
@@ -112,7 +113,7 @@ describe('MainLaneOverflowRedirect', () => {
mockRepository.batchCheck.mockResolvedValue(new Map([['token1:user1', false]]))
const batch1 = [createBatch('token1', 'user1', 1)]
- await service.handleEventBatch('events', batch1)
+ await service.handleEventBatch(batch1)
// Reset mock
mockRepository.batchCheck.mockClear()
@@ -120,7 +121,7 @@ describe('MainLaneOverflowRedirect', () => {
// Second call: should use cache (null), not check repository again
const batch2 = [createBatch('token1', 'user1', 1)]
- await service.handleEventBatch('events', batch2)
+ await service.handleEventBatch(batch2)
expect(mockRepository.batchCheck).not.toHaveBeenCalled()
})
@@ -138,7 +139,7 @@ describe('MainLaneOverflowRedirect', () => {
createBatch('token1', 'user2', 15), // Exceeds limit
]
- const result = await service.handleEventBatch('events', batch)
+ const result = await service.handleEventBatch(batch)
expect(result.size).toBe(1)
expect(result.has('token1:user2')).toBe(true)
@@ -152,7 +153,7 @@ describe('MainLaneOverflowRedirect', () => {
createBatch('token2', 'user1', 1),
]
- await service.handleEventBatch('events', batch)
+ await service.handleEventBatch(batch)
expect(mockRepository.batchCheck).toHaveBeenCalledTimes(1)
expect(mockRepository.batchCheck).toHaveBeenCalledWith('events', [
@@ -171,7 +172,7 @@ describe('MainLaneOverflowRedirect', () => {
const batch = [createBatch('token1', 'user1', 5)]
- const result = await service.handleEventBatch('events', batch)
+ const result = await service.handleEventBatch(batch)
expect(result.size).toBe(0)
})
@@ -181,7 +182,7 @@ describe('MainLaneOverflowRedirect', () => {
// rate limit decision still causes a redirect for this batch
const batch = [createBatch('token1', 'user1', 15)]
- const result = await service.handleEventBatch('events', batch)
+ const result = await service.handleEventBatch(batch)
expect(result.size).toBe(1)
expect(result.has('token1:user1')).toBe(true)
@@ -192,12 +193,12 @@ describe('MainLaneOverflowRedirect', () => {
it('rate limit state persists across batches', async () => {
// First batch: consume 8 of 10 tokens
const batch1 = [createBatch('token1', 'user1', 8)]
- const result1 = await service.handleEventBatch('events', batch1)
+ const result1 = await service.handleEventBatch(batch1)
expect(result1.size).toBe(0)
// Second batch: consume 3 more tokens (total 11, exceeds 10)
const batch2 = [createBatch('token1', 'user1', 3)]
- const result2 = await service.handleEventBatch('events', batch2)
+ const result2 = await service.handleEventBatch(batch2)
expect(result2.size).toBe(1)
expect(result2.has('token1:user1')).toBe(true)
})
@@ -205,11 +206,11 @@ describe('MainLaneOverflowRedirect', () => {
it('different keys have independent rate limits', async () => {
// Exhaust tokens for user1
const batch1 = [createBatch('token1', 'user1', 15)]
- await service.handleEventBatch('events', batch1)
+ await service.handleEventBatch(batch1)
// user2 should still have tokens
const batch2 = [createBatch('token1', 'user2', 5)]
- const result = await service.handleEventBatch('events', batch2)
+ const result = await service.handleEventBatch(batch2)
expect(result.size).toBe(0)
})
@@ -228,7 +229,7 @@ describe('MainLaneOverflowRedirect', () => {
it('clears local cache', async () => {
// Populate cache
mockRepository.batchCheck.mockResolvedValue(new Map([['token1:user1', true]]))
- await service.handleEventBatch('events', [createBatch('token1', 'user1', 1)])
+ await service.handleEventBatch([createBatch('token1', 'user1', 1)])
await service.shutdown()
@@ -236,7 +237,7 @@ describe('MainLaneOverflowRedirect', () => {
// Next call should check repository again
mockRepository.batchCheck.mockClear()
mockRepository.batchCheck.mockResolvedValue(new Map([['token1:user1', false]]))
- await service.handleEventBatch('events', [createBatch('token1', 'user1', 1)])
+ await service.handleEventBatch([createBatch('token1', 'user1', 1)])
expect(mockRepository.batchCheck).toHaveBeenCalled()
})
diff --git a/nodejs/src/ingestion/utils/overflow-redirect/main-lane-overflow-redirect.ts b/nodejs/src/ingestion/utils/overflow-redirect/main-lane-overflow-redirect.ts
index dc90017c3a9c..8b631624b680 100644
--- a/nodejs/src/ingestion/utils/overflow-redirect/main-lane-overflow-redirect.ts
+++ b/nodejs/src/ingestion/utils/overflow-redirect/main-lane-overflow-redirect.ts
@@ -1,3 +1,4 @@
+import { Component } from '~/ingestion/common/scopes'
import { MemoryRateLimiter } from '~/ingestion/utils/overflow-detector'
import { HealthCheckResult } from '~/types'
@@ -18,6 +19,8 @@ export interface MainLaneOverflowRedirectConfig {
localCacheTTLSeconds: number
bucketCapacity: number
replenishRate: number
+ /** Redis keyspace this service operates on. Fixed per pipeline. */
+ overflowType: OverflowType
}
interface CacheEntry {
@@ -43,6 +46,7 @@ export class MainLaneOverflowRedirect implements OverflowRedirectService {
private localCacheTTLSeconds: number
private statefulEnabled: boolean
private redisRepository: OverflowRedisRepository
+ private overflowType: OverflowType
constructor(config: MainLaneOverflowRedirectConfig) {
this.redisRepository = config.redisRepository
@@ -50,6 +54,7 @@ export class MainLaneOverflowRedirect implements OverflowRedirectService {
this.rateLimiter = new MemoryRateLimiter(config.bucketCapacity, config.replenishRate)
this.localCacheTTLSeconds = config.localCacheTTLSeconds
this.statefulEnabled = config.statefulEnabled
+ this.overflowType = config.overflowType
}
private localCacheKey(type: OverflowType, token: string, distinctId: string): string {
@@ -75,7 +80,8 @@ export class MainLaneOverflowRedirect implements OverflowRedirectService {
})
}
- async handleEventBatch(type: OverflowType, batch: OverflowEventBatch[]): Promise<Set<string>> {
+ async handleEventBatch(batch: OverflowEventBatch[]): Promise<Set<string>> {
+ const type = this.overflowType
const toRedirect = new Set<string>()
const redirectSource = new Map<string, 'redis' | 'rate_limiter'>()
const needsRateLimitCheck: OverflowEventBatch[] = []
@@ -211,3 +217,13 @@ export class MainLaneOverflowRedirect implements OverflowRedirectService {
return Promise.resolve()
}
}
+
+/** Scope component for the main-lane overflow redirect (rate-limiting). */
+export class MainLaneOverflowRedirectComponent implements Component<OverflowRedirectService> {
+ constructor(private readonly config: MainLaneOverflowRedirectConfig) {}
+
+ start(): Promise<{ value: OverflowRedirectService; stop: () => Promise<void> }> {
+ const service = new MainLaneOverflowRedirect(this.config)
+ return Promise.resolve({ value: service, stop: () => service.shutdown() })
+ }
+}
diff --git a/nodejs/src/ingestion/utils/overflow-redirect/overflow-lane-overflow-redirect.test.ts b/nodejs/src/ingestion/utils/overflow-redirect/overflow-lane-overflow-redirect.test.ts
index ab78d92dd5c8..6753f6ec0c89 100644
--- a/nodejs/src/ingestion/utils/overflow-redirect/overflow-lane-overflow-redirect.test.ts
+++ b/nodejs/src/ingestion/utils/overflow-redirect/overflow-lane-overflow-redirect.test.ts
@@ -30,6 +30,7 @@ describe('OverflowLaneOverflowRedirect', () => {
mockRepository = createMockRepository()
service = new OverflowLaneOverflowRedirect({
redisRepository: mockRepository,
+ overflowType: 'events',
})
})
@@ -37,7 +38,7 @@ describe('OverflowLaneOverflowRedirect', () => {
it('always returns empty set (no redirects from overflow lane)', async () => {
const batch = [createBatch('token1', 'user1', 100), createBatch('token1', 'user2', 100)]
- const result = await service.handleEventBatch('events', batch)
+ const result = await service.handleEventBatch(batch)
expect(result.size).toBe(0)
})
@@ -45,7 +46,7 @@ describe('OverflowLaneOverflowRedirect', () => {
it('refreshes TTL for all keys in batch', async () => {
const batch = [createBatch('token1', 'user1'), createBatch('token1', 'user2')]
- await service.handleEventBatch('events', batch)
+ await service.handleEventBatch(batch)
expect(mockRepository.batchRefreshTTL).toHaveBeenCalledWith('events', [
{ token: 'token1', distinctId: 'user1' },
@@ -54,7 +55,12 @@ describe('OverflowLaneOverflowRedirect', () => {
})
it('uses correct overflow type', async () => {
- await service.handleEventBatch('recordings', [createBatch('token1', 'session1')])
+ const recordingsService = new OverflowLaneOverflowRedirect({
+ redisRepository: mockRepository,
+ overflowType: 'recordings',
+ })
+
+ await recordingsService.handleEventBatch([createBatch('token1', 'session1')])
expect(mockRepository.batchRefreshTTL).toHaveBeenCalledWith('recordings', [
{ token: 'token1', distinctId: 'session1' },
@@ -62,7 +68,7 @@ describe('OverflowLaneOverflowRedirect', () => {
})
it('handles empty batch gracefully', async () => {
- const result = await service.handleEventBatch('events', [])
+ const result = await service.handleEventBatch([])
expect(result.size).toBe(0)
expect(mockRepository.batchRefreshTTL).not.toHaveBeenCalled()
@@ -75,7 +81,7 @@ describe('OverflowLaneOverflowRedirect', () => {
createBatch('token2', 'user1'),
]
- await service.handleEventBatch('events', batch)
+ await service.handleEventBatch(batch)
expect(mockRepository.batchRefreshTTL).toHaveBeenCalledTimes(1)
expect(mockRepository.batchRefreshTTL).toHaveBeenCalledWith('events', [
@@ -93,7 +99,7 @@ describe('OverflowLaneOverflowRedirect', () => {
// and the service still returns an empty set (no redirects from overflow lane)
const batch = [createBatch('token1', 'user1')]
- const result = await service.handleEventBatch('events', batch)
+ const result = await service.handleEventBatch(batch)
expect(result.size).toBe(0)
})
diff --git a/nodejs/src/ingestion/utils/overflow-redirect/overflow-lane-overflow-redirect.ts b/nodejs/src/ingestion/utils/overflow-redirect/overflow-lane-overflow-redirect.ts
index 3396c3cb69bd..56b24238798a 100644
--- a/nodejs/src/ingestion/utils/overflow-redirect/overflow-lane-overflow-redirect.ts
+++ b/nodejs/src/ingestion/utils/overflow-redirect/overflow-lane-overflow-redirect.ts
@@ -1,3 +1,4 @@
+import { Component } from '~/ingestion/common/scopes'
import { HealthCheckResult } from '~/types'
import { overflowRedirectEventsTotal, overflowRedirectKeysTotal } from './metrics'
@@ -6,6 +7,8 @@ import { OverflowRedisRepository, OverflowType } from './overflow-redis-reposito
export interface OverflowLaneOverflowRedirectConfig {
redisRepository: OverflowRedisRepository
+ /** Redis keyspace this service operates on. Fixed per pipeline. */
+ overflowType: OverflowType
}
/**
@@ -24,12 +27,16 @@ export interface OverflowLaneOverflowRedirectConfig {
*/
export class OverflowLaneOverflowRedirect implements OverflowRedirectService {
private redisRepository: OverflowRedisRepository
+ private overflowType: OverflowType
constructor(config: OverflowLaneOverflowRedirectConfig) {
this.redisRepository = config.redisRepository
+ this.overflowType = config.overflowType
}
- async handleEventBatch(type: OverflowType, batch: OverflowEventBatch[]): Promise<Set<string>> {
+ async handleEventBatch(batch: OverflowEventBatch[]): Promise<Set<string>> {
+ const type = this.overflowType
+
// Refresh TTL for all keys in the batch
if (batch.length > 0) {
await this.redisRepository.batchRefreshTTL(
@@ -57,3 +64,13 @@ export class OverflowLaneOverflowRedirect implements OverflowRedirectService {
// No local state to clean up in overflow lane implementation
}
}
+
+/** Scope component for the overflow-lane TTL refresh service. */
+export class OverflowLaneOverflowRedirectComponent implements Component<OverflowRedirectService> {
+ constructor(private readonly config: OverflowLaneOverflowRedirectConfig) {}
+
+ start(): Promise<{ value: OverflowRedirectService; stop: () => Promise<void> }> {
+ const service = new OverflowLaneOverflowRedirect(this.config)
+ return Promise.resolve({ value: service, stop: () => service.shutdown() })
+ }
+}
diff --git a/nodejs/src/ingestion/utils/overflow-redirect/overflow-redirect-service.ts b/nodejs/src/ingestion/utils/overflow-redirect/overflow-redirect-service.ts
index e47a652b3770..72fcf5502545 100644
--- a/nodejs/src/ingestion/utils/overflow-redirect/overflow-redirect-service.ts
+++ b/nodejs/src/ingestion/utils/overflow-redirect/overflow-redirect-service.ts
@@ -1,7 +1,5 @@
import { HealthCheckResult } from '~/types'
-import { OverflowType } from './overflow-redis-repository'
-
// Re-export OverflowType so consumers of the interface
// don't need to know about the repository layer
export type { OverflowType } from './overflow-redis-repository'
@@ -28,9 +26,12 @@ export interface OverflowRedirectService {
* - Main lane: Check if flagged, flag if rate limited, return set of keys to redirect
* - Overflow lane: Refresh TTL for all keys, return empty set (no redirects)
*
+ * The overflow keyspace (`OverflowType`) is fixed per service instance and
+ * supplied at construction — a given service belongs to exactly one pipeline.
+ *
* @returns Set of keys (token:distinctId) that should be redirected to overflow
*/
- handleEventBatch(type: OverflowType, batch: OverflowEventBatch[]): Promise<Set<string>>
+ handleEventBatch(batch: OverflowEventBatch[]): Promise<Set<string>>
/**
* Health check for the service
diff --git a/nodejs/src/ingestion/utils/overflow-redirect/overflow-redis-repository.ts b/nodejs/src/ingestion/utils/overflow-redirect/overflow-redis-repository.ts
index 217c3307b91e..1e76bd33760a 100644
--- a/nodejs/src/ingestion/utils/overflow-redirect/overflow-redis-repository.ts
+++ b/nodejs/src/ingestion/utils/overflow-redirect/overflow-redis-repository.ts
@@ -3,11 +3,12 @@ import { Redis } from 'ioredis'
import { timeoutGuard } from '~/common/utils/db/utils'
import { logger } from '~/common/utils/logger'
+import { Component } from '~/ingestion/common/scopes'
import { HealthCheckResult, HealthCheckResultError, HealthCheckResultOk } from '~/types'
import { overflowRedirectRedisLatency, overflowRedirectRedisOpsTotal } from './metrics'
-export type OverflowType = 'events' | 'recordings' | 'llm'
+export type OverflowType = 'events' | 'recordings' | 'ai' | 'errortracking'
const REDIS_KEY_PREFIX = '@posthog/stateful-overflow/'
@@ -220,3 +221,23 @@ export class RedisOverflowRepository implements OverflowRedisRepository {
}
}
}
+
+/**
+ * Scope component for the overflow Redis repository. Set up in a parent scope so
+ * the main-lane and overflow-lane redirect services can share one repository
+ * instance instead of each constructing its own.
+ */
+export class RedisOverflowRepositoryComponent implements Component<OverflowRedisRepository> {
+ constructor(
+ private readonly redisPool: GenericPool<Redis>,
+ private readonly redisTTLSeconds: number
+ ) {}
+
+ start(): Promise<{ value: OverflowRedisRepository; stop: () => Promise<void> }> {
+ const repository = new RedisOverflowRepository({
+ redisPool: this.redisPool,
+ redisTTLSeconds: this.redisTTLSeconds,
+ })
+ return Promise.resolve({ value: repository, stop: () => Promise.resolve() })
+ }
+}
diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.ts
index 22edf2eac28b..2820f94257db 100644
--- a/nodejs/src/servers/ingestion-api-server.ts
+++ b/nodejs/src/servers/ingestion-api-server.ts
@@ -313,6 +313,7 @@ export class IngestionApiServer implements NodeServer {
bucketCapacity: this.config.EVENT_OVERFLOW_BUCKET_CAPACITY,
replenishRate: this.config.EVENT_OVERFLOW_BUCKET_REPLENISH_RATE,
statefulEnabled: this.config.INGESTION_STATEFUL_OVERFLOW_ENABLED,
+ overflowType: 'events',
})
}
@@ -320,6 +321,7 @@ export class IngestionApiServer implements NodeServer {
if (this.config.INGESTION_LANE === 'overflow' && this.config.INGESTION_STATEFUL_OVERFLOW_ENABLED) {
overflowLaneTTLRefreshService = new OverflowLaneOverflowRedirect({
redisRepository: overflowRedisRepository,
+ overflowType: 'events',
})
}
@@ -486,8 +488,10 @@ export class IngestionApiServer implements NodeServer {
}
// Wait for all side effects — the HTTP response is the ACK to the
- // Rust consumer, so all work must finish before responding.
- await Promise.all([this.promiseScheduler.waitForAll(), this.hogTransformer.processInvocationResults()])
+ // Rust consumer, so all work must finish before responding. The hog
+ // transformer drain is scheduled as a side effect by the pipeline's
+ // afterBatch flush step, so it's covered by waitForAll().
+ await this.promiseScheduler.waitForAll()
batchesProcessed.inc()
messagesProcessed.inc(messages.length)
diff --git a/nodejs/src/servers/ingestion-general-server.ts b/nodejs/src/servers/ingestion-general-server.ts
index 3715a27fac10..db70a428ff31 100644
--- a/nodejs/src/servers/ingestion-general-server.ts
+++ b/nodejs/src/servers/ingestion-general-server.ts
@@ -14,6 +14,8 @@ import {
import { GroupTypeManager } from '~/common/groups/group-type-manager'
import { ClickhouseGroupRepository } from '~/common/groups/repositories/clickhouse-group-repository'
import { PostgresGroupRepository } from '~/common/groups/repositories/postgres-group-repository'
+import { HogTransformerComponent } from '~/common/hog-transformations/hog-transformer-component'
+import { IngestionOutputsComponent } from '~/common/outputs/ingestion-outputs'
import { PersonHogConfig, buildGroupRepository, buildPersonRepository, createPersonHogClient } from '~/common/personhog'
import { PostgresPersonRepository } from '~/common/persons/repositories/postgres-person-repository'
import { ServerCommands } from '~/common/utils/commands'
@@ -31,7 +33,8 @@ import {
getDefaultKafkaDownstreamProducerEnvConfig,
getDefaultKafkaUpstreamProducerEnvConfig,
} from '~/ingestion/common/producers'
-import { createAiEventSubpipeline } from '~/ingestion/pipelines/ai'
+import { createAiConsumer, createAiEventSubpipeline } from '~/ingestion/pipelines/ai'
+import { createOutputsRegistry as createAiOutputsRegistry } from '~/ingestion/pipelines/ai/outputs/registry'
import { createOutputsRegistry } from '~/ingestion/pipelines/analytics/outputs/registry'
import { createClientWarningsConsumer } from '~/ingestion/pipelines/clientwarnings'
import { createHeatmapsConsumer } from '~/ingestion/pipelines/heatmaps'
@@ -303,6 +306,39 @@ export class IngestionGeneralServer implements NodeServer {
})
}
+ const startAi = (override?: { topic: string; groupId: string }) => {
+ serviceLoaders.push(async () => {
+ const consumerConfig = override
+ ? {
+ ...this.config,
+ INGESTION_CONSUMER_CONSUME_TOPIC: override.topic,
+ INGESTION_CONSUMER_GROUP_ID: override.groupId,
+ }
+ : this.config
+ // The AI lane can't construct the cdp-owned hog transformer itself (boundary),
+ // so the server injects it (and the lane's outputs, which also back the
+ // transformer's monitoring) through an AI-specific scope. The consumer owns
+ // everything else (incl. its personhog client), taking only config + parent scope.
+ const aiOutputs = createAiOutputsRegistry().build(ingestionProducerRegistry, this.config)
+ const aiSharedScope = extend(sharedServicesScope, 'ai-shared', (_container, builder) =>
+ builder
+ .add(
+ 'hogTransformer',
+ new HogTransformerComponent(() =>
+ createHogTransformerService(this.config, {
+ ...hogTransformerDeps,
+ monitoringOutputs: aiOutputs,
+ })
+ )
+ )
+ .add('outputs', new IngestionOutputsComponent(() => aiOutputs))
+ )
+ const consumerScope = createAiConsumer(consumerConfig, aiSharedScope)
+ const { consumer, stop } = await consumerScope.start()
+ return ingestionConsumerService(consumer, stop)
+ })
+ }
+
if (isCombinedMode) {
// Local dev / hobby: run multiple consumers for all ingestion topics in one process
const consumersOptions = [
@@ -335,6 +371,12 @@ export class IngestionGeneralServer implements NodeServer {
startClientWarnings()
} else if (this.config.INGESTION_PIPELINE === 'heatmaps') {
startHeatmaps()
+ } else if (this.config.INGESTION_PIPELINE === 'ai') {
+ // Dedicated AI pipeline deployment. Not started in combined mode: the
+ // combined analytics consumers already process AI events on the shared
+ // topic, so running this in parallel there would double-process them.
+ // Switchover to this pipeline is driven by capture-side routing.
+ startAi()
} else {
// Production ingestion-v2: single consumer using config-provided topic
serviceLoaders.push(async () => {