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(error-tracking): run the consumer on the common ingestion consumer (#98945)

José Sequeira8b3ac4d4ddd7
diff --git a/nodejs/src/ingestion/pipelines/errortracking/consumer.test.ts b/nodejs/src/ingestion/pipelines/errortracking/consumer.test.ts
new file mode 100644
index 000000000000..475b30c93fce
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/errortracking/consumer.test.ts
@@ -0,0 +1,280 @@
+import { mockProducer, mockProducerObserver } from '~/tests/helpers/mocks/producer.mock'
+
+import { DateTime } from 'luxon'
+import { Message } from 'node-rdkafka'
+
+import { HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
+import { parseJSON } from '~/common/utils/json-parse'
+import { UUIDT } from '~/common/utils/utils'
+import { Component, newScope } from '~/ingestion/common/scopes'
+import { IngestionTestInfra, createIngestionTestInfra } from '~/tests/helpers/ingestion-e2e'
+import { createTestTeamFixture } from '~/tests/helpers/sql'
+import { PipelineEvent, Team } from '~/types'
+
+import { ErrorTrackingLaneConfig, createErrorTrackingConsumer } from './consumer'
+import { ErrorTrackingOutputs } from './error-tracking-pipeline'
+
+jest.setTimeout(60000)
+
+type BatchHandler = (messages: Message[]) => Promise<{ backgroundTask?: Promise<unknown> }>
+
+// The common consumer connects its own Kafka consumer; capture the batch handler it
+// registers so tests can drive batches without a broker.
+let mockBatchHandler: BatchHandler | undefined
+jest.mock('~/common/kafka/consumer', () => ({
+ ...jest.requireActual('~/common/kafka/consumer'),
+ createKafkaConsumer: jest.fn(() => ({
+ connect: jest.fn((handler: BatchHandler) => {
+ mockBatchHandler = handler
+ return Promise.resolve()
+ }),
+ disconnect: jest.fn().mockResolvedValue(undefined),
+ isHealthy: jest.fn().mockReturnValue({ status: 'ok' }),
+ })),
+}))
+
+// The lane owns its personhog client and reads persons/groups through it; there is no
+// personhog server in tests, so stand in for the client and the read repositories.
+jest.mock('~/common/personhog/personhog-client-component', () => ({
+ PersonHogClientComponent: jest.fn().mockImplementation(() => ({
+ start: () => Promise.resolve({ value: {}, stop: () => Promise.resolve() }),
+ })),
+}))
+jest.mock('~/common/personhog/personhog-person-read-repository', () => ({
+ PersonHogPersonReadRepository: jest.fn().mockImplementation(() => ({
+ fetchPerson: jest.fn().mockResolvedValue(undefined),
+ fetchPersonsByDistinctIds: jest.fn().mockResolvedValue([]),
+ fetchPersonsByPersonIds: jest.fn().mockResolvedValue([]),
+ fetchDistinctIdsForPersons: jest.fn().mockResolvedValue({}),
+ })),
+}))
+jest.mock('~/common/personhog/personhog-group-read-repository', () => ({
+ PersonHogGroupReadRepository: jest.fn().mockImplementation(() => ({
+ fetchGroupsByKeys: jest.fn().mockResolvedValue([]),
+ fetchGroupTypesByTeamIds: jest.fn().mockResolvedValue({}),
+ fetchGroupTypesByProjectIds: jest.fn().mockResolvedValue({}),
+ })),
+}))
+
+jest.mock('~/common/utils/posthog', () => {
+ const original = jest.requireActual('~/common/utils/posthog')
+ return {
+ ...original,
+ captureException: jest.fn(),
+ }
+})
+
+jest.mock('~/common/utils/token-bucket', () => {
+ const mockConsume = jest.fn().mockReturnValue(true)
+ return {
+ ...jest.requireActual('~/common/utils/token-bucket'),
+ IngestionWarningLimiter: {
+ consume: mockConsume,
+ },
+ }
+})
+
+jest.mock('~/common/utils/logger', () => ({
+ logger: {
+ debug: jest.fn(),
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ },
+}))
+
+jest.mock('./cymbal', () => ({
+ CymbalClient: jest.fn().mockImplementation(() => ({
+ processExceptions: jest.fn().mockImplementation((items) =>
+ items.map((item: any) => ({
+ uuid: item.request.uuid,
+ event: item.request.event,
+ team_id: item.request.team_id,
+ timestamp: item.request.timestamp,
+ properties: {
+ ...item.request.properties,
+ $exception_fingerprint: `fingerprint-${item.request.uuid}`,
+ $exception_issue_id: `issue-${item.request.uuid}`,
+ },
+ }))
+ ),
+ })),
+}))
+
+const createMockHogTransformer = (): jest.Mocked<HogTransformer> => ({
+ start: jest.fn().mockResolvedValue(undefined),
+ stop: jest.fn().mockResolvedValue(undefined),
+ transformEventAndProduceMessages: jest
+ .fn()
+ .mockImplementation((event) => Promise.resolve({ event, invocationResults: [] })),
+ processInvocationResults: jest.fn().mockResolvedValue(undefined),
+ prefetchHogFunctionsForTeams: jest.fn().mockResolvedValue(undefined),
+})
+
+const staticComponent = <T>(value: T): Component<T> => ({
+ start: () => Promise.resolve({ value, stop: () => Promise.resolve() }),
+})
+
+let offsetIncrementer = 0
+
+const createKafkaMessage = (event: PipelineEvent, token: string): Message => {
+ const captureEvent = {
+ uuid: event.uuid,
+ distinct_id: event.distinct_id,
+ ip: event.ip,
+ now: event.now,
+ token,
+ data: JSON.stringify(event),
+ }
+ return {
+ key: `${token}:${event.distinct_id}`,
+ value: Buffer.from(JSON.stringify(captureEvent)),
+ size: 1,
+ topic: 'error_tracking_events_test',
+ offset: offsetIncrementer++,
+ timestamp: DateTime.now().toMillis(),
+ partition: 1,
+ headers: [
+ { distinct_id: Buffer.from(event.distinct_id || '') },
+ { token: Buffer.from(token) },
+ { event: Buffer.from(event.event || '') },
+ { uuid: Buffer.from(event.uuid || '') },
+ { now: Buffer.from(event.now || '') },
+ ],
+ }
+}
+
+describe('createErrorTrackingConsumer', () => {
+ let infra: IngestionTestInfra
+ let team: Team
+ let fixedTime: DateTime
+ let mockHogTransformer: jest.Mocked<HogTransformer>
+ let stopConsumer: () => Promise<void>
+
+ const startConsumer = async (infra: IngestionTestInfra): Promise<void> => {
+ const config: ErrorTrackingLaneConfig = {
+ ...infra.config,
+ INGESTION_CONSUMER_GROUP_ID: infra.config.ERROR_TRACKING_CONSUMER_GROUP_ID,
+ INGESTION_CONSUMER_CONSUME_TOPIC: infra.config.ERROR_TRACKING_CONSUMER_CONSUME_TOPIC,
+ }
+ const outputs: ErrorTrackingOutputs = new IngestionOutputs({
+ events: new SingleIngestionOutput(
+ 'events',
+ infra.config.ERROR_TRACKING_CONSUMER_OUTPUT_TOPIC,
+ mockProducer,
+ 'test'
+ ),
+ ingestion_warnings: new SingleIngestionOutput(
+ 'ingestion_warnings',
+ 'clickhouse_ingestion_warnings_test',
+ mockProducer,
+ 'test'
+ ),
+ dlq: new SingleIngestionOutput('dlq', infra.config.ERROR_TRACKING_CONSUMER_DLQ_TOPIC, mockProducer, 'test'),
+ overflow: new SingleIngestionOutput(
+ 'overflow',
+ infra.config.ERROR_TRACKING_CONSUMER_OVERFLOW_TOPIC,
+ mockProducer,
+ 'test'
+ ),
+ tophog: new SingleIngestionOutput('tophog', 'clickhouse_tophog_test', mockProducer, 'test'),
+ app_metrics: new SingleIngestionOutput('app_metrics', 'clickhouse_app_metrics2_test', mockProducer, 'test'),
+ })
+ mockHogTransformer = createMockHogTransformer()
+
+ const sharedScope = newScope('shared-test', (builder) =>
+ builder
+ .add('redisPool', staticComponent(infra.redisPool))
+ .add('teamManager', staticComponent(infra.teamManager))
+ .add('cookielessManager', staticComponent(infra.cookielessManager))
+ .add('hogTransformer', staticComponent<HogTransformer>(mockHogTransformer))
+ .add('outputs', staticComponent(outputs))
+ )
+
+ const started = await createErrorTrackingConsumer(config, sharedScope).start()
+ stopConsumer = started.stop
+ }
+
+ const createEvent = (event?: Partial<PipelineEvent>): PipelineEvent => ({
+ distinct_id: 'user-1',
+ uuid: new UUIDT().toString(),
+ ip: '127.0.0.1',
+ site_url: 'us.posthog.com',
+ now: fixedTime.toISO()!,
+ event: '$exception',
+ ...event,
+ properties: {
+ $exception_list: [
+ {
+ type: 'Error',
+ value: 'Test error message',
+ mechanism: { type: 'generic', handled: true },
+ },
+ ],
+ ...(event?.properties || {}),
+ },
+ })
+
+ // A batch is fully processed once the returned background task (the
+ // scheduled side-effect flush) has settled, matching the consumer loop.
+ const handleBatch = async (messages: Message[]): Promise<void> => {
+ const result = await mockBatchHandler!(messages)
+ expect(result.backgroundTask).toBeDefined()
+ await result.backgroundTask
+ }
+
+ beforeEach(async () => {
+ fixedTime = DateTime.fromObject({ year: 2025, month: 1, day: 1 }, { zone: 'UTC' })
+ jest.spyOn(Date, 'now').mockReturnValue(fixedTime.toMillis())
+ jest.spyOn(Date.prototype, 'toISOString').mockReturnValue(fixedTime.toISO()!)
+
+ offsetIncrementer = 0
+ mockBatchHandler = undefined
+ infra = await createIngestionTestInfra()
+ team = (await createTestTeamFixture(infra.postgres)).team
+
+ await startConsumer(infra)
+ })
+
+ afterEach(async () => {
+ await stopConsumer()
+ await infra.close()
+ mockProducerObserver.resetKafkaProducer()
+ })
+
+ afterAll(() => {
+ jest.useRealTimers()
+ })
+
+ it('emits an exception event with Cymbal fields and drains the hog transformer once per batch', async () => {
+ await handleBatch([createKafkaMessage(createEvent(), team.api_token)])
+
+ const producedMessages = mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')
+ expect(producedMessages).toHaveLength(1)
+
+ const event = producedMessages[0].value
+ expect(event.event).toBe('$exception')
+ expect(event.team_id).toBe(team.id)
+ expect(event.distinct_id).toBe('user-1')
+ // Error tracking always uses full person_mode to preserve group properties
+ expect(event.person_mode).toBe('full')
+
+ const properties = parseJSON(event.properties as string)
+ expect(properties.$exception_fingerprint).toBeDefined()
+ expect(properties.$exception_issue_id).toBeDefined()
+
+ expect(mockHogTransformer.transformEventAndProduceMessages).toHaveBeenCalledTimes(1)
+ expect(mockHogTransformer.processInvocationResults).toHaveBeenCalledTimes(1)
+ })
+
+ it('drops events whose token resolves to no team', async () => {
+ await handleBatch([createKafkaMessage(createEvent(), 'invalid-token-that-does-not-exist')])
+
+ expect(mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')).toHaveLength(0)
+ expect(
+ mockProducerObserver.getProducedKafkaMessagesForTopic(infra.config.ERROR_TRACKING_CONSUMER_DLQ_TOPIC)
+ ).toHaveLength(0)
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/errortracking/consumer.ts b/nodejs/src/ingestion/pipelines/errortracking/consumer.ts
new file mode 100644
index 000000000000..e3fff0c2a2f0
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/errortracking/consumer.ts
@@ -0,0 +1,139 @@
+import { CommonConfig } from '~/common/config'
+import { ReadOnlyGroupTypeManager } from '~/common/groups/readonly-group-type-manager'
+import { HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'
+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 { UsageIngestionConfig, createEventUsageBatchFactory } from '~/common/usage-ingestion'
+import { EventIngestionRestrictionManagerComponent } from '~/common/utils/event-ingestion-restrictions'
+import { DEFAULT_LOADER_RETRY } from '~/common/utils/lazy-loader'
+import { TeamManager } from '~/common/utils/team-manager'
+import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
+import { CommonIngestionConsumerConfig, CommonIngestionConsumerScope } from '~/ingestion/common/ingestion-consumer'
+import { DisabledOverflowRedirectComponent } from '~/ingestion/common/overflow-redirect/disabled-overflow-redirect'
+import { MainLaneOverflowRedirectComponent } from '~/ingestion/common/overflow-redirect/main-lane-overflow-redirect'
+import { OverflowLaneOverflowRedirectComponent } from '~/ingestion/common/overflow-redirect/overflow-lane-overflow-redirect'
+import { RedisOverflowRepositoryComponent } from '~/ingestion/common/overflow-redirect/overflow-redis-repository'
+import { eventRateStrategy } from '~/ingestion/common/overflow-redirect/overflow-strategy'
+import { Scope, extend } from '~/ingestion/common/scopes'
+import { PromiseSchedulerComponent } from '~/ingestion/common/utils/promise-scheduler'
+import { RedisPool } from '~/types'
+
+import { ErrorTrackingConsumerConfig } from './config'
+import { CymbalClient } from './cymbal'
+import { ErrorTrackingOutputs, createErrorTrackingPipeline } from './error-tracking-pipeline'
+
+export type ErrorTrackingLaneConfig = CommonIngestionConsumerConfig &
+ PersonHogConfig &
+ UsageIngestionConfig &
+ Pick<
+ ErrorTrackingConsumerConfig,
+ | 'ERROR_TRACKING_CYMBAL_BASE_URL'
+ | 'ERROR_TRACKING_CYMBAL_TIMEOUT_MS'
+ | 'ERROR_TRACKING_CYMBAL_MAX_BODY_BYTES'
+ | 'ERROR_TRACKING_OVERFLOW_BUCKET_CAPACITY'
+ | 'ERROR_TRACKING_OVERFLOW_BUCKET_REPLENISH_RATE'
+ | 'ERROR_TRACKING_STATEFUL_OVERFLOW_REDIS_TTL_SECONDS'
+ | 'ERROR_TRACKING_STATEFUL_OVERFLOW_LOCAL_CACHE_TTL_SECONDS'
+ | 'ERROR_TRACKING_OVERFLOW_PRESERVE_PARTITION_LOCALITY'
+ | 'INGESTION_OVERFLOW_MODE'
+ > &
+ Pick<CommonConfig, 'PLUGIN_SERVER_MODE'>
+
+/**
+ * Services shared from the server scope. The server builds the hog transformer
+ * (cdp-owned, so the lane can't construct it) and the outputs, because the same
+ * outputs instance backs the transformer's monitoring. The personhog client is
+ * owned by the error tracking scope, not shared in here.
+ */
+export type ErrorTrackingSharedScope = Scope<{
+ redisPool: RedisPool
+ teamManager: TeamManager
+ cookielessManager: CookielessManager
+ hogTransformer: HogTransformer
+ outputs: ErrorTrackingOutputs
+}>
+
+export function createErrorTrackingConsumer(config: ErrorTrackingLaneConfig, sharedScope: ErrorTrackingSharedScope) {
+ const overflowMode = config.INGESTION_OVERFLOW_MODE
+ const preservePartitionLocality = config.ERROR_TRACKING_OVERFLOW_PRESERVE_PARTITION_LOCALITY
+ const clientLabel = config.PLUGIN_SERVER_MODE ?? 'unknown'
+
+ const overflowScope = extend(sharedScope, 'errortracking-overflow', (container, builder) =>
+ builder.add(
+ 'overflowRedisRepository',
+ new RedisOverflowRepositoryComponent(
+ container.redisPool,
+ config.ERROR_TRACKING_STATEFUL_OVERFLOW_REDIS_TTL_SECONDS
+ )
+ )
+ )
+
+ const scope = extend(overflowScope, 'errortracking', (container, builder) =>
+ builder
+ .add('promiseScheduler', new PromiseSchedulerComponent())
+ .add(
+ 'eventIngestionRestrictionManager',
+ new EventIngestionRestrictionManagerComponent(container.redisPool, { pipeline: 'errortracking' })
+ )
+ .add(
+ 'overflowRedirectService',
+ overflowMode === 'redirect'
+ ? new MainLaneOverflowRedirectComponent({
+ redisRepository: container.overflowRedisRepository,
+ localCacheTTLSeconds: config.ERROR_TRACKING_STATEFUL_OVERFLOW_LOCAL_CACHE_TTL_SECONDS,
+ strategies: [
+ {
+ ...eventRateStrategy(),
+ bucketCapacity: config.ERROR_TRACKING_OVERFLOW_BUCKET_CAPACITY,
+ replenishRate: config.ERROR_TRACKING_OVERFLOW_BUCKET_REPLENISH_RATE,
+ },
+ ],
+ overflowType: 'errortracking',
+ })
+ : new DisabledOverflowRedirectComponent()
+ )
+ .add(
+ 'overflowLaneTTLRefreshService',
+ overflowMode === 'consume'
+ ? new OverflowLaneOverflowRedirectComponent({
+ redisRepository: container.overflowRedisRepository,
+ overflowType: 'errortracking',
+ })
+ : new DisabledOverflowRedirectComponent()
+ )
+ .add('personhogClient', new PersonHogClientComponent(config))
+ )
+
+ const cymbalClient = new CymbalClient({
+ baseUrl: config.ERROR_TRACKING_CYMBAL_BASE_URL,
+ timeoutMs: config.ERROR_TRACKING_CYMBAL_TIMEOUT_MS,
+ maxBodyBytes: config.ERROR_TRACKING_CYMBAL_MAX_BODY_BYTES,
+ })
+ const createEventUsageBatch = createEventUsageBatchFactory(config, 'exceptions')
+
+ return new CommonIngestionConsumerScope('errortracking', config, scope, ({ container }) =>
+ createErrorTrackingPipeline({
+ outputs: container.outputs,
+ promiseScheduler: container.promiseScheduler,
+ teamManager: container.teamManager,
+ // Read-only person/group access — read through personhog, never written.
+ personRepository: new PersonHogPersonReadRepository(container.personhogClient, clientLabel),
+ hogTransformer: container.hogTransformer,
+ cymbalClient,
+ groupTypeManager: new ReadOnlyGroupTypeManager(
+ new PersonHogGroupReadRepository(container.personhogClient, clientLabel),
+ { loaderRetry: DEFAULT_LOADER_RETRY }
+ ),
+ cookielessManager: container.cookielessManager,
+ eventIngestionRestrictionManager: container.eventIngestionRestrictionManager,
+ overflowMode,
+ preservePartitionLocality,
+ overflowRedirectService: container.overflowRedirectService,
+ overflowLaneTTLRefreshService: container.overflowLaneTTLRefreshService,
+ topHog: container.topHog,
+ createEventUsageBatch,
+ })
+ )
+}
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts
deleted file mode 100644
index a77750d9e849..000000000000
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts
+++ /dev/null
@@ -1,426 +0,0 @@
-import { mockProducer, mockProducerObserver } from '~/tests/helpers/mocks/producer.mock'
-
-import { DateTime } from 'luxon'
-import { Message } from 'node-rdkafka'
-
-import { ReadOnlyGroupTypeManager } from '~/common/groups/readonly-group-type-manager'
-import { KafkaConsumer } from '~/common/kafka/consumer/consumer-v1'
-import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
-import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
-import { PersonReadRepository } from '~/common/persons/repositories/person-repository'
-import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'
-import { parseJSON } from '~/common/utils/json-parse'
-import { UUIDT } from '~/common/utils/utils'
-import { IngestionTestInfra, createIngestionTestInfra } from '~/tests/helpers/ingestion-e2e'
-import { createTestTeamFixture } from '~/tests/helpers/sql'
-import { PipelineEvent, Team } from '~/types'
-
-import { ErrorTrackingConsumer, ErrorTrackingHogTransformer } from './error-tracking-consumer'
-
-/** Creates a mock KafkaConsumer for tests that don't need actual Kafka connections */
-const createMockKafkaConsumer = (): jest.Mocked<Pick<KafkaConsumer, 'connect' | 'disconnect' | 'isHealthy'>> => ({
- connect: jest.fn().mockResolvedValue(undefined),
- disconnect: jest.fn().mockResolvedValue(undefined),
- isHealthy: jest.fn().mockReturnValue({ status: 'ok' }),
-})
-
-jest.setTimeout(60000)
-
-jest.mock('~/common/utils/posthog', () => {
- const original = jest.requireActual('~/common/utils/posthog')
- return {
- ...original,
- captureException: jest.fn(),
- }
-})
-
-// Mock the IngestionWarningLimiter to always allow warnings
-jest.mock('~/common/utils/token-bucket', () => {
- const mockConsume = jest.fn().mockReturnValue(true)
- return {
- ...jest.requireActual('~/common/utils/token-bucket'),
- IngestionWarningLimiter: {
- consume: mockConsume,
- },
- }
-})
-
-// Mock the logger to reduce noise
-jest.mock('~/common/utils/logger', () => ({
- logger: {
- debug: jest.fn(),
- info: jest.fn(),
- warn: jest.fn(),
- error: jest.fn(),
- },
-}))
-
-const createMockPersonRepository = (): jest.Mocked<PersonReadRepository> => ({
- fetchPerson: jest.fn().mockResolvedValue(undefined),
- fetchPersonsByDistinctIds: jest.fn().mockResolvedValue([]),
- fetchPersonsByPersonIds: jest.fn().mockResolvedValue([]),
- fetchDistinctIdsForPersons: jest.fn().mockResolvedValue({}),
-})
-
-// Mock the CymbalClient to avoid real HTTP calls
-// Cymbal receives event properties and returns them with fingerprint/issue_id added
-jest.mock('./cymbal', () => ({
- CymbalClient: jest.fn().mockImplementation(() => ({
- processExceptions: jest.fn().mockImplementation((items) =>
- items.map((item: any) => {
- const signature = (item.request.properties?.$exception_list ?? [])
- .flatMap((exc: any) => exc?.stacktrace?.frames ?? [])
- .map((frame: any) => frame?.function ?? '')
- .join('|')
- const issueKey = signature || item.request.uuid
- return {
- uuid: item.request.uuid,
- event: item.request.event,
- team_id: item.request.team_id,
- timestamp: item.request.timestamp,
- properties: {
- ...item.request.properties,
- $exception_fingerprint: `fingerprint-${issueKey}`,
- $exception_issue_id: `issue-${issueKey}`,
- },
- }
- })
- ),
- })),
-}))
-
-// Create a mock HogTransformerService that passes through events unchanged
-const createMockHogTransformer = (): jest.Mocked<ErrorTrackingHogTransformer> => ({
- start: jest.fn().mockResolvedValue(undefined),
- stop: jest.fn().mockResolvedValue(undefined),
- transformEventAndProduceMessages: jest
- .fn()
- .mockImplementation((event) => Promise.resolve({ event, invocationResults: [] })),
- processInvocationResults: jest.fn().mockResolvedValue(undefined),
-})
-
-let offsetIncrementer = 0
-
-const createKafkaMessage = (event: PipelineEvent, token: string): Message => {
- const captureEvent = {
- uuid: event.uuid,
- distinct_id: event.distinct_id,
- ip: event.ip,
- now: event.now,
- token,
- data: JSON.stringify(event),
- }
- return {
- key: `${token}:${event.distinct_id}`,
- value: Buffer.from(JSON.stringify(captureEvent)),
- size: 1,
- topic: 'error_tracking_events_test',
- offset: offsetIncrementer++,
- timestamp: DateTime.now().toMillis(),
- partition: 1,
- headers: [
- { distinct_id: Buffer.from(event.distinct_id || '') },
- { token: Buffer.from(token) },
- { event: Buffer.from(event.event || '') },
- { uuid: Buffer.from(event.uuid || '') },
- { now: Buffer.from(event.now || '') },
- ],
- }
-}
-
-describe('ErrorTrackingConsumer', () => {
- let consumer: ErrorTrackingConsumer
- let infra: IngestionTestInfra
- let team: Team
- let fixedTime: DateTime
- let mockHogTransformer: jest.Mocked<ErrorTrackingHogTransformer>
-
- const createConsumer = async (infra: IngestionTestInfra) => {
- const config = {
- groupId: infra.config.ERROR_TRACKING_CONSUMER_GROUP_ID,
- topic: infra.config.ERROR_TRACKING_CONSUMER_CONSUME_TOPIC,
- cymbalBaseUrl: infra.config.ERROR_TRACKING_CYMBAL_BASE_URL,
- cymbalTimeoutMs: infra.config.ERROR_TRACKING_CYMBAL_TIMEOUT_MS,
- cymbalMaxBodyBytes: infra.config.ERROR_TRACKING_CYMBAL_MAX_BODY_BYTES,
- lane: infra.config.INGESTION_LANE ?? ('main' as const),
- overflowMode: infra.config.INGESTION_OVERFLOW_MODE,
- overflowBucketCapacity: infra.config.ERROR_TRACKING_OVERFLOW_BUCKET_CAPACITY,
- overflowBucketReplenishRate: infra.config.ERROR_TRACKING_OVERFLOW_BUCKET_REPLENISH_RATE,
- statefulOverflowRedisTTLSeconds: infra.config.ERROR_TRACKING_STATEFUL_OVERFLOW_REDIS_TTL_SECONDS,
- statefulOverflowLocalCacheTTLSeconds: infra.config.ERROR_TRACKING_STATEFUL_OVERFLOW_LOCAL_CACHE_TTL_SECONDS,
- preservePartitionLocality: infra.config.ERROR_TRACKING_OVERFLOW_PRESERVE_PARTITION_LOCALITY,
- pipeline: infra.config.INGESTION_PIPELINE ?? 'errortracking',
- }
- // Create and store the mock so tests can configure it
- mockHogTransformer = createMockHogTransformer()
- const deps = {
- outputs: new IngestionOutputs({
- events: new SingleIngestionOutput(
- 'events',
- infra.config.ERROR_TRACKING_CONSUMER_OUTPUT_TOPIC,
- mockProducer,
- 'test'
- ),
- ingestion_warnings: new SingleIngestionOutput(
- 'ingestion_warnings',
- 'clickhouse_ingestion_warnings_test',
- mockProducer,
- 'test'
- ),
- dlq: new SingleIngestionOutput(
- 'dlq',
- infra.config.ERROR_TRACKING_CONSUMER_DLQ_TOPIC,
- mockProducer,
- 'test'
- ),
- overflow: new SingleIngestionOutput(
- 'overflow',
- infra.config.ERROR_TRACKING_CONSUMER_OVERFLOW_TOPIC || '',
- mockProducer,
- 'test'
- ),
- tophog: new SingleIngestionOutput('tophog', 'clickhouse_tophog_test', mockProducer, 'test'),
- app_metrics: new SingleIngestionOutput(
- 'app_metrics',
- 'clickhouse_app_metrics2_test',
- mockProducer,
- 'test'
- ),
- }),
- teamManager: infra.teamManager,
- hogTransformer: mockHogTransformer,
- groupTypeManager: new ReadOnlyGroupTypeManager({
- fetchGroupsByKeys: jest.fn().mockResolvedValue([]),
- fetchGroupTypesByTeamIds: jest.fn().mockResolvedValue({}),
- fetchGroupTypesByProjectIds: jest.fn().mockResolvedValue({}),
- }),
- cookielessManager: infra.cookielessManager,
- redisPool: infra.redisPool,
- personRepository: createMockPersonRepository(),
- createEventUsageBatch: () => new UsageRecordBatch(null, { unit: 'events', isTeamEnabled: () => false }),
- }
- const consumer = new ErrorTrackingConsumer(config, deps)
- // Replace Kafka consumer with mock to avoid actual connections
- consumer['kafkaConsumer'] = createMockKafkaConsumer() as unknown as KafkaConsumer
- await consumer.start()
- return consumer
- }
-
- const createEvent = (event?: Partial<PipelineEvent>): PipelineEvent => ({
- distinct_id: 'user-1',
- uuid: new UUIDT().toString(),
- ip: '127.0.0.1',
- site_url: 'us.posthog.com',
- now: fixedTime.toISO()!,
- event: '$exception',
- ...event,
- properties: {
- $exception_list: [
- {
- type: 'Error',
- value: 'Test error message',
- mechanism: { type: 'generic', handled: true },
- },
- ],
- ...(event?.properties || {}),
- },
- })
-
- const createKafkaMessages = (events: PipelineEvent[], token?: string): Message[] => {
- return events.map((event) => createKafkaMessage(event, token ?? team.api_token))
- }
-
- // A batch is fully processed once the returned background task (the
- // scheduled side-effect flush) has settled, matching the consumer loop.
- const handleBatch = async (messages: Message[]): Promise<void> => {
- const result = await consumer.handleKafkaBatch(messages)
- expect(result.backgroundTask).toBeDefined()
- await result.backgroundTask
- }
-
- beforeEach(async () => {
- fixedTime = DateTime.fromObject({ year: 2025, month: 1, day: 1 }, { zone: 'UTC' })
- jest.spyOn(Date, 'now').mockReturnValue(fixedTime.toMillis())
- jest.spyOn(Date.prototype, 'toISOString').mockReturnValue(fixedTime.toISO()!)
-
- offsetIncrementer = 0
- infra = await createIngestionTestInfra()
- team = (await createTestTeamFixture(infra.postgres)).team
-
- consumer = await createConsumer(infra)
- })
-
- afterEach(async () => {
- await consumer.stop()
- await infra.close()
- mockProducerObserver.resetKafkaProducer()
- })
-
- afterAll(() => {
- jest.useRealTimers()
- })
-
- describe('configuration', () => {
- it('should have correct config defaults', () => {
- expect(consumer['name']).toBe('error-tracking-consumer')
- expect(consumer['config'].groupId).toBe('ingestion-errortracking')
- expect(consumer['config'].topic).toBe('ingestion-errortracking-main_test')
- })
- })
-
- describe('event processing', () => {
- it('should process a basic exception event', async () => {
- const messages = createKafkaMessages([createEvent()])
- await handleBatch(messages)
-
- const producedMessages =
- mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')
- expect(producedMessages).toHaveLength(1)
-
- const event = producedMessages[0].value
- expect(event.event).toBe('$exception')
- expect(event.team_id).toBe(team.id)
- expect(event.distinct_id).toBe('user-1')
- })
-
- it('should process multiple exception events', async () => {
- const events = [
- createEvent({ distinct_id: 'user-1' }),
- createEvent({ distinct_id: 'user-2' }),
- createEvent({ distinct_id: 'user-3' }),
- ]
- const messages = createKafkaMessages(events)
- await handleBatch(messages)
-
- const producedMessages =
- mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')
- expect(producedMessages).toHaveLength(3)
-
- const distinctIds = producedMessages.map((m) => m.value.distinct_id).sort()
- expect(distinctIds).toEqual(['user-1', 'user-2', 'user-3'])
- })
-
- it('should include exception fingerprint and issue id from Cymbal', async () => {
- const messages = createKafkaMessages([createEvent()])
- await handleBatch(messages)
-
- const producedMessages =
- mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')
- expect(producedMessages).toHaveLength(1)
-
- const properties = parseJSON(producedMessages[0].value.properties as string)
- // Cymbal adds fingerprint and issue_id to processed events
- expect(properties.$exception_fingerprint).toBeDefined()
- expect(properties.$exception_issue_id).toBeDefined()
- })
-
- it('should preserve group properties', async () => {
- const messages = createKafkaMessages([
- createEvent({
- properties: {
- $exception_list: [{ type: 'Error', value: 'Test' }],
- $groups: {
- company: 'acme-corp',
- },
- },
- }),
- ])
- await handleBatch(messages)
-
- const producedMessages =
- mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')
- expect(producedMessages).toHaveLength(1)
-
- const properties = parseJSON(producedMessages[0].value.properties as string)
- // Group properties should be preserved (mapped to $group_0)
- expect(properties.$groups).toEqual({ company: 'acme-corp' })
- })
-
- it('should run Hog transformations on events', async () => {
- // Configure the mock to add GeoIP properties (simulating the GeoIP transformation)
- mockHogTransformer.transformEventAndProduceMessages.mockImplementation((event) =>
- Promise.resolve({
- event: {
- ...event,
- properties: {
- ...event.properties,
- $geoip_country_code: 'SE',
- $geoip_city_name: 'Linköping',
- },
- },
- invocationResults: [],
- })
- )
-
- const messages = createKafkaMessages([
- createEvent({
- ip: '89.160.20.129',
- }),
- ])
- await handleBatch(messages)
-
- const producedMessages =
- mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')
- expect(producedMessages).toHaveLength(1)
-
- // Verify Hog transformations were called and added GeoIP properties
- expect(mockHogTransformer.transformEventAndProduceMessages).toHaveBeenCalledTimes(1)
- const properties = parseJSON(producedMessages[0].value.properties as string)
- expect(properties.$geoip_country_code).toBe('SE')
- expect(properties.$geoip_city_name).toBe('Linköping')
- })
-
- it('should flush invocation results after batch processing', async () => {
- const messages = createKafkaMessages([createEvent()])
- await handleBatch(messages)
-
- expect(mockHogTransformer.processInvocationResults).toHaveBeenCalledTimes(1)
- })
-
- it('should flush invocation results even when batch processing fails', async () => {
- // Make the pipeline throw an error
- mockHogTransformer.transformEventAndProduceMessages.mockRejectedValueOnce(new Error('Test error'))
-
- const messages = createKafkaMessages([createEvent()])
- await expect(consumer.handleKafkaBatch(messages)).rejects.toThrow('Test error')
-
- // processInvocationResults should still be called via finally block
- expect(mockHogTransformer.processInvocationResults).toHaveBeenCalledTimes(1)
- })
- })
-
- describe('error handling', () => {
- it('should reject events with invalid token', async () => {
- const messages = createKafkaMessages([createEvent()], 'invalid-token-that-does-not-exist')
- await handleBatch(messages)
-
- // Event should not be produced to output topic (team not found = dropped)
- const producedMessages =
- mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')
- expect(producedMessages).toHaveLength(0)
-
- // Invalid token events are dropped (not DLQ'd) by the resolve team step
- // This is consistent with how the ingestion pipeline handles unknown tokens
- })
-
- it('should handle empty batch', async () => {
- await handleBatch([])
-
- const producedMessages = mockProducerObserver.getProducedKafkaMessages()
- expect(producedMessages).toHaveLength(0)
- })
- })
-
- describe('person properties', () => {
- it('should always use full person_mode', async () => {
- // Error tracking always uses full person_mode to preserve group properties
- const messages = createKafkaMessages([createEvent()])
- await handleBatch(messages)
-
- const producedMessages =
- mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')
- expect(producedMessages).toHaveLength(1)
- expect(producedMessages[0].value.person_mode).toBe('full')
- })
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts
deleted file mode 100644
index 2392e2c215f1..000000000000
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts
+++ /dev/null
@@ -1,300 +0,0 @@
-import { Pool as GenericPool } from 'generic-pool'
-import { Redis } from 'ioredis'
-import { Message } from 'node-rdkafka'
-import { Counter, Gauge } from 'prom-client'
-
-import { ReadOnlyGroupTypeManager } from '~/common/groups/readonly-group-type-manager'
-import { HogTransformationResult } from '~/common/hog-transformations/hog-transformer.interface'
-import { KafkaConsumerInterface, createKafkaConsumer } from '~/common/kafka/consumer'
-import { PersonReadRepository } from '~/common/persons/repositories/person-repository'
-import { instrumentFn } from '~/common/tracing/tracing-utils'
-import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'
-import {
- EventIngestionRestrictionManager,
- EventIngestionRestrictionManagerComponent,
-} from '~/common/utils/event-ingestion-restrictions'
-import { logger } from '~/common/utils/logger'
-import { PromiseScheduler } from '~/common/utils/promise-scheduler'
-import { TeamManager } from '~/common/utils/team-manager'
-import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
-import { MainLaneOverflowRedirect } from '~/ingestion/common/overflow-redirect/main-lane-overflow-redirect'
-import { OverflowLaneOverflowRedirect } from '~/ingestion/common/overflow-redirect/overflow-lane-overflow-redirect'
-import { OverflowRedirectService } from '~/ingestion/common/overflow-redirect/overflow-redirect-service'
-import { RedisOverflowRepository } from '~/ingestion/common/overflow-redirect/overflow-redis-repository'
-import { eventRateStrategy } from '~/ingestion/common/overflow-redirect/overflow-strategy'
-import { IngestionLane, IngestionOverflowMode } from '~/ingestion/config'
-import { TopHog } from '~/ingestion/framework/tophog'
-import { PluginEvent } from '~/plugin-scaffold'
-import { HealthCheckResult, PluginServerService } from '~/types'
-
-import { CymbalClient } from './cymbal'
-import {
- ErrorTrackingOutputs,
- ErrorTrackingPipeline,
- createErrorTrackingPipeline,
- runErrorTrackingPipeline,
-} from './error-tracking-pipeline'
-
-/**
- * Configuration values for ErrorTrackingConsumer.
- * These are plain values that configure behavior.
- */
-export interface ErrorTrackingConsumerOptions {
- groupId: string
- topic: string
- cymbalBaseUrl: string
- cymbalTimeoutMs: number
- cymbalMaxBodyBytes: number
- lane: IngestionLane
- overflowMode: IngestionOverflowMode
- overflowBucketCapacity: number
- overflowBucketReplenishRate: number
- statefulOverflowRedisTTLSeconds: number
- statefulOverflowLocalCacheTTLSeconds: number
- /**
- * When true (the default), overflow redirects keep the original partition
- * key. When false, the overflow producer emits with a null key so Kafka
- * spreads the load across the overflow topic's partitions. Applies to both
- * restriction-driven force-overflow and rate-limit-to-overflow.
- */
- preservePartitionLocality: boolean
- pipeline: string
-}
-
-/**
- * Interface for the HogTransformer methods used by the error tracking consumer.
- * This allows for easier mocking in tests without needing the full service implementation.
- */
-export interface ErrorTrackingHogTransformer {
- start(): Promise<void>
- stop(): Promise<void>
- transformEventAndProduceMessages(event: PluginEvent): Promise<HogTransformationResult>
- processInvocationResults(): Promise<void>
-}
-
-/**
- * Dependencies for ErrorTrackingConsumer.
- * These are services and clients that are injected.
- */
-export interface ErrorTrackingConsumerDeps {
- outputs: ErrorTrackingOutputs
- teamManager: TeamManager
- hogTransformer: ErrorTrackingHogTransformer
- groupTypeManager: ReadOnlyGroupTypeManager
- cookielessManager: CookielessManager
- redisPool: GenericPool<Redis>
- personRepository: PersonReadRepository
- createEventUsageBatch: () => UsageRecordBatch
-}
-
-// Batch processing status - useful for tracking failures (batch sizes already tracked by KafkaConsumer)
-const batchProcessedCounter = new Counter({
- name: 'error_tracking_batches_processed_total',
- help: 'Total batches processed by the error tracking consumer',
- labelNames: ['status'],
-})
-
-// Useful for consumer lag calculation
-const latestOffsetTimestampGauge = new Gauge({
- name: 'error_tracking_latest_processed_timestamp_ms',
- help: 'Timestamp of the latest offset that has been committed.',
- labelNames: ['topic', 'partition', 'groupId'],
- aggregator: 'max',
-})
-
-export class ErrorTrackingConsumer {
- protected name = 'error-tracking-consumer'
- protected kafkaConsumer: KafkaConsumerInterface
- protected pipeline!: ErrorTrackingPipeline
- protected cymbalClient: CymbalClient
- protected promiseScheduler: PromiseScheduler
- private eventIngestionRestrictionManagerComponent: EventIngestionRestrictionManagerComponent
- protected eventIngestionRestrictionManager!: EventIngestionRestrictionManager
- private stopEventIngestionRestrictionManager?: () => Promise<void>
- protected overflowRedirectService?: OverflowRedirectService
- protected overflowLaneTTLRefreshService?: OverflowRedirectService
- protected topHog?: TopHog
-
- constructor(
- private config: ErrorTrackingConsumerOptions,
- private deps: ErrorTrackingConsumerDeps
- ) {
- this.kafkaConsumer = createKafkaConsumer({
- groupId: config.groupId,
- topic: config.topic,
- })
-
- this.cymbalClient = new CymbalClient({
- baseUrl: config.cymbalBaseUrl,
- timeoutMs: config.cymbalTimeoutMs,
- maxBodyBytes: config.cymbalMaxBodyBytes,
- })
-
- this.promiseScheduler = new PromiseScheduler()
-
- this.eventIngestionRestrictionManagerComponent = new EventIngestionRestrictionManagerComponent(deps.redisPool, {
- pipeline: 'errortracking',
- })
-
- // Create shared Redis repository for overflow redirect services
- const overflowRedisRepository = new RedisOverflowRepository({
- redisPool: deps.redisPool,
- redisTTLSeconds: config.statefulOverflowRedisTTLSeconds,
- })
-
- // Create overflow redirect service for main lane (rate limiting)
- if (config.overflowMode === 'redirect') {
- this.overflowRedirectService = new MainLaneOverflowRedirect({
- redisRepository: overflowRedisRepository,
- localCacheTTLSeconds: config.statefulOverflowLocalCacheTTLSeconds,
- strategies: [
- {
- ...eventRateStrategy(),
- bucketCapacity: config.overflowBucketCapacity,
- replenishRate: config.overflowBucketReplenishRate,
- },
- ],
- overflowType: 'errortracking',
- })
- }
-
- // Create TTL refresh service for overflow lane
- if (config.overflowMode === 'consume') {
- this.overflowLaneTTLRefreshService = new OverflowLaneOverflowRedirect({
- redisRepository: overflowRedisRepository,
- overflowType: 'errortracking',
- })
- }
- }
-
- public get service(): PluginServerService {
- return {
- id: this.name,
- onShutdown: async () => await this.stop(),
- healthcheck: () => this.isHealthy(),
- }
- }
-
- public async start(): Promise<void> {
- logger.info('🚀', `${this.name} - starting`, {
- groupId: this.config.groupId,
- topic: this.config.topic,
- overflowMode: this.config.overflowMode,
- lane: this.config.lane,
- cymbalUrl: this.config.cymbalBaseUrl,
- })
-
- const started = await this.eventIngestionRestrictionManagerComponent.start()
- this.eventIngestionRestrictionManager = started.value
- this.stopEventIngestionRestrictionManager = started.stop
- // Initialize pipeline with dependencies
- await this.initializePipeline()
-
- await this.kafkaConsumer.connect(async (messages) => {
- return await instrumentFn('errorTrackingConsumer.handleEachBatch', async () => {
- return await this.handleKafkaBatch(messages)
- })
- })
-
- logger.info('✅', `${this.name} - started`)
- }
-
- private async initializePipeline(): Promise<void> {
- // Start the Hog transformer service
- await this.deps.hogTransformer.start()
-
- // Initialize TopHog for metrics
- this.topHog = new TopHog({
- outputs: this.deps.outputs,
- pipeline: this.config.pipeline,
- lane: this.config.lane,
- })
- this.topHog.start()
-
- this.pipeline = createErrorTrackingPipeline({
- outputs: this.deps.outputs,
- promiseScheduler: this.promiseScheduler,
- teamManager: this.deps.teamManager,
- personRepository: this.deps.personRepository,
- hogTransformer: this.deps.hogTransformer,
- cymbalClient: this.cymbalClient,
- groupTypeManager: this.deps.groupTypeManager,
- cookielessManager: this.deps.cookielessManager,
- eventIngestionRestrictionManager: this.eventIngestionRestrictionManager,
- overflowMode: this.config.overflowMode,
- preservePartitionLocality: this.config.preservePartitionLocality,
- overflowRedirectService: this.overflowRedirectService,
- overflowLaneTTLRefreshService: this.overflowLaneTTLRefreshService,
- topHog: this.topHog,
- createEventUsageBatch: this.deps.createEventUsageBatch,
- })
-
- logger.info('✅', `${this.name} - pipeline initialized`)
- }
-
- public async stop(): Promise<void> {
- logger.info('🔁', `${this.name} - stopping`)
-
- // Wait for any pending side effects
- await this.promiseScheduler.waitForAll()
-
- // Shutdown overflow services
- await this.overflowRedirectService?.shutdown()
- await this.overflowLaneTTLRefreshService?.shutdown()
-
- // Stop Hog transformer service
- await this.deps.hogTransformer.stop()
-
- // Stop TopHog metrics
- await this.topHog?.stop()
-
- await this.kafkaConsumer.disconnect()
-
- await this.stopEventIngestionRestrictionManager?.()
-
- logger.info('👍', `${this.name} - stopped`)
- }
-
- public isHealthy(): HealthCheckResult {
- return this.kafkaConsumer.isHealthy()
- }
-
- public async handleKafkaBatch(messages: Message[]): Promise<{ backgroundTask?: Promise<unknown> }> {
- // Update offset timestamps for lag metrics
- for (const message of messages) {
- if (message.timestamp) {
- latestOffsetTimestampGauge
- .labels({ partition: message.partition, topic: message.topic, groupId: this.config.groupId })
- .set(message.timestamp)
- }
- }
-
- try {
- await runErrorTrackingPipeline(this.pipeline, messages)
- batchProcessedCounter.inc({ status: 'success' })
- } catch (error) {
- batchProcessedCounter.inc({ status: 'error' })
- logger.error('❌', `${this.name} - batch processing failed`, {
- error: error instanceof Error ? error.message : String(error),
- size: messages.length,
- })
- // Flush scheduled work before the error propagates and crashes the loop
- await this.flushScheduledWork()
- throw error
- }
-
- // Flushing scheduled produces is the slow tail of a batch (broker acks),
- // so hand it to the consumer as a background task: the consumer fetches
- // and processes the next batch while this settles, and only stores this
- // batch's offsets once it has. CONSUMER_MAX_BACKGROUND_TASKS caps how
- // many batches may overlap this way.
- return {
- backgroundTask: instrumentFn('errorTrackingConsumer.awaitScheduledWork', () => this.flushScheduledWork()),
- }
- }
-
- private async flushScheduledWork(): Promise<void> {
- // Flush scheduled work and invocation results to prevent memory accumulation
- await Promise.all([this.promiseScheduler.waitForAll(), this.deps.hogTransformer.processInvocationResults()])
- }
-}
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts
index f11e4810684e..542c7b9b6edb 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts
@@ -16,6 +16,7 @@ import { UUIDT } from '~/common/utils/utils'
import { COOKIELESS_SENTINEL_VALUE, CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
import { OverflowRedirectService } from '~/ingestion/common/overflow-redirect/overflow-redirect-service'
import { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'
+import { createOkContext } from '~/ingestion/framework/helpers'
import { ok } from '~/ingestion/framework/results'
import { TopHog } from '~/ingestion/framework/tophog'
import { createTestTeam } from '~/tests/helpers/team'
@@ -23,13 +24,25 @@ import { InternalPerson } from '~/types'
import { CymbalClient } from './cymbal/client'
import { CymbalResponse } from './cymbal/types'
-import { ErrorTrackingHogTransformer } from './error-tracking-consumer'
import {
+ ErrorTrackingHogTransformer,
+ ErrorTrackingPipeline,
ErrorTrackingPipelineConfig,
createErrorTrackingPipeline,
- runErrorTrackingPipeline,
} from './error-tracking-pipeline'
+/** Drives a batch through the pipeline the way the common consumer's batch handler does. */
+async function runErrorTrackingPipeline(pipeline: ErrorTrackingPipeline, messages: Message[]): Promise<void> {
+ const batch = messages.map((message) => createOkContext({ message }, { message }))
+ const feedResult = await pipeline.feed(batch, {})
+ if (!feedResult.ok) {
+ throw new Error(`Pipeline rejected batch: ${feedResult.reason}`)
+ }
+ while ((await pipeline.next()) !== null) {
+ // Drain all results
+ }
+}
+
// Skip retry sleeps so tests run instantly
jest.mock('~/common/utils/utils', () => ({
...jest.requireActual('~/common/utils/utils'),
@@ -249,8 +262,6 @@ describe('ErrorTrackingPipeline', () => {
// HogTransformer mock that passes through events unchanged by default
mockHogTransformer = {
- start: jest.fn().mockResolvedValue(undefined),
- stop: jest.fn().mockResolvedValue(undefined),
transformEventAndProduceMessages: jest
.fn()
.mockImplementation((event) => Promise.resolve({ event, invocationResults: [] })),
@@ -368,8 +379,9 @@ describe('ErrorTrackingPipeline', () => {
const pipeline = createErrorTrackingPipeline(pipelineConfig)
await runErrorTrackingPipeline(pipeline, [message])
- // Verify Hog transformations were run
+ // Verify Hog transformations were run and their invocation results drained once per batch
expect(mockHogTransformer.transformEventAndProduceMessages).toHaveBeenCalledTimes(1)
+ expect(mockHogTransformer.processInvocationResults).toHaveBeenCalledTimes(1)
// Verify event was emitted to Kafka
const producedEvents = getProducedEvents()
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts
index 3c1565db4a8a..d5335bc11b26 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts
@@ -1,6 +1,7 @@
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,
@@ -28,6 +29,7 @@ import {
import { createCreateEventStep } from '~/ingestion/common/steps/event-processing/create-event-step'
import { EmitEventStepOutput, createEmitEventStep } from '~/ingestion/common/steps/event-processing/emit-event-step'
import { createFetchPersonChunkStep } from '~/ingestion/common/steps/event-processing/fetch-person-chunk-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 { createReadOnlyProcessGroupsStep } from '~/ingestion/common/steps/event-processing/readonly-process-groups-step'
import { createRecordIngestionLagStep } from '~/ingestion/common/steps/record-ingestion-lag'
@@ -42,14 +44,18 @@ import { resolveExceptionUsageKey } from '~/ingestion/common/usage-records/billa
import { IngestionOverflowMode } from '~/ingestion/config'
import { BatchingContext, BatchingPipeline } from '~/ingestion/framework/batching-pipeline'
import { TopHogRegistry, count } from '~/ingestion/framework/extensions/tophog'
-import { createBatch } from '~/ingestion/framework/helpers'
import { createAttachMessageBytesStep } from './attach-message-bytes-step'
import { createCymbalProcessingStep } from './cymbal-processing-step'
import { CymbalClient } from './cymbal/client'
-import { ErrorTrackingHogTransformer } from './error-tracking-consumer'
import { createErrorTrackingPrepareEventStep } from './prepare-event-step'
+/** The hog transformer methods the pipeline uses; lifecycle stays with the owning scope. */
+export type ErrorTrackingHogTransformer = Pick<
+ HogTransformer,
+ 'transformEventAndProduceMessages' | 'processInvocationResults'
+>
+
export interface ErrorTrackingPipelineInput {
message: Message
}
@@ -79,7 +85,7 @@ export interface ErrorTrackingPipelineConfig {
promiseScheduler: PromiseScheduler
teamManager: TeamManager
personRepository: PersonReadRepository
- hogTransformer: ErrorTrackingHogTransformer | null
+ hogTransformer: ErrorTrackingHogTransformer
cymbalClient: CymbalClient
groupTypeManager: ReadOnlyGroupTypeManager
cookielessManager: CookielessManager
@@ -225,35 +231,12 @@ export function createErrorTrackingPipeline(config: ErrorTrackingPipelineConfig)
})
.pipe(createRecordEventUsageAfterIngestStep())
.pipe(createRecordIngestionLagStep())
- .afterBatch((b) => b.pipe(createFlushEventUsageStep()))
+ .afterBatch((b) =>
+ b
+ .pipe(createFlushEventUsageStep())
+ // Drain hog transformer invocation results once per batch.
+ .pipe(createFlushHogTransformerStep(hogTransformer))
+ )
.build()
)
}
-
-/**
- * Runs a batch of messages through the error tracking pipeline.
- *
- * Events are emitted to the output topic as a side effect. Failures are
- * handled by the result handling pipeline (DLQ, drop, redirect).
- *
- * All side effects — element results and batch hooks alike — are handled
- * inside the pipeline (scheduled on the promise scheduler, which the consumer
- * drains before committing offsets), so this driver only drains results.
- */
-export async function runErrorTrackingPipeline(pipeline: ErrorTrackingPipeline, messages: Message[]): Promise<void> {
- if (messages.length === 0) {
- return
- }
-
- const batch = createBatch(messages.map((message) => ({ message })))
- // The consumer drains each batch fully before feeding the next and the hooks
- // always succeed, so a rejected feed can only be a framework invariant violation.
- const feedResult = await pipeline.feed(batch, {})
- if (!feedResult.ok) {
- throw new Error(`error tracking pipeline rejected feed: ${feedResult.kind} (${feedResult.reason})`)
- }
-
- while ((await pipeline.next()) !== null) {
- // Drain all results
- }
-}
diff --git a/nodejs/src/ingestion/pipelines/errortracking/index.ts b/nodejs/src/ingestion/pipelines/errortracking/index.ts
index 97be86052144..87adea87170e 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/index.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/index.ts
@@ -1,15 +1,11 @@
// Error tracking ingestion pipeline exports
// This module processes $exception events from the error tracking ingestion topic
-export {
- ErrorTrackingConsumer,
- type ErrorTrackingConsumerOptions,
- type ErrorTrackingConsumerDeps,
- type ErrorTrackingHogTransformer,
-} from './error-tracking-consumer'
+export { createErrorTrackingConsumer, type ErrorTrackingLaneConfig, type ErrorTrackingSharedScope } from './consumer'
export { CymbalClient, type CymbalClientConfig } from './cymbal'
-export { createErrorTrackingPipeline, runErrorTrackingPipeline } from './error-tracking-pipeline'
+export { createErrorTrackingPipeline } from './error-tracking-pipeline'
export type {
+ ErrorTrackingHogTransformer,
ErrorTrackingPipelineConfig,
ErrorTrackingPipelineInput,
ErrorTrackingPipelineOutput,
diff --git a/nodejs/src/servers/error-tracking-server.ts b/nodejs/src/servers/error-tracking-server.ts
index 83a1f6574c90..a5213e727a82 100644
--- a/nodejs/src/servers/error-tracking-server.ts
+++ b/nodejs/src/servers/error-tracking-server.ts
@@ -5,36 +5,35 @@ import {
createCookielessRedisConnectionConfig,
createIngestionRedisConnectionConfig,
} from '~/common/config/redis-pools'
-import { ReadOnlyGroupTypeManager } from '~/common/groups/readonly-group-type-manager'
-import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'
-import { PersonHogConfig, createPersonHogClient } from '~/common/personhog'
-import { PersonHogGroupReadRepository } from '~/common/personhog/personhog-group-read-repository'
-import { PersonHogPersonReadRepository } from '~/common/personhog/personhog-person-read-repository'
-import { UsageIngestionConfig, createEventUsageBatchFactory } from '~/common/usage-ingestion'
+import { HogTransformerComponent } from '~/common/hog-transformations/hog-transformer-component'
+import { IngestionOutputsComponent } from '~/common/outputs/ingestion-outputs'
+import { PersonHogConfig } from '~/common/personhog'
+import { UsageIngestionConfig } from '~/common/usage-ingestion'
import { ServerCommands } from '~/common/utils/commands'
-import { PostgresRouter } from '~/common/utils/db/postgres'
-import { createRedisPoolFromConfig } from '~/common/utils/db/redis'
+import { PostgresRouter, PostgresRouterComponent } from '~/common/utils/db/postgres'
+import { RedisPoolComponent } from '~/common/utils/db/redis'
import { GeoIPService } from '~/common/utils/geoip'
import { DEFAULT_LOADER_RETRY } from '~/common/utils/lazy-loader'
import { logger } from '~/common/utils/logger'
import { PubSub } from '~/common/utils/pubsub'
-import { TeamManager } from '~/common/utils/team-manager'
-import { CookielessManager, CookielessServerConfig } from '~/ingestion/common/cookieless/cookieless-manager'
-import { createIngestionProducerRegistry } from '~/ingestion/common/outputs/producer-registry'
+import { TeamManagerComponent } from '~/common/utils/team-manager'
+import { CookielessManagerComponent, CookielessServerConfig } from '~/ingestion/common/cookieless/cookieless-manager'
+import { ingestionConsumerService } from '~/ingestion/common/ingestion-consumer'
+import { KafkaProducerRegistryComponent } from '~/ingestion/common/outputs/producer-registry'
import {
KafkaDownstreamProducerEnvConfig,
KafkaUpstreamProducerEnvConfig,
- ProducerName,
getDefaultKafkaDownstreamProducerEnvConfig,
getDefaultKafkaUpstreamProducerEnvConfig,
} from '~/ingestion/common/outputs/producers'
+import { extend, newScope } from '~/ingestion/common/scopes'
import {
ErrorTrackingConsumerConfig,
ErrorTrackingOutputsConfig,
getDefaultErrorTrackingConsumerConfig,
getDefaultErrorTrackingOutputsConfig,
} from '~/ingestion/pipelines/errortracking/config'
-import { ErrorTrackingConsumer } from '~/ingestion/pipelines/errortracking/error-tracking-consumer'
+import { createErrorTrackingConsumer } from '~/ingestion/pipelines/errortracking/consumer'
import { createOutputsRegistry } from '~/ingestion/pipelines/errortracking/outputs/registry'
import {
@@ -46,6 +45,7 @@ import { EncryptedFields } from '../cdp/utils/encryption-utils'
import { CommonConfig } from '../common/config'
import {
DatabaseConnectionConfig,
+ IngestionConsumerConfig,
KafkaBrokerConfig,
KafkaConsumerBaseConfig,
RedisConnectionsConfig,
@@ -79,6 +79,7 @@ export type ErrorTrackingServerConfig = BaseServerConfig &
PersonHogConfig &
UsageIngestionConfig &
CookielessServerConfig &
+ Pick<IngestionConsumerConfig, 'KAFKA_BATCH_START_LOGGING_ENABLED'> &
Pick<
CommonConfig,
| 'LOG_LEVEL'
@@ -96,11 +97,9 @@ export class ErrorTrackingServer implements NodeServer {
private config: ErrorTrackingServerConfig
private postgres?: PostgresRouter
- private producerRegistry?: KafkaProducerRegistry<ProducerName>
private redisPool?: RedisPool
- private cookielessRedisPool?: RedisPool
- private cookielessManager?: CookielessManager
private pubsub?: PubSub
+ private stopSharedServices?: () => Promise<void>
constructor(config: Partial<ErrorTrackingServerConfig> = {}) {
this.config = {
@@ -132,58 +131,67 @@ export class ErrorTrackingServer implements NodeServer {
this.config.INGESTION_LANE ?? 'main'
)
- // 1. Shared infrastructure
+ // 1. Shared infrastructure — postgres, redis pools and the producer registry are
+ // owned by a server-level Scope so the consumer can extend off it to get them
+ // as handles without taking ownership.
logger.info('ℹ️', 'Connecting to shared infrastructure...')
- this.postgres = new PostgresRouter(this.config)
- logger.info('👍', 'Postgres Router ready')
+ const sharedInfraScope = newScope('shared-infra', (builder) =>
+ builder
+ .add('postgres', new PostgresRouterComponent(this.config, this.config.PLUGIN_SERVER_MODE!))
+ .add(
+ 'redisPool',
+ new RedisPoolComponent({
+ connection: createIngestionRedisConnectionConfig(this.config),
+ poolMinSize: this.config.REDIS_POOL_MIN_SIZE,
+ poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,
+ })
+ )
+ .add(
+ 'cookielessRedisPool',
+ new RedisPoolComponent({
+ connection: createCookielessRedisConnectionConfig(this.config),
+ poolMinSize: this.config.REDIS_POOL_MIN_SIZE,
+ poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,
+ })
+ )
+ .add('producerRegistry', new KafkaProducerRegistryComponent(this.config.KAFKA_CLIENT_RACK, this.config))
+ )
- logger.info('🤔', 'Connecting to Kafka...')
- this.producerRegistry = await createIngestionProducerRegistry(this.config.KAFKA_CLIENT_RACK).build(this.config)
- const outputs = createOutputsRegistry().build(this.producerRegistry, this.config)
- logger.info('👍', 'Kafka ready')
+ const sharedServicesScope = extend(sharedInfraScope, 'shared', (container, builder) =>
+ builder
+ .add(
+ 'teamManager',
+ // Retry transient team-load failures (e.g. a Postgres pooler scale-down returning
+ // ECONNREFUSED). The team loader runs detached in the LazyLoader buffer, so an un-retried
+ // transient failure can surface as an unhandled rejection and restart the worker.
+ new TeamManagerComponent(container.postgres, { loaderRetry: DEFAULT_LOADER_RETRY })
+ )
+ .add('cookielessManager', new CookielessManagerComponent(this.config, container.cookielessRedisPool))
+ )
- logger.info('🤔', 'Connecting to ingestion Redis...')
- this.redisPool = createRedisPoolFromConfig({
- connection: createIngestionRedisConnectionConfig(this.config),
- poolMinSize: this.config.REDIS_POOL_MIN_SIZE,
- poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,
- })
+ const sharedServices = await sharedServicesScope.start()
+ this.postgres = sharedServices.container.postgres
+ this.redisPool = sharedServices.container.redisPool
+ this.stopSharedServices = sharedServices.stop
+ logger.info('👍', 'Postgres Router ready')
+ logger.info('👍', 'Kafka ready')
logger.info('👍', 'Ingestion Redis ready')
-
- logger.info('🤔', 'Connecting to cookieless Redis...')
- this.cookielessRedisPool = createRedisPoolFromConfig({
- connection: createCookielessRedisConnectionConfig(this.config),
- poolMinSize: this.config.REDIS_POOL_MIN_SIZE,
- poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,
- })
logger.info('👍', 'Cookieless Redis ready')
- this.cookielessManager = new CookielessManager(this.config, this.cookielessRedisPool)
-
this.pubsub = new PubSub(this.redisPool)
await this.pubsub.start()
- const teamManager = new TeamManager(this.postgres, { loaderRetry: DEFAULT_LOADER_RETRY })
-
- // 2. Services needed by ErrorTrackingConsumer and HogTransformer
const geoipService = new GeoIPService(this.config.MMDB_FILE_LOCATION)
await geoipService.get()
- const personhogClient = createPersonHogClient(this.config)
- const clientLabel = this.config.PLUGIN_SERVER_MODE ?? 'unknown'
-
- if (!personhogClient) {
- throw new Error(
- 'PersonHog client is required for error tracking — set PERSONHOG_ENABLED=true and PERSONHOG_ADDR'
- )
- }
-
- const personRepository = new PersonHogPersonReadRepository(personhogClient, clientLabel)
- const groupRepository = new PersonHogGroupReadRepository(personhogClient, clientLabel)
const encryptedFields = new EncryptedFields(this.config.ENCRYPTION_SALT_KEYS)
const integrationManager = new IntegrationManagerService(this.pubsub, this.postgres, encryptedFields)
+ // The same outputs instance backs the pipeline's emissions and the hog
+ // transformer's monitoring (app_metrics + log_entries).
+ const outputs = createOutputsRegistry().build(sharedServices.container.producerRegistry, this.config)
+
const hogTransformerDeps: HogTransformerServiceDeps = {
geoipService,
postgres: this.postgres,
@@ -193,44 +201,28 @@ export class ErrorTrackingServer implements NodeServer {
monitoringOutputs: outputs,
}
- // 3. Error tracking consumer
- const serviceLoaders: (() => Promise<PluginServerService>)[] = []
+ const errorTrackingSharedScope = extend(sharedServicesScope, 'errortracking-shared', (_container, builder) =>
+ builder
+ .add(
+ 'hogTransformer',
+ new HogTransformerComponent(() => createHogTransformerService(this.config, hogTransformerDeps))
+ )
+ .add('outputs', new IngestionOutputsComponent(() => outputs))
+ )
- const createEventUsageBatch = createEventUsageBatchFactory(this.config, 'exceptions')
+ const serviceLoaders: (() => Promise<PluginServerService>)[] = []
serviceLoaders.push(async () => {
- const consumer = new ErrorTrackingConsumer(
+ const consumerScope = createErrorTrackingConsumer(
{
- groupId: this.config.ERROR_TRACKING_CONSUMER_GROUP_ID,
- topic: this.config.ERROR_TRACKING_CONSUMER_CONSUME_TOPIC,
- cymbalBaseUrl: this.config.ERROR_TRACKING_CYMBAL_BASE_URL,
- cymbalTimeoutMs: this.config.ERROR_TRACKING_CYMBAL_TIMEOUT_MS,
- cymbalMaxBodyBytes: this.config.ERROR_TRACKING_CYMBAL_MAX_BODY_BYTES,
- lane: this.config.INGESTION_LANE ?? 'main',
- overflowMode: this.config.INGESTION_OVERFLOW_MODE,
- overflowBucketCapacity: this.config.ERROR_TRACKING_OVERFLOW_BUCKET_CAPACITY,
- overflowBucketReplenishRate: this.config.ERROR_TRACKING_OVERFLOW_BUCKET_REPLENISH_RATE,
- statefulOverflowRedisTTLSeconds: this.config.ERROR_TRACKING_STATEFUL_OVERFLOW_REDIS_TTL_SECONDS,
- statefulOverflowLocalCacheTTLSeconds:
- this.config.ERROR_TRACKING_STATEFUL_OVERFLOW_LOCAL_CACHE_TTL_SECONDS,
- preservePartitionLocality: this.config.ERROR_TRACKING_OVERFLOW_PRESERVE_PARTITION_LOCALITY,
- pipeline: this.config.INGESTION_PIPELINE ?? 'errortracking',
+ ...this.config,
+ INGESTION_CONSUMER_GROUP_ID: this.config.ERROR_TRACKING_CONSUMER_GROUP_ID,
+ INGESTION_CONSUMER_CONSUME_TOPIC: this.config.ERROR_TRACKING_CONSUMER_CONSUME_TOPIC,
},
- {
- outputs,
- teamManager,
- hogTransformer: createHogTransformerService(this.config, hogTransformerDeps),
- groupTypeManager: new ReadOnlyGroupTypeManager(groupRepository, {
- loaderRetry: DEFAULT_LOADER_RETRY,
- }),
- cookielessManager: this.cookielessManager!,
- redisPool: this.redisPool!,
- personRepository,
- createEventUsageBatch,
- }
+ errorTrackingSharedScope
)
- await consumer.start()
- return consumer.service
+ const { consumer, stop } = await consumerScope.start()
+ return ingestionConsumerService(consumer, stop)
})
serviceLoaders.push(() => {
@@ -246,12 +238,12 @@ export class ErrorTrackingServer implements NodeServer {
private getCleanupResources(): CleanupResources {
return {
kafkaProducers: [],
- redisPools: [this.redisPool, this.cookielessRedisPool].filter(Boolean) as RedisPool[],
- postgres: this.postgres,
+ redisPools: [],
pubsub: this.pubsub,
additionalCleanup: async () => {
- await this.producerRegistry?.disconnectAll()
- this.cookielessManager?.shutdown()
+ if (this.stopSharedServices) {
+ await this.stopSharedServices()
+ }
},
}
}