:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ingestion): break heatmaps out into a dedicated consumer (#62199)
Paweł Ledwoń92b4a2f8bc80
diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 3d20a3bb145c..4be7f1497f68 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -492,6 +492,7 @@ services:events_plugin_ingestion_overflow \events_plugin_ingestion_async \ingestion-clientwarnings-main-1 \+ heatmaps_ingestion \clickhouse_groups \clickhouse_person \clickhouse_person_distinct_id \diff --git a/docker-compose.hobby.yml b/docker-compose.hobby.ymlindex 622c62594eda..e774221ffde0 100644--- a/docker-compose.hobby.yml+++ b/docker-compose.hobby.yml@@ -535,6 +535,7 @@ services:events_plugin_ingestion_overflow \events_plugin_ingestion_async \ingestion-clientwarnings-main-1 \+ heatmaps_ingestion \clickhouse_groups \clickhouse_person \clickhouse_person_distinct_id \diff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.tsindex fb36e1ec02bf..a0cca199afec 100644--- a/nodejs/src/capabilities.ts+++ b/nodejs/src/capabilities.ts@@ -186,7 +186,6 @@ export function getPluginServerCapabilities(cdpRerunWorker: true,}case PluginServerMode.ingestion_v2:- case PluginServerMode.ingestion_v2_testing:case PluginServerMode.ingestion_v2_combined:throw new Error(`Mode ${mode} is handled by IngestionGeneralServer, not PluginServer`)case PluginServerMode.ingestion_api:diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.tsindex 5cc9e26ff1c2..de571ad6c278 100644--- a/nodejs/src/common/config.ts+++ b/nodejs/src/common/config.ts@@ -38,7 +38,6 @@ export enum PluginServerMode {cdp_cyclotron_v2_janitor = 'cdp-cyclotron-v2-janitor',cdp_rerun_worker = 'cdp-rerun-worker',recording_api = 'recording-api',- ingestion_v2_testing = 'ingestion-v2-testing',ingestion_v2_combined = 'ingestion-v2-combined',ingestion_traces = 'ingestion-traces',cdp_hogflow_scheduler = 'cdp-hogflow-scheduler',diff --git a/nodejs/src/index.ts b/nodejs/src/index.tsindex f561d7b9cec5..d92a31d92dea 100644--- a/nodejs/src/index.ts+++ b/nodejs/src/index.ts@@ -17,7 +17,6 @@ import { initSuperProperties } from '~/utils/posthog'function createServer(): NodeServer {switch (defaultConfig.PLUGIN_SERVER_MODE) {case PluginServerMode.ingestion_v2:- case PluginServerMode.ingestion_v2_testing:case PluginServerMode.ingestion_v2_combined:return new IngestionGeneralServer()diff --git a/nodejs/src/ingestion/__snapshots__/ingestion-testing-consumer.test.ts.snap b/nodejs/src/ingestion/__snapshots__/ingestion-testing-consumer.test.ts.snapdeleted file mode 100644index 626198d2d883..000000000000--- a/nodejs/src/ingestion/__snapshots__/ingestion-testing-consumer.test.ts.snap+++ /dev/null@@ -1,29 +0,0 @@-// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing--exports[`IngestionTestingConsumer general should process a standard event 1`] = `-[- {- "headers": {- "productTrack": "general",- },- "key": "<REPLACED-UUID-0>",- "topic": "clickhouse_events_json_test",- "value": {- "captured_at": "2025-01-01 00:00:00.000",- "created_at": "2025-01-01 00:00:00.000",- "distinct_id": "user-1",- "elements_chain": "",- "event": "$pageview",- "person_created_at": "1970-01-01 00:00:05",- "person_id": "<REPLACED-UUID-1>",- "person_mode": "propertyless",- "person_properties": "{}",- "project_id": 2,- "properties": "{"$current_url":"http://localhost:8000","$ip":"127.0.0.1","$process_person_profile":false}",- "team_id": 2,- "timestamp": "2025-01-01 00:00:00.000",- "uuid": "<REPLACED-UUID-0>",- },- },-]-`;diff --git a/nodejs/src/ingestion/analytics/heatmap-subpipeline.ts b/nodejs/src/ingestion/analytics/heatmap-subpipeline.tsdeleted file mode 100644index 209e908ddfa7..000000000000--- a/nodejs/src/ingestion/analytics/heatmap-subpipeline.ts+++ /dev/null@@ -1,47 +0,0 @@-import { PluginEvent } from '~/plugin-scaffold'--import { EventHeaders, Team } from '../../types'-import { TeamManager } from '../../utils/team-manager'-import { GroupTypeManager } from '../../worker/ingestion/group-type-manager'-import { GroupStoreForBatch } from '../../worker/ingestion/groups/group-store-for-batch'-import { createCheckHeatmapOptInStep } from '../event-processing/check-heatmap-opt-in-step'-import { createDisablePersonProcessingStep } from '../event-processing/disable-person-processing-step'-import { EventPipelineRunnerOptions } from '../event-processing/event-pipeline-options'-import { createExtractHeatmapDataStep } from '../event-processing/extract-heatmap-data-step'-import { createNormalizeEventStep } from '../event-processing/normalize-event-step'-import { createPrepareEventStep } from '../event-processing/prepare-event-step'-import { createProcessGroupsStep } from '../event-processing/process-groups-step'-import { createSkipEmitEventStep } from '../event-processing/skip-emit-event-step'-import { IngestionOutputs } from '../outputs/ingestion-outputs'-import { PipelineBuilder, StartPipelineBuilder } from '../pipelines/builders/pipeline-builders'-import { HeatmapsOutput } from './outputs'--export interface HeatmapSubpipelineInput {- event: PluginEvent- team: Team- headers: EventHeaders- groupStoreForBatch: GroupStoreForBatch-}--export interface HeatmapSubpipelineConfig {- options: EventPipelineRunnerOptions- outputs: IngestionOutputs<HeatmapsOutput>- teamManager: TeamManager- groupTypeManager: GroupTypeManager-}--export function createHeatmapSubpipeline<TInput extends HeatmapSubpipelineInput, TContext>(- builder: StartPipelineBuilder<TInput, TContext>,- config: HeatmapSubpipelineConfig-): PipelineBuilder<TInput, void, TContext> {- const { options, outputs, teamManager, groupTypeManager } = config-- return builder- .pipe(createCheckHeatmapOptInStep())- .pipe(createDisablePersonProcessingStep())- .pipe(createNormalizeEventStep())- .pipe(createPrepareEventStep())- .pipe(createProcessGroupsStep(teamManager, groupTypeManager, options))- .pipe(createExtractHeatmapDataStep(outputs))- .pipe(createSkipEmitEventStep())-}diff --git a/nodejs/src/ingestion/analytics/index.ts b/nodejs/src/ingestion/analytics/index.tsindex 47137d2f61ef..abca0bc59023 100644--- a/nodejs/src/ingestion/analytics/index.ts+++ b/nodejs/src/ingestion/analytics/index.ts@@ -1,11 +1,5 @@export { createEventSubpipeline, type EventSubpipelineConfig, type EventSubpipelineInput } from './event-subpipeline'-export {- createHeatmapSubpipeline,- type HeatmapSubpipelineConfig,- type HeatmapSubpipelineInput,-} from './heatmap-subpipeline'-export {createPerDistinctIdPipeline,type PerDistinctIdPipelineConfig,@@ -26,11 +20,3 @@ export {type JoinedIngestionPipelineDeps,type JoinedIngestionPipelineInput,} from './joined-ingestion-pipeline'--export {- createTestingJoinedIngestionPipeline,- type TestingJoinedIngestionPipelineConfig,- type TestingJoinedIngestionPipelineContext,- type TestingJoinedIngestionPipelineDeps,- type TestingJoinedIngestionPipelineInput,-} from './testing-joined-ingestion-pipeline'diff --git a/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.tsindex b6a0bf8c5dda..b6303fe6cc81 100644--- a/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts+++ b/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts@@ -39,14 +39,7 @@ import { TopHogRegistry, createTopHogWrapper } from '../pipelines/extensions/topimport { OkResultWithContext } from '../pipelines/pipeline.interface'import { PipelineConfig } from '../pipelines/result-handling-pipeline'import { OverflowRedirectService } from '../utils/overflow-redirect/overflow-redirect-service'-import {- AiEventOutput,- AsyncOutput,- EventOutput,- HeatmapsOutput,- PersonDistinctIdsOutput,- PersonsOutput,-} from './outputs'+import { AiEventOutput, AsyncOutput, EventOutput, PersonDistinctIdsOutput, PersonsOutput } from './outputs'import {PerDistinctIdPipelineConfig,PerDistinctIdPipelineInput,@@ -67,7 +60,6 @@ export interface JoinedIngestionPipelineConfig {outputs: IngestionOutputs<| EventOutput| AiEventOutput- | HeatmapsOutput| IngestionWarningsOutput| DlqOutput| OverflowOutput@@ -213,7 +205,7 @@ export function createJoinedIngestionPipeline<.sequentially((b) =>b.pipe(createParseHeadersStep())- .pipe(createDenyEventsStep(['$exception', '$$client_ingestion_warning']))+ .pipe(createDenyEventsStep(['$exception', '$$client_ingestion_warning', '$$heatmap'])).pipe(createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {overflowEnabled,diff --git a/nodejs/src/ingestion/analytics/outputs/index.ts b/nodejs/src/ingestion/analytics/outputs/index.tsindex b207b7a62bb5..ce8b3fc32f78 100644--- a/nodejs/src/ingestion/analytics/outputs/index.ts+++ b/nodejs/src/ingestion/analytics/outputs/index.ts@@ -3,9 +3,6 @@ export { EVENTS_OUTPUT, type EventOutput } from '../../common/outputs'export const AI_EVENTS_OUTPUT = 'ai_events' as constexport type AiEventOutput = typeof AI_EVENTS_OUTPUT-export const HEATMAPS_OUTPUT = 'heatmaps' as const-export type HeatmapsOutput = typeof HEATMAPS_OUTPUT-export const ASYNC_OUTPUT = 'async' as constexport type AsyncOutput = typeof ASYNC_OUTPUTdiff --git a/nodejs/src/ingestion/analytics/outputs/registry.ts b/nodejs/src/ingestion/analytics/outputs/registry.tsindex 6bbe562d105a..06bec3ab726a 100644--- a/nodejs/src/ingestion/analytics/outputs/registry.ts+++ b/nodejs/src/ingestion/analytics/outputs/registry.ts@@ -1,11 +1,4 @@-import {- AI_EVENTS_OUTPUT,- ASYNC_OUTPUT,- EVENTS_OUTPUT,- HEATMAPS_OUTPUT,- PERSONS_OUTPUT,- PERSON_DISTINCT_IDS_OUTPUT,-} from '.'+import { AI_EVENTS_OUTPUT, ASYNC_OUTPUT, EVENTS_OUTPUT, PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT } from '.'import {APP_METRICS_OUTPUT,@@ -29,10 +22,6 @@ export function createOutputsRegistry() {topicKey: 'INGESTION_OUTPUT_AI_EVENTS_TOPIC',producerKey: 'INGESTION_OUTPUT_AI_EVENTS_PRODUCER',})- .register(HEATMAPS_OUTPUT, {- topicKey: 'INGESTION_OUTPUT_HEATMAPS_TOPIC',- producerKey: 'INGESTION_OUTPUT_HEATMAPS_PRODUCER',- }).register(INGESTION_WARNINGS_OUTPUT, {topicKey: 'INGESTION_OUTPUT_INGESTION_WARNINGS_TOPIC',producerKey: 'INGESTION_OUTPUT_INGESTION_WARNINGS_PRODUCER',diff --git a/nodejs/src/ingestion/analytics/per-distinct-id-pipeline.ts b/nodejs/src/ingestion/analytics/per-distinct-id-pipeline.tsindex 20eeceb29d80..7a9e5e4a13af 100644--- a/nodejs/src/ingestion/analytics/per-distinct-id-pipeline.ts+++ b/nodejs/src/ingestion/analytics/per-distinct-id-pipeline.ts@@ -13,22 +13,14 @@ import { IngestionOutputs } from '../outputs/ingestion-outputs'import { PipelineBuilder, StartPipelineBuilder } from '../pipelines/builders/pipeline-builders'import { TopHogWrapper } from '../pipelines/extensions/tophog'import { EventSubpipelineInput, createEventSubpipeline } from './event-subpipeline'-import { HeatmapSubpipelineInput, createHeatmapSubpipeline } from './heatmap-subpipeline'-import {- AiEventOutput,- AsyncOutput,- EventOutput,- HeatmapsOutput,- PersonDistinctIdsOutput,- PersonsOutput,-} from './outputs'+import { AiEventOutput, AsyncOutput, EventOutput, PersonDistinctIdsOutput, PersonsOutput } from './outputs'-export type PerDistinctIdPipelineInput = EventSubpipelineInput & HeatmapSubpipelineInput & AiEventSubpipelineInput+export type PerDistinctIdPipelineInput = EventSubpipelineInput & AiEventSubpipelineInputexport interface PerDistinctIdPipelineConfig {options: EventPipelineRunnerOptionsoutputs: IngestionOutputs<- EventOutput | AiEventOutput | HeatmapsOutput | IngestionWarningsOutput | PersonsOutput | PersonDistinctIdsOutput+ EventOutput | AiEventOutput | IngestionWarningsOutput | PersonsOutput | PersonDistinctIdsOutput>splitAiEventsConfig: SplitAiEventsStepConfigteamManager: TeamManager@@ -43,10 +35,9 @@ export interface PerDistinctIdPipelineContext {team: Team}-type EventBranch = 'heatmap' | 'ai' | 'event'+type EventBranch = 'ai' | 'event'const EVENT_BRANCH_MAP = new Map<string, EventBranch>([- ['$$heatmap', 'heatmap'],...[...AI_EVENT_TYPES].map((t): [string, EventBranch] => [t, 'ai']),])@@ -65,14 +56,6 @@ export function createPerDistinctIdPipeline<TInput extends PerDistinctIdPipeline(e) =>e.branching(classifyEvent, (branches) =>branches- .branch('heatmap', (b) =>- createHeatmapSubpipeline(b, {- options,- outputs,- teamManager,- groupTypeManager,- })- ).branch('ai', (b) =>createAiEventSubpipeline(b, {options,diff --git a/nodejs/src/ingestion/analytics/testing-ai-event-subpipeline.ts b/nodejs/src/ingestion/analytics/testing-ai-event-subpipeline.tsdeleted file mode 100644index 344f0acce630..000000000000--- a/nodejs/src/ingestion/analytics/testing-ai-event-subpipeline.ts+++ /dev/null@@ -1,50 +0,0 @@-import { Message } from 'node-rdkafka'--import { PluginEvent } from '~/plugin-scaffold'--import { EventHeaders, Team } from '../../types'-import { createProcessAiEventStep } from '../ai/pipelines/steps/process-ai-event-step'-import { IngestionWarningsOutput } from '../common/outputs'-import { createCreateEventStep } from '../event-processing/create-event-step'-import { createDisablePersonProcessingWithFakePersonStep } from '../event-processing/disable-person-processing-with-fake-person-step'-import { createEmitEventStep } from '../event-processing/emit-event-step'-import { createNormalizeEventStep } from '../event-processing/normalize-event-step'-import { createPrepareEventStep } from '../event-processing/prepare-event-step'-import { IngestionOutputs } from '../outputs/ingestion-outputs'-import { PipelineBuilder, StartPipelineBuilder } from '../pipelines/builders/pipeline-builders'-import { EVENTS_OUTPUT, EventOutput } from './outputs'--export interface TestingAiEventSubpipelineInput {- message: Message- event: PluginEvent- team: Team- headers: EventHeaders-}--export interface TestingAiEventSubpipelineConfig {- outputs: IngestionOutputs<EventOutput | IngestionWarningsOutput>- groupId: string-}--export function createTestingAiEventSubpipeline<TInput extends TestingAiEventSubpipelineInput, TContext>(- builder: StartPipelineBuilder<TInput, TContext>,- config: TestingAiEventSubpipelineConfig-): PipelineBuilder<TInput, void, TContext> {- const { outputs, groupId } = config-- // Compared to ai-event-subpipeline.ts:- // CHANGED: createNormalizeProcessPersonFlagStep → createDisablePersonProcessingWithFakePersonStep- // (always disables person processing and provides a deterministic fake person)- // REMOVED: createProcessPersonlessStep (fetches/creates personless persons from cache)- // REMOVED: createProcessPersonsStep (creates/updates real person records, handles merges)- // REMOVED: createProcessGroupsStep (creates/updates group records, enriches with group properties)- // REMOVED: createHogTransformEventStep (no hog transformations — avoids Redis writes)- // REMOVED: topHog metrics wrapping (no TopHog in this pipeline)- return builder- .pipe(createDisablePersonProcessingWithFakePersonStep())- .pipe(createNormalizeEventStep())- .pipe(createProcessAiEventStep())- .pipe(createPrepareEventStep())- .pipe(createCreateEventStep(EVENTS_OUTPUT))- .pipe(createEmitEventStep({ outputs, groupId }))-}diff --git a/nodejs/src/ingestion/analytics/testing-event-subpipeline.ts b/nodejs/src/ingestion/analytics/testing-event-subpipeline.tsdeleted file mode 100644index 87997990b00e..000000000000--- a/nodejs/src/ingestion/analytics/testing-event-subpipeline.ts+++ /dev/null@@ -1,55 +0,0 @@-import { Message } from 'node-rdkafka'--import { PluginEvent } from '~/plugin-scaffold'--import { EventHeaders, Team } from '../../types'-import { IngestionWarningsOutput } from '../common/outputs'-import { createCreateEventStep } from '../event-processing/create-event-step'-import { createDisablePersonProcessingWithFakePersonStep } from '../event-processing/disable-person-processing-with-fake-person-step'-import { createEmitEventStep } from '../event-processing/emit-event-step'-import { createExtractHeatmapDataStep } from '../event-processing/extract-heatmap-data-step'-import { createNormalizeEventStep } from '../event-processing/normalize-event-step'-import { createPrepareEventStep } from '../event-processing/prepare-event-step'-import { IngestionOutputs } from '../outputs/ingestion-outputs'-import { PipelineBuilder, StartPipelineBuilder } from '../pipelines/builders/pipeline-builders'-import { EVENTS_OUTPUT, EventOutput, HeatmapsOutput } from './outputs'--export interface TestingEventSubpipelineInput {- message: Message- event: PluginEvent- team: Team- headers: EventHeaders-}--export interface TestingEventSubpipelineConfig {- outputs: IngestionOutputs<EventOutput | HeatmapsOutput | IngestionWarningsOutput>- groupId: string-}--export function createTestingEventSubpipeline<TInput extends TestingEventSubpipelineInput, TContext>(- builder: StartPipelineBuilder<TInput, TContext>,- config: TestingEventSubpipelineConfig-): PipelineBuilder<TInput, void, TContext> {- const { outputs, groupId } = config-- // Compared to event-subpipeline.ts:- // CHANGED: createNormalizeProcessPersonFlagStep → createDisablePersonProcessingWithFakePersonStep- // (always disables person processing and provides a deterministic fake person)- // REMOVED: createProcessPersonlessStep (fetches/creates personless persons from cache)- // REMOVED: createProcessPersonsStep (creates/updates real person records, handles merges)- // REMOVED: createProcessGroupsStep (creates/updates group records, enriches with group properties)- // REMOVED: createHogTransformEventStep (no hog transformations — avoids Redis writes)- // REMOVED: topHog metrics wrapping (no TopHog in this pipeline)- return builder- .pipe(createDisablePersonProcessingWithFakePersonStep())- .pipe(createNormalizeEventStep())- .pipe(createPrepareEventStep())- .pipe(createExtractHeatmapDataStep(outputs))- .pipe(createCreateEventStep(EVENTS_OUTPUT))- .pipe(- createEmitEventStep({- outputs,- groupId,- })- )-}diff --git a/nodejs/src/ingestion/analytics/testing-heatmap-subpipeline.ts b/nodejs/src/ingestion/analytics/testing-heatmap-subpipeline.tsdeleted file mode 100644index 727d190aea54..000000000000--- a/nodejs/src/ingestion/analytics/testing-heatmap-subpipeline.ts+++ /dev/null@@ -1,39 +0,0 @@-import { PluginEvent } from '~/plugin-scaffold'--import { EventHeaders, Team } from '../../types'-import { createCheckHeatmapOptInStep } from '../event-processing/check-heatmap-opt-in-step'-import { createDisablePersonProcessingStep } from '../event-processing/disable-person-processing-step'-import { createExtractHeatmapDataStep } from '../event-processing/extract-heatmap-data-step'-import { createNormalizeEventStep } from '../event-processing/normalize-event-step'-import { createPrepareEventStep } from '../event-processing/prepare-event-step'-import { createSkipEmitEventStep } from '../event-processing/skip-emit-event-step'-import { IngestionOutputs } from '../outputs/ingestion-outputs'-import { PipelineBuilder, StartPipelineBuilder } from '../pipelines/builders/pipeline-builders'-import { HeatmapsOutput } from './outputs'--export interface TestingHeatmapSubpipelineInput {- event: PluginEvent- team: Team- headers: EventHeaders-}--export interface TestingHeatmapSubpipelineConfig {- outputs: IngestionOutputs<HeatmapsOutput>-}--export function createTestingHeatmapSubpipeline<TInput extends TestingHeatmapSubpipelineInput, TContext>(- builder: StartPipelineBuilder<TInput, TContext>,- config: TestingHeatmapSubpipelineConfig-): PipelineBuilder<TInput, void, TContext> {- const { outputs } = config-- // Compared to heatmap-subpipeline.ts:- // REMOVED: createProcessGroupsStep (creates/updates group records, enriches with group properties)- return builder- .pipe(createCheckHeatmapOptInStep())- .pipe(createDisablePersonProcessingStep())- .pipe(createNormalizeEventStep())- .pipe(createPrepareEventStep())- .pipe(createExtractHeatmapDataStep(outputs))- .pipe(createSkipEmitEventStep())-}diff --git a/nodejs/src/ingestion/analytics/testing-joined-ingestion-pipeline.ts b/nodejs/src/ingestion/analytics/testing-joined-ingestion-pipeline.tsdeleted file mode 100644index 9026aad7da93..000000000000--- a/nodejs/src/ingestion/analytics/testing-joined-ingestion-pipeline.ts+++ /dev/null@@ -1,132 +0,0 @@-import { Message } from 'node-rdkafka'--import { Team } from '../../types'-import { PromiseScheduler } from '../../utils/promise-scheduler'-import { TeamManager } from '../../utils/team-manager'-import { DlqOutput, IngestionWarningsOutput } from '../common/outputs'-import { IngestionOutputs } from '../outputs/ingestion-outputs'-import { BatchPipelineBuilder } from '../pipelines/builders/batch-pipeline-builders'-import { OkResultWithContext } from '../pipelines/pipeline.interface'-import { PipelineConfig } from '../pipelines/result-handling-pipeline'-import { ok } from '../pipelines/results'-import { EventOutput, HeatmapsOutput } from './outputs'-import {- TestingPerDistinctIdPipelineConfig,- TestingPerDistinctIdPipelineInput,- createTestingPerDistinctIdPipeline,-} from './testing-per-distinct-id-pipeline'-import {- TestingPostTeamPreprocessingSubpipelineInput,- createTestingPostTeamPreprocessingSubpipeline,-} from './testing-post-team-preprocessing-subpipeline'-import { createTestingPreTeamPreprocessingSubpipeline } from './testing-pre-team-preprocessing-subpipeline'--export interface TestingJoinedIngestionPipelineConfig {- groupId: string- outputs: IngestionOutputs<EventOutput | HeatmapsOutput | IngestionWarningsOutput | DlqOutput>-}--export interface TestingJoinedIngestionPipelineDeps {- promiseScheduler: PromiseScheduler- teamManager: TeamManager-}--export interface TestingJoinedIngestionPipelineInput {- message: Message-}--export interface TestingJoinedIngestionPipelineContext {- message: Message-}--type PreprocessingOutput = TestingPostTeamPreprocessingSubpipelineInput--function addTeamToContext<T extends { team: Team }, C>(- element: OkResultWithContext<T, C>-): OkResultWithContext<T, C & { team: Team }> {- return {- result: element.result,- context: {- ...element.context,- team: element.result.value.team,- },- }-}--function getTokenAndDistinctId(input: TestingPerDistinctIdPipelineInput): string {- const token = input.headers.token ?? ''- const distinctId = input.event.distinct_id ?? ''- return `${token}:${distinctId}`-}--function mapToPerEventInput<C>(- element: OkResultWithContext<PreprocessingOutput, C>-): OkResultWithContext<TestingPerDistinctIdPipelineInput, C> {- const input = element.result.value- return {- result: ok({- message: input.message,- event: input.event,- team: input.team,- headers: input.headers,- }),- context: element.context,- }-}--export function createTestingJoinedIngestionPipeline<- TInput extends TestingJoinedIngestionPipelineInput,- TContext extends TestingJoinedIngestionPipelineContext,->(- builder: BatchPipelineBuilder<TInput, TInput, TContext, TContext>,- config: TestingJoinedIngestionPipelineConfig,- deps: TestingJoinedIngestionPipelineDeps-) {- const { groupId, outputs } = config-- const { promiseScheduler } = deps-- const pipelineConfig: PipelineConfig = {- outputs,- promiseScheduler,- }-- const perEventConfig: TestingPerDistinctIdPipelineConfig = {- outputs,- groupId,- }-- // Compared to joined-ingestion-pipeline.ts:- // CHANGED: uses createTestingPostTeamPreprocessingSubpipeline (no person prefetch, cookieless, or personless batch)- // CHANGED: uses createTestingPerDistinctIdPipeline (no person/group processing in event branches)- // REMOVED: createFlushBatchStoresStep (no person/group stores to flush)- // REMOVED: personsStore, groupStore, cookielessManager, groupTypeManager from deps/config- return builder- .messageAware((b) =>- b- .sequentially((b) =>- createTestingPreTeamPreprocessingSubpipeline(b, {- teamManager: deps.teamManager,- })- )- .filterMap(addTeamToContext, (b) =>- b- .teamAware((b) =>- createTestingPostTeamPreprocessingSubpipeline(b)- .filterMap(mapToPerEventInput, (b) =>- b- .groupBy(getTokenAndDistinctId)- .concurrently((eventsForDistinctId) =>- eventsForDistinctId.sequentially((event) =>- createTestingPerDistinctIdPipeline(event, perEventConfig)- )- )- )- .gather()- )- .handleIngestionWarnings(outputs)- )- )- .handleResults(pipelineConfig)- .handleSideEffects(promiseScheduler, { await: false })-}diff --git a/nodejs/src/ingestion/analytics/testing-per-distinct-id-pipeline.ts b/nodejs/src/ingestion/analytics/testing-per-distinct-id-pipeline.tsdeleted file mode 100644index c36e3e98e33a..000000000000--- a/nodejs/src/ingestion/analytics/testing-per-distinct-id-pipeline.ts+++ /dev/null@@ -1,68 +0,0 @@-import { Message } from 'node-rdkafka'--import { Team } from '../../types'-import { AI_EVENT_TYPES } from '../ai'-import { IngestionWarningsOutput } from '../common/outputs'-import { IngestionOutputs } from '../outputs/ingestion-outputs'-import { PipelineBuilder, StartPipelineBuilder } from '../pipelines/builders/pipeline-builders'-import { EventOutput, HeatmapsOutput } from './outputs'-import { TestingAiEventSubpipelineInput, createTestingAiEventSubpipeline } from './testing-ai-event-subpipeline'-import { TestingEventSubpipelineInput, createTestingEventSubpipeline } from './testing-event-subpipeline'-import { TestingHeatmapSubpipelineInput, createTestingHeatmapSubpipeline } from './testing-heatmap-subpipeline'--export type TestingPerDistinctIdPipelineInput = TestingEventSubpipelineInput &- TestingHeatmapSubpipelineInput &- TestingAiEventSubpipelineInput--export interface TestingPerDistinctIdPipelineConfig {- outputs: IngestionOutputs<EventOutput | HeatmapsOutput | IngestionWarningsOutput>- groupId: string-}--export interface TestingPerDistinctIdPipelineContext {- message: Message- team: Team-}--type EventBranch = 'heatmap' | 'ai' | 'event'--const EVENT_BRANCH_MAP = new Map<string, EventBranch>([- ['$$heatmap', 'heatmap'],- ...[...AI_EVENT_TYPES].map((t): [string, EventBranch] => [t, 'ai']),-])--function classifyEvent(input: TestingPerDistinctIdPipelineInput): EventBranch {- return EVENT_BRANCH_MAP.get(input.event.event) ?? 'event'-}--export function createTestingPerDistinctIdPipeline<TInput extends TestingPerDistinctIdPipelineInput, TContext>(- builder: StartPipelineBuilder<TInput, TContext>,- config: TestingPerDistinctIdPipelineConfig-): PipelineBuilder<TInput, void, TContext> {- const { outputs, groupId } = config-- return builder.retry(- (e) =>- e.branching<EventBranch, void>(classifyEvent, (branches) =>- branches- .branch('heatmap', (b) =>- createTestingHeatmapSubpipeline(b, {- outputs,- })- )- .branch('ai', (b) =>- createTestingAiEventSubpipeline(b, {- outputs,- groupId,- })- )- .branch('event', (b) =>- createTestingEventSubpipeline(b, {- outputs,- groupId,- })- )- ),- { tries: 3, sleepMs: 100 }- )-}diff --git a/nodejs/src/ingestion/analytics/testing-post-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/analytics/testing-post-team-preprocessing-subpipeline.tsdeleted file mode 100644index d510befa9a82..000000000000--- a/nodejs/src/ingestion/analytics/testing-post-team-preprocessing-subpipeline.ts+++ /dev/null@@ -1,38 +0,0 @@-import { Message } from 'node-rdkafka'--import { PluginEvent } from '~/plugin-scaffold'--import { EventHeaders, Team } from '../../types'-import { createValidateEventMetadataStep, createValidateEventPropertiesStep } from '../event-preprocessing'-import { createDropOldEventsStep } from '../event-processing/drop-old-events-step'-import { BatchPipelineBuilder } from '../pipelines/builders/batch-pipeline-builders'--export interface TestingPostTeamPreprocessingSubpipelineInput {- message: Message- headers: EventHeaders- event: PluginEvent- team: Team-}--export function createTestingPostTeamPreprocessingSubpipeline<- TInput extends TestingPostTeamPreprocessingSubpipelineInput,- TContext,->(builder: BatchPipelineBuilder<TInput, TInput, TContext, TContext>) {- // Compared to post-team-preprocessing-subpipeline.ts:- // REMOVED: createApplyPersonProcessingRestrictionsStep (applies per-token/distinct_id person processing restrictions)- // REMOVED: createApplyCookielessProcessingStep (rewrites cookieless distinct IDs for person processing)- // REMOVED: prefetchPersonsStep (prefetches person data from Postgres into cache)- // REMOVED: processPersonlessDistinctIdsBatchStep (batch inserts personless distinct IDs)- // REMOVED: createRateLimitToOverflowStep (overflow rate limiting writes to Redis)- // REMOVED: createOverflowLaneTTLRefreshStep (overflow TTL refresh writes to Redis)- // REMOVED: createPrefetchHogFunctionsStep (no hog transformations in this pipeline)- // REMOVED: createValidateEventSchemaStep (no event schema enforcement in this pipeline)- return builder- .sequentially((b) => {- return b- .pipe(createValidateEventMetadataStep())- .pipe(createValidateEventPropertiesStep())- .pipe(createDropOldEventsStep())- })- .gather()-}diff --git a/nodejs/src/ingestion/analytics/testing-pre-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/analytics/testing-pre-team-preprocessing-subpipeline.tsdeleted file mode 100644index 8a7f4223dd3d..000000000000--- a/nodejs/src/ingestion/analytics/testing-pre-team-preprocessing-subpipeline.ts+++ /dev/null@@ -1,49 +0,0 @@-import { Message } from 'node-rdkafka'--import { PluginEvent } from '~/plugin-scaffold'-import { TeamManager } from '~/utils/team-manager'--import { EventHeaders, Team } from '../../types'-import { createDenyEventsStep } from '../common/steps/deny-events'-import {- createEnrichSurveyPersonPropertiesStep,- createParseHeadersStep,- createParseKafkaMessageStep,- createResolveTeamStep,- createValidateAiEventTokensStep,- createValidateHistoricalMigrationStep,-} from '../event-preprocessing'-import { StartPipelineBuilder } from '../pipelines/builders/pipeline-builders'--export interface TestingPreTeamPreprocessingSubpipelineInput {- message: Message-}--export interface TestingPreTeamPreprocessingSubpipelineOutput {- message: Message- headers: EventHeaders- event: PluginEvent- team: Team-}--export interface TestingPreTeamPreprocessingSubpipelineConfig {- teamManager: TeamManager-}--// Compared to pre-team-preprocessing-subpipeline.ts:-// REMOVED: createApplyEventRestrictionsStep (drop/overflow/skip-persons restrictions — not needed in testing pipeline)-export function createTestingPreTeamPreprocessingSubpipeline<- TInput extends TestingPreTeamPreprocessingSubpipelineInput,- TContext,->(builder: StartPipelineBuilder<TInput, TContext>, config: TestingPreTeamPreprocessingSubpipelineConfig) {- const { teamManager } = config-- return builder- .pipe(createParseHeadersStep())- .pipe(createDenyEventsStep(['$exception', '$$client_ingestion_warning']))- .pipe(createParseKafkaMessageStep())- .pipe(createResolveTeamStep(teamManager))- .pipe(createValidateHistoricalMigrationStep())- .pipe(createValidateAiEventTokensStep())- .pipe(createEnrichSurveyPersonPropertiesStep())-}diff --git a/nodejs/src/ingestion/clientwarnings/consumer.test.ts b/nodejs/src/ingestion/clientwarnings/consumer.test.tsindex b93bd5b23900..5a32245470b3 100644--- a/nodejs/src/ingestion/clientwarnings/consumer.test.ts+++ b/nodejs/src/ingestion/clientwarnings/consumer.test.ts@@ -15,7 +15,7 @@ describe('createClientWarningsConsumer', () => {return {INGESTION_CONSUMER_GROUP_ID: 'g',INGESTION_CONSUMER_CONSUME_TOPIC: 't',- INGESTION_PIPELINE: 'analytics',+ INGESTION_PIPELINE: 'clientwarnings',INGESTION_LANE: 'main',KAFKA_BATCH_START_LOGGING_ENABLED: false,DROP_EVENTS_BY_TOKEN_DISTINCT_ID: '',diff --git a/nodejs/src/ingestion/cookieless/cookieless-manager.ts b/nodejs/src/ingestion/cookieless/cookieless-manager.tsindex 1b699cb77bfb..bcd87d55f081 100644--- a/nodejs/src/ingestion/cookieless/cookieless-manager.ts+++ b/nodejs/src/ingestion/cookieless/cookieless-manager.ts@@ -14,7 +14,14 @@ import { instrumentFn } from '~/common/tracing/tracing-utils'import { PluginEvent, Properties } from '~/plugin-scaffold'import { cookielessRedisErrorCounter } from '../../common/metrics'-import { CookielessServerHashMode, EventHeaders, IncomingEventWithTeam, PipelineEvent, Team } from '../../types'+import {+ CookielessServerHashMode,+ EventHeaders,+ IncomingEventWithTeam,+ PipelineEvent,+ RedisPool,+ Team,+} from '../../types'import { ConcurrencyController } from '../../utils/concurrencyController'import { RedisOperationError } from '../../utils/db/error'import { logger } from '../../utils/logger'@@ -1024,3 +1031,26 @@ export function extractRootDomain(input: string): string {// Add the port back if it existsreturn port ? `${domain}:${port}` : domain}++/**+ * Scope entry for a `CookielessManager`. Takes an already-built Redis pool (its own scope entry, so+ * draining it is the pool component's job); `stop` only shuts the manager down — i.e. clears its+ * cleanup interval.+ */+export class CookielessManagerComponent {+ constructor(+ private readonly config: CookielessManagerConfig,+ private readonly redisPool: RedisPool+ ) {}++ start(): Promise<{ value: CookielessManager; stop: () => Promise<void> }> {+ const manager = new CookielessManager(this.config, this.redisPool)+ return Promise.resolve({+ value: manager,+ stop: (): Promise<void> => {+ manager.shutdown()+ return Promise.resolve()+ },+ })+ }+}diff --git a/nodejs/src/ingestion/event-processing/disable-person-processing-with-fake-person-step.test.ts b/nodejs/src/ingestion/event-processing/disable-person-processing-with-fake-person-step.test.tsdeleted file mode 100644index 560b280935f5..000000000000--- a/nodejs/src/ingestion/event-processing/disable-person-processing-with-fake-person-step.test.ts+++ /dev/null@@ -1,74 +0,0 @@-import { DateTime } from 'luxon'--import { Team } from '../../types'-import { uuidFromDistinctId } from '../../worker/ingestion/person-uuid'-import { isOkResult } from '../pipelines/results'-import { createDisablePersonProcessingWithFakePersonStep } from './disable-person-processing-with-fake-person-step'--describe('createDisablePersonProcessingWithFakePersonStep', () => {- const team = { id: 42, project_id: 42 } as Team-- const step = createDisablePersonProcessingWithFakePersonStep()-- it('should set processPerson to false', async () => {- const input = { team, event: { distinct_id: 'user-1' }, headers: {} }- const result = await step(input)-- expect(isOkResult(result)).toBe(true)- if (isOkResult(result)) {- expect(result.value.processPerson).toBe(false)- }- })-- it('should provide a deterministic fake person', async () => {- const input = { team, event: { distinct_id: 'user-1' }, headers: {} }- const result = await step(input)-- expect(isOkResult(result)).toBe(true)- if (isOkResult(result)) {- expect(result.value.person.team_id).toBe(42)- expect(result.value.person.properties).toEqual({})- expect(result.value.person.uuid).toBe(uuidFromDistinctId(42, 'user-1'))- expect(result.value.person.created_at).toEqual(DateTime.utc(1970, 1, 1, 0, 0, 5))- }- })-- it('should produce the same person uuid for the same team and distinct_id', async () => {- const input1 = { team, event: { distinct_id: 'user-1' }, headers: {} }- const input2 = { team, event: { distinct_id: 'user-1' }, headers: {} }-- const result1 = await step(input1)- const result2 = await step(input2)-- expect(isOkResult(result1)).toBe(true)- expect(isOkResult(result2)).toBe(true)- if (isOkResult(result1) && isOkResult(result2)) {- expect(result1.value.person.uuid).toBe(result2.value.person.uuid)- }- })-- it('should produce different person uuids for different distinct_ids', async () => {- const input1 = { team, event: { distinct_id: 'user-1' }, headers: {} }- const input2 = { team, event: { distinct_id: 'user-2' }, headers: {} }-- const result1 = await step(input1)- const result2 = await step(input2)-- expect(isOkResult(result1)).toBe(true)- expect(isOkResult(result2)).toBe(true)- if (isOkResult(result1) && isOkResult(result2)) {- expect(result1.value.person.uuid).not.toBe(result2.value.person.uuid)- }- })-- it('should preserve existing input fields', async () => {- const input = { team, event: { distinct_id: 'user-1' } }- const result = await step(input)-- expect(isOkResult(result)).toBe(true)- if (isOkResult(result)) {- expect(result.value.team).toBe(team)- expect(result.value.event).toEqual({ distinct_id: 'user-1' })- }- })-})diff --git a/nodejs/src/ingestion/event-processing/disable-person-processing-with-fake-person-step.ts b/nodejs/src/ingestion/event-processing/disable-person-processing-with-fake-person-step.tsdeleted file mode 100644index 0588d1263057..000000000000--- a/nodejs/src/ingestion/event-processing/disable-person-processing-with-fake-person-step.ts+++ /dev/null@@ -1,46 +0,0 @@-import { DateTime } from 'luxon'--import { Person, Team } from '../../types'-import { uuidFromDistinctId } from '../../worker/ingestion/person-uuid'-import { PipelineResult, ok } from '../pipelines/results'-import { ProcessingStep } from '../pipelines/steps'--export interface DisablePersonProcessingWithFakePersonInput {- team: Team- event: { distinct_id: string }-}--/**- * Pipeline step that disables person processing and provides a deterministic- * fake person. Used in pipelines that skip person/group processing entirely- * (e.g. the testing ingestion pipeline).- *- * The fake person UUID is deterministic based on team_id and distinct_id.- */-export function createDisablePersonProcessingWithFakePersonStep<- TInput extends DisablePersonProcessingWithFakePersonInput,->(): ProcessingStep<TInput, TInput & { processPerson: boolean; person: Person }> {- return function disablePersonProcessingWithFakePersonStep(- input: TInput- ): Promise<PipelineResult<TInput & { processPerson: boolean; person: Person }>> {- const { team, event } = input- const distinctId = String(event.distinct_id)-- // Deterministic fake person - same logic as createFakePerson in process-personless-step.ts- const createdAt = DateTime.utc(1970, 1, 1, 0, 0, 5)- const person: Person = {- team_id: team.id,- properties: {},- uuid: uuidFromDistinctId(team.id, distinctId),- created_at: createdAt,- }-- return Promise.resolve(- ok({- ...input,- processPerson: false,- person,- })- )- }-}diff --git a/nodejs/src/ingestion/event-processing/check-heatmap-opt-in-step.test.ts b/nodejs/src/ingestion/heatmaps/check-heatmap-opt-in-step.test.tssimilarity index 100%rename from nodejs/src/ingestion/event-processing/check-heatmap-opt-in-step.test.tsrename to nodejs/src/ingestion/heatmaps/check-heatmap-opt-in-step.test.tsdiff --git a/nodejs/src/ingestion/event-processing/check-heatmap-opt-in-step.ts b/nodejs/src/ingestion/heatmaps/check-heatmap-opt-in-step.tssimilarity index 100%rename from nodejs/src/ingestion/event-processing/check-heatmap-opt-in-step.tsrename to nodejs/src/ingestion/heatmaps/check-heatmap-opt-in-step.tsdiff --git a/nodejs/src/ingestion/heatmaps/consumer-e2e.test.ts b/nodejs/src/ingestion/heatmaps/consumer-e2e.test.tsnew file mode 100644index 000000000000..30155fef6218--- /dev/null+++ b/nodejs/src/ingestion/heatmaps/consumer-e2e.test.ts@@ -0,0 +1,153 @@+import { Message } from 'node-rdkafka'++import { Clickhouse } from '~/tests/helpers/clickhouse'+import { waitForExpect } from '~/tests/helpers/expectations'+import {+ EventBuilder,+ IngesterLike,+ createKafkaMessages,+ createTestWithTeamIngester,+ waitForClickHouseKafkaConsumer,+} from '~/tests/helpers/ingestion-e2e'+import { resetKafka } from '~/tests/helpers/kafka'+import { resetTestDatabase } from '~/tests/helpers/sql'++import { getDefaultKafkaDownstreamProducerEnvConfig, getDefaultKafkaUpstreamProducerEnvConfig } from '../common/config'+import { KafkaProducerRegistryComponent } from '../common/outputs/registry'+import { Component, newScope } from '../common/scopes'+import { getDefaultIngestionOutputsConfig } from '../config'+import { CookielessManagerComponent } from '../cookieless/cookieless-manager'+import { HeatmapsConsumerConfig, HeatmapsSharedScope, createHeatmapsConsumer } from './consumer'++type CapturedBatchHandler = (messages: Message[]) => Promise<{ backgroundTask?: Promise<unknown> } | void>++// Captures the per-batch handler that `KafkaConsumerComponent` wires into the+// Kafka consumer at start, so the test can drive batches through the real+// pipeline without a live consumer. Prefixed `mock` so the jest.mock factory+// is allowed to reference it.+let mockCapturedHandler: CapturedBatchHandler | undefined++jest.mock('~/kafka/consumer', () => {+ const actual = jest.requireActual('~/kafka/consumer')+ const { HealthCheckResultOk } = jest.requireActual('~/types')+ return {+ ...actual,+ createKafkaConsumer: jest.fn(() => ({+ connect: (handler: CapturedBatchHandler) => {+ mockCapturedHandler = handler+ return Promise.resolve()+ },+ disconnect: () => Promise.resolve(),+ isHealthy: () => new HealthCheckResultOk(),+ offsetsStore: () => undefined,+ })),+ }+})++jest.mock('../../utils/logger')++function constComponent<T extends object>(value: T): Component<T> {+ return { start: () => Promise.resolve({ value, stop: () => Promise.resolve() }) }+}++class HeatmapsTestIngester implements IngesterLike {+ private stopScope?: () => Promise<void>++ constructor(private readonly consumerScope: ReturnType<typeof createHeatmapsConsumer>) {}++ async start(): Promise<void> {+ const { stop } = await this.consumerScope.start()+ this.stopScope = stop+ }++ async stop(): Promise<void> {+ await this.stopScope?.()+ }++ async handleKafkaBatch(messages: Message[]): Promise<{ backgroundTask?: Promise<unknown> }> {+ if (!mockCapturedHandler) {+ throw new Error('Kafka consumer batch handler was not captured — did the consumer start?')+ }+ return (await mockCapturedHandler(messages)) ?? {}+ }+}++async function fetchHeatmaps(clickhouse: Clickhouse, teamId: number): Promise<any[]> {+ return (await clickhouse.query(`SELECT * FROM heatmaps WHERE team_id = ${teamId}`)) as unknown as any[]+}++describe('Heatmaps consumer E2E', () => {+ const testWithTeamIngester = createTestWithTeamIngester({}, (infra) => {+ const config: HeatmapsConsumerConfig = {+ ...infra.config,+ ...getDefaultIngestionOutputsConfig(),+ INGESTION_CONSUMER_GROUP_ID: 'heatmaps-e2e-test',+ INGESTION_CONSUMER_CONSUME_TOPIC: 'heatmaps-e2e-test',+ INGESTION_PIPELINE: 'heatmaps',+ INGESTION_LANE: null,+ KAFKA_BATCH_START_LOGGING_ENABLED: false,+ }++ // Empty producer env values fall back to the rdkafka defaults (broker+ // `kafka:9092`), which is the same broker the rest of the test suite+ // produces to — so the registry's heatmaps producer reaches ClickHouse.+ const registryConfig = {+ ...getDefaultKafkaUpstreamProducerEnvConfig(),+ ...getDefaultKafkaDownstreamProducerEnvConfig(),+ }+ const sharedScope: HeatmapsSharedScope = newScope('heatmaps-e2e-shared', (b) =>+ b+ .add('postgres', constComponent(infra.postgres))+ .add('redisPool', constComponent(infra.redisPool))+ .add('teamManager', constComponent(infra.teamManager))+ .add('cookielessManager', new CookielessManagerComponent(infra.config, infra.redisPool))+ .add(+ 'producerRegistry',+ new KafkaProducerRegistryComponent(infra.config.KAFKA_CLIENT_RACK, registryConfig)+ )+ )++ return new HeatmapsTestIngester(createHeatmapsConsumer(config, sharedScope))+ })++ let clickhouse: Clickhouse++ beforeAll(async () => {+ clickhouse = Clickhouse.create()+ await resetKafka()+ await resetTestDatabase()+ await clickhouse.resetTestDatabase()+ await waitForClickHouseKafkaConsumer(clickhouse)+ })++ afterAll(async () => {+ await resetTestDatabase()+ await clickhouse.resetTestDatabase()+ clickhouse.close()+ })++ testWithTeamIngester('extracts heatmap data to ClickHouse', {}, async ({ ingester, team, token }) => {+ const event = new EventBuilder(team)+ .withEvent('$$heatmap')+ .withProperties({+ $session_id: 'session-1',+ $viewport_width: 1024,+ $viewport_height: 768,+ $current_url: 'http://localhost:3000/',+ $heatmap_data: {+ 'http://localhost:3000/': [{ x: 100, y: 200, target_fixed: false, type: 'click' }],+ },+ })+ .build()++ const { backgroundTask } = await ingester.handleKafkaBatch(createKafkaMessages([event], token))+ await backgroundTask++ await waitForExpect(async () => {+ const heatmaps = await fetchHeatmaps(clickhouse, team.id)+ expect(heatmaps.length).toBe(1)+ expect(heatmaps[0].type).toBe('click')+ expect(heatmaps[0].session_id).toBe('session-1')+ }, 30_000)+ })+})diff --git a/nodejs/src/ingestion/heatmaps/consumer.test.ts b/nodejs/src/ingestion/heatmaps/consumer.test.tsnew file mode 100644index 000000000000..6edaa9d288a3--- /dev/null+++ b/nodejs/src/ingestion/heatmaps/consumer.test.ts@@ -0,0 +1,68 @@+import { RedisPool } from '../../types'+import { PostgresRouter } from '../../utils/db/postgres'+import { TeamManagerComponent } from '../../utils/team-manager'+import { ProducerName } from '../common/outputs'+import { newScope } from '../common/scopes'+import { IngestionOutputsConfig } from '../config'+import { CookielessManager } from '../cookieless/cookieless-manager'+import { KafkaProducerRegistry } from '../outputs/kafka-producer-registry'+import { HeatmapsConsumerConfig, HeatmapsSharedScope, createHeatmapsConsumer } from './consumer'+import * as pipelineModule from './pipeline'++jest.mock('./pipeline')++describe('createHeatmapsConsumer', () => {+ function makeConfig(): HeatmapsConsumerConfig {+ return {+ INGESTION_CONSUMER_GROUP_ID: 'g',+ INGESTION_CONSUMER_CONSUME_TOPIC: 't',+ INGESTION_PIPELINE: 'heatmaps',+ INGESTION_LANE: 'main',+ KAFKA_BATCH_START_LOGGING_ENABLED: false,+ DROP_EVENTS_BY_TOKEN_DISTINCT_ID: '',+ ...({} as IngestionOutputsConfig),+ }+ }++ function makeSharedScope(): HeatmapsSharedScope {+ // 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 — the components' bodies don't run.+ 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(),+ }),+ })+ )+ }++ beforeEach(() => {+ ;(pipelineModule.createHeatmapsPipeline as jest.Mock) = jest.fn().mockReturnValue({+ feed: jest.fn(),+ next: jest.fn(),+ })+ })++ it('defers pipeline construction until scope.start()', () => {+ createHeatmapsConsumer(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.createHeatmapsPipeline).not.toHaveBeenCalled()+ })+})diff --git a/nodejs/src/ingestion/heatmaps/consumer.ts b/nodejs/src/ingestion/heatmaps/consumer.tsnew file mode 100644index 000000000000..79f82588302a--- /dev/null+++ b/nodejs/src/ingestion/heatmaps/consumer.ts@@ -0,0 +1,51 @@+import { RedisPool } from '../../types'+import { PostgresRouter } from '../../utils/db/postgres'+import { EventIngestionRestrictionManagerComponent } from '../../utils/event-ingestion-restrictions'+import { TeamManager } from '../../utils/team-manager'+import { EventFilterManagerComponent } from '../common/event-filters'+import { CommonIngestionConsumerConfig, CommonIngestionConsumerScope } from '../common/ingestion-consumer'+import { ProducerName } from '../common/outputs'+import { Scope, extend } from '../common/scopes'+import { PromiseSchedulerComponent } from '../common/utils/promise-scheduler'+import { IngestionConsumerConfig, IngestionOutputsConfig } from '../config'+import { CookielessManager } from '../cookieless/cookieless-manager'+import { IngestionOutputsComponent } from '../outputs/ingestion-outputs'+import { KafkaProducerRegistry } from '../outputs/kafka-producer-registry'+import { createOutputsRegistry } from './outputs/registry'+import { createHeatmapsPipeline } from './pipeline'++export type HeatmapsConsumerConfig = CommonIngestionConsumerConfig &+ IngestionOutputsConfig &+ Pick<IngestionConsumerConfig, 'DROP_EVENTS_BY_TOKEN_DISTINCT_ID'>++export type HeatmapsSharedScope = Scope<{+ postgres: PostgresRouter+ redisPool: RedisPool+ teamManager: TeamManager+ cookielessManager: CookielessManager+ producerRegistry: KafkaProducerRegistry<ProducerName>+}>++export function createHeatmapsConsumer(config: HeatmapsConsumerConfig, sharedScope: HeatmapsSharedScope) {+ const staticDropEventTokens = config.DROP_EVENTS_BY_TOKEN_DISTINCT_ID.split(',').filter((x) => !!x)+ const scope = extend(sharedScope, 'heatmaps', (container, builder) =>+ builder+ .add('promiseScheduler', new PromiseSchedulerComponent())+ .add(+ 'eventIngestionRestrictionManager',+ new EventIngestionRestrictionManagerComponent(container.redisPool, {+ pipeline: 'heatmaps',+ staticDropEventTokens,+ })+ )+ .add('eventFilterManager', new EventFilterManagerComponent(container.postgres))+ .add(+ 'outputs',+ new IngestionOutputsComponent(() => createOutputsRegistry().build(container.producerRegistry, config))+ )+ )++ return new CommonIngestionConsumerScope('heatmaps', config, scope, ({ container }) =>+ createHeatmapsPipeline(container)+ )+}diff --git a/nodejs/src/ingestion/event-processing/disable-person-processing-step.test.ts b/nodejs/src/ingestion/heatmaps/disable-person-processing-step.test.tssimilarity index 100%rename from nodejs/src/ingestion/event-processing/disable-person-processing-step.test.tsrename to nodejs/src/ingestion/heatmaps/disable-person-processing-step.test.tsdiff --git a/nodejs/src/ingestion/event-processing/disable-person-processing-step.ts b/nodejs/src/ingestion/heatmaps/disable-person-processing-step.tssimilarity index 100%rename from nodejs/src/ingestion/event-processing/disable-person-processing-step.tsrename to nodejs/src/ingestion/heatmaps/disable-person-processing-step.tsdiff --git a/nodejs/src/ingestion/event-processing/extract-heatmap-data-step.test.ts b/nodejs/src/ingestion/heatmaps/extract-heatmap-data-step.test.tssimilarity index 99%rename from nodejs/src/ingestion/event-processing/extract-heatmap-data-step.test.tsrename to nodejs/src/ingestion/heatmaps/extract-heatmap-data-step.test.tsindex 867faa91c8fc..ebbf33e31923 100644--- a/nodejs/src/ingestion/event-processing/extract-heatmap-data-step.test.ts+++ b/nodejs/src/ingestion/heatmaps/extract-heatmap-data-step.test.ts@@ -3,10 +3,10 @@ import { createMockIngestionOutputs } from '../../../tests/helpers/mock-ingestioimport { ISOTimestamp, PreIngestionEvent, ProjectId } from '../../types'import { parseJSON } from '../../utils/json-parse'import { cloneObject } from '../../utils/utils'-import { HEATMAPS_OUTPUT, HeatmapsOutput } from '../analytics/outputs'import { IngestionOutputs } from '../outputs/ingestion-outputs'import { PipelineResultType } from '../pipelines/results'import { createExtractHeatmapDataStep } from './extract-heatmap-data-step'+import { HEATMAPS_OUTPUT, HeatmapsOutput } from './outputs'const createTestEvent = (overrides: Partial<PreIngestionEvent> = {}): PreIngestionEvent => ({eventUuid: '018eebf3-cb48-750b-bfad-36409ea6f2b2',diff --git a/nodejs/src/ingestion/event-processing/extract-heatmap-data-step.ts b/nodejs/src/ingestion/heatmaps/extract-heatmap-data-step.tssimilarity index 99%rename from nodejs/src/ingestion/event-processing/extract-heatmap-data-step.tsrename to nodejs/src/ingestion/heatmaps/extract-heatmap-data-step.tsindex 10f3e5ea5119..39afea16cf71 100644--- a/nodejs/src/ingestion/event-processing/extract-heatmap-data-step.ts+++ b/nodejs/src/ingestion/heatmaps/extract-heatmap-data-step.ts@@ -4,11 +4,11 @@ import { EventHeaders, PreIngestionEvent, RawClickhouseHeatmapEvent, TimestampFoimport { logger } from '../../utils/logger'import { castTimestampOrNow } from '../../utils/utils'import { isDistinctIdIllegal } from '../../worker/ingestion/persons/person-merge-service'-import { HEATMAPS_OUTPUT, HeatmapsOutput } from '../analytics/outputs'import { IngestionOutputs } from '../outputs/ingestion-outputs'import { PipelineWarning } from '../pipelines/pipeline.interface'import { PipelineResult, drop, isOkResult, ok } from '../pipelines/results'import { ProcessingStep } from '../pipelines/steps'+import { HEATMAPS_OUTPUT, HeatmapsOutput } from './outputs'export interface ExtractHeatmapDataStepInput {preparedEvent: PreIngestionEventdiff --git a/nodejs/src/ingestion/heatmaps/index.ts b/nodejs/src/ingestion/heatmaps/index.tsnew file mode 100644index 000000000000..cdde728a841d--- /dev/null+++ b/nodejs/src/ingestion/heatmaps/index.ts@@ -0,0 +1,3 @@+export { createHeatmapsConsumer } from './consumer'+export type { HeatmapsConsumerConfig, HeatmapsSharedScope } from './consumer'+export { createHeatmapsPipeline } from './pipeline'diff --git a/nodejs/src/ingestion/heatmaps/outputs/index.ts b/nodejs/src/ingestion/heatmaps/outputs/index.tsnew file mode 100644index 000000000000..18f187b11600--- /dev/null+++ b/nodejs/src/ingestion/heatmaps/outputs/index.ts@@ -0,0 +1,2 @@+export const HEATMAPS_OUTPUT = 'heatmaps' as const+export type HeatmapsOutput = typeof HEATMAPS_OUTPUTdiff --git a/nodejs/src/ingestion/heatmaps/outputs/registry.ts b/nodejs/src/ingestion/heatmaps/outputs/registry.tsnew file mode 100644index 000000000000..68566a0b7b98--- /dev/null+++ b/nodejs/src/ingestion/heatmaps/outputs/registry.ts@@ -0,0 +1,28 @@+import { APP_METRICS_OUTPUT, DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT } from '../../common/outputs'+import { IngestionOutputsBuilder } from '../../outputs/ingestion-outputs-builder'+import { HEATMAPS_OUTPUT } from './index'++/**+ * Register the outputs the heatmaps pipeline produces to. Call+ * `.build(registry, config)` to resolve against the shared producer+ * registry.+ */+export function createOutputsRegistry() {+ return new IngestionOutputsBuilder()+ .register(HEATMAPS_OUTPUT, {+ topicKey: 'INGESTION_OUTPUT_HEATMAPS_TOPIC',+ producerKey: 'INGESTION_OUTPUT_HEATMAPS_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(APP_METRICS_OUTPUT, {+ topicKey: 'INGESTION_OUTPUT_APP_METRICS_TOPIC',+ producerKey: 'INGESTION_OUTPUT_APP_METRICS_PRODUCER',+ })+}diff --git a/nodejs/src/ingestion/heatmaps/pipeline.test.ts b/nodejs/src/ingestion/heatmaps/pipeline.test.tsnew file mode 100644index 000000000000..a622c9e27c97--- /dev/null+++ b/nodejs/src/ingestion/heatmaps/pipeline.test.ts@@ -0,0 +1,214 @@+import { Message } from 'node-rdkafka'++import { KafkaProducerWrapper } from '~/kafka/producer'+import { createTestTeam } from '~/tests/helpers/team'+import { EventIngestionRestrictionManager } from '~/utils/event-ingestion-restrictions'+import { parseJSON } from '~/utils/json-parse'+import { PromiseScheduler } from '~/utils/promise-scheduler'+import { TeamManager } from '~/utils/team-manager'+import { UUIDT } from '~/utils/utils'++import { EventFilterManager } from '../common/event-filters'+import { APP_METRICS_OUTPUT, DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT } from '../common/outputs'+import { CookielessManager } from '../cookieless/cookieless-manager'+import { IngestionOutputs } from '../outputs/ingestion-outputs'+import { SingleIngestionOutput } from '../outputs/single-ingestion-output'+import { createOkContext } from '../pipelines/helpers'+import { drop, ok } from '../pipelines/results'+import { HEATMAPS_OUTPUT } from './outputs'+import { HeatmapsPipelineConfig, createHeatmapsPipeline } from './pipeline'++jest.mock('~/utils/logger', () => ({+ logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },+}))++const HEATMAPS_TOPIC = 'clickhouse_heatmap_events_test'+const DLQ_TOPIC = 'events_plugin_ingestion_dlq_test'++describe('HeatmapsPipeline', () => {+ let mockKafkaProducer: jest.Mocked<KafkaProducerWrapper>+ let mockTeamManager: jest.Mocked<TeamManager>+ let mockEventIngestionRestrictionManager: jest.Mocked<EventIngestionRestrictionManager>+ let mockEventFilterManager: jest.Mocked<EventFilterManager>+ let mockCookielessManager: jest.Mocked<CookielessManager>+ let promiseScheduler: PromiseScheduler+ let config: HeatmapsPipelineConfig++ const team = createTestTeam({ id: 123, api_token: 'token-123', heatmaps_opt_in: true })++ const heatmapProperties = {+ $session_id: 'session-1',+ $viewport_width: 1024,+ $viewport_height: 768,+ $current_url: 'http://localhost:3000/',+ $heatmap_data: {+ 'http://localhost:3000/': [{ x: 100, y: 200, target_fixed: false, type: 'click' }],+ },+ }++ const createMessage = (event: string, properties: Record<string, any> = heatmapProperties): Message => {+ const distinctId = 'user-1'+ const eventData = {+ event,+ distinct_id: distinctId,+ uuid: new UUIDT().toString(),+ timestamp: '2024-01-01T00:00:00Z',+ 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: 'heatmaps_ingestion',+ partition: 0,+ offset: 0,+ size: 0,+ key: Buffer.from(distinctId),+ } as Message+ }++ const runPipeline = async (messages: Message[]): Promise<void> => {+ const pipeline = createHeatmapsPipeline(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 heatmapsProducedFor = (): any[] =>+ mockKafkaProducer.queueMessages.mock.calls+ .map((call) => call[0])+ .filter((arg: any) => arg.topic === HEATMAPS_TOPIC)+ .flatMap((arg: any) => arg.messages.map((m: { value: Buffer }) => parseJSON(m.value.toString())))++ const dlqProducedFor = (): any[] =>+ mockKafkaProducer.produce.mock.calls.map((call) => call[0]).filter((arg: any) => arg.topic === DLQ_TOPIC)++ 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),+ } as unknown as jest.Mocked<EventFilterManager>++ // Passthrough by default: events round-trip unchanged. The apply step reads `.value.event`+ // from each result, so returning `ok(e)` leaves the distinct id untouched.+ mockCookielessManager = {+ doBatch: jest.fn().mockImplementation((events: any[]) => Promise.resolve(events.map((e) => ok(e)))),+ } as unknown as jest.Mocked<CookielessManager>++ promiseScheduler = new PromiseScheduler()++ config = {+ outputs: new IngestionOutputs({+ [HEATMAPS_OUTPUT]: new SingleIngestionOutput(+ HEATMAPS_OUTPUT,+ HEATMAPS_TOPIC,+ mockKafkaProducer,+ 'test'+ ),+ [DLQ_OUTPUT]: new SingleIngestionOutput(DLQ_OUTPUT, DLQ_TOPIC, mockKafkaProducer, 'test'),+ [INGESTION_WARNINGS_OUTPUT]: new SingleIngestionOutput(+ INGESTION_WARNINGS_OUTPUT,+ 'clickhouse_ingestion_warnings_test',+ mockKafkaProducer,+ 'test'+ ),+ [APP_METRICS_OUTPUT]: new SingleIngestionOutput(+ APP_METRICS_OUTPUT,+ 'clickhouse_app_metrics2_test',+ mockKafkaProducer,+ 'test'+ ),+ }),+ teamManager: mockTeamManager,+ eventIngestionRestrictionManager: mockEventIngestionRestrictionManager,+ eventFilterManager: mockEventFilterManager,+ cookielessManager: mockCookielessManager,+ promiseScheduler,+ }+ })++ it('extracts heatmap data from $$heatmap events', async () => {+ await runPipeline([createMessage('$$heatmap')])++ const heatmaps = heatmapsProducedFor()+ expect(heatmaps).toHaveLength(1)+ expect(heatmaps[0].type).toBe('click')+ expect(heatmaps[0].session_id).toBe('session-1')+ expect(dlqProducedFor()).toHaveLength(0)+ })++ it('extracts heatmaps using the cookieless-rewritten distinct id', async () => {+ // Cookieless events arrive with a sentinel distinct id; the cookieless step rewrites it to a+ // deterministic hash, which extraction must use.+ mockCookielessManager.doBatch.mockImplementation((events: any[]) =>+ Promise.resolve(events.map((e) => ok({ ...e, event: { ...e.event, distinct_id: 'hashed-cookieless-id' } })))+ )++ await runPipeline([createMessage('$$heatmap')])++ const heatmaps = heatmapsProducedFor()+ expect(heatmaps).toHaveLength(1)+ expect(heatmaps[0].distinct_id).toBe('hashed-cookieless-id')+ expect(mockCookielessManager.doBatch).toHaveBeenCalledTimes(1)+ })++ it('drops $$heatmap events that cookieless processing rejects', async () => {+ mockCookielessManager.doBatch.mockImplementation((events: any[]) =>+ Promise.resolve(events.map(() => drop('cookieless_team_disabled')))+ )++ await runPipeline([createMessage('$$heatmap')])++ expect(heatmapsProducedFor()).toHaveLength(0)+ expect(dlqProducedFor()).toHaveLength(0)+ })++ it.each(['$pageview', '$autocapture', '$identify', '$exception', '$$client_ingestion_warning', 'custom_event'])(+ 'DLQs %s events instead of processing them as heatmaps',+ async (eventName) => {+ await runPipeline([createMessage(eventName)])++ expect(dlqProducedFor()).toHaveLength(1)+ expect(heatmapsProducedFor()).toHaveLength(0)+ }+ )++ it('drops $$heatmap events when the team has opted out', async () => {+ const optedOutTeam = createTestTeam({ id: 456, api_token: 'token-456', heatmaps_opt_in: false })+ mockTeamManager.getTeamByToken.mockResolvedValue(optedOutTeam)++ await runPipeline([createMessage('$$heatmap')])++ // Opt-out is a drop, not a DLQ — nothing is produced anywhere.+ expect(heatmapsProducedFor()).toHaveLength(0)+ expect(dlqProducedFor()).toHaveLength(0)+ })+})diff --git a/nodejs/src/ingestion/heatmaps/pipeline.ts b/nodejs/src/ingestion/heatmaps/pipeline.tsnew file mode 100644index 000000000000..1bea3a256848--- /dev/null+++ b/nodejs/src/ingestion/heatmaps/pipeline.ts@@ -0,0 +1,125 @@+import { Message } from 'node-rdkafka'++import { EventIngestionRestrictionManager } from '../../utils/event-ingestion-restrictions'+import { PromiseScheduler } from '../../utils/promise-scheduler'+import { TeamManager } from '../../utils/team-manager'+import { EventFilterManager } from '../common/event-filters'+import { AppMetricsOutput, DlqOutput, IngestionWarningsOutput } from '../common/outputs'+import { createAllowEventsStep } from '../common/steps/allow-events'+import {+ EventFiltersBatchContext,+ createApplyEventFiltersStep,+ createEventFiltersBatchAppMetricsBeforeBatchStep,+ createFlushEventFiltersBatchAppMetricsStep,+} from '../common/steps/event-filters-steps'+import { addTeamToContext } from '../common/subpipelines/helpers'+import { CookielessManager } from '../cookieless/cookieless-manager'+import {+ createApplyCookielessProcessingStep,+ createParseHeadersStep,+ createParseKafkaMessageStep,+ createResolveTeamStep,+ createValidateEventMetadataStep,+ createValidateEventPropertiesStep,+ createValidateHistoricalMigrationStep,+} from '../event-preprocessing'+import { createApplyBasicEventRestrictionsStep } from '../event-preprocessing/apply-event-restrictions'+import { createDropOldEventsStep } from '../event-processing/drop-old-events-step'+import { createNormalizeEventStep } from '../event-processing/normalize-event-step'+import { createPrepareEventStep } from '../event-processing/prepare-event-step'+import { IngestionOutputs } from '../outputs/ingestion-outputs'+import { newBatchingPipeline } from '../pipelines/builders'+import { PipelineConfig } from '../pipelines/result-handling-pipeline'+import { createCheckHeatmapOptInStep } from './check-heatmap-opt-in-step'+import { createDisablePersonProcessingStep } from './disable-person-processing-step'+import { createExtractHeatmapDataStep } from './extract-heatmap-data-step'+import { HeatmapsOutput } from './outputs'+import { createSkipEmitEventStep } from './skip-emit-event-step'++export interface HeatmapsPipelineConfig {+ outputs: IngestionOutputs<HeatmapsOutput | IngestionWarningsOutput | DlqOutput | AppMetricsOutput>+ teamManager: TeamManager+ // The managers come from a started `Lifecycle`'s service map, where+ // `start` and `stop` are stripped from the type — the pipeline only+ // needs their business methods.+ eventIngestionRestrictionManager: EventIngestionRestrictionManager+ eventFilterManager: EventFilterManager+ cookielessManager: CookielessManager+ promiseScheduler: PromiseScheduler+}++interface HeatmapsPipelineInput {+ message: Message+}++interface HeatmapsPipelineContext {+ message: Message+}++export function createHeatmapsPipeline<TInput extends HeatmapsPipelineInput, TContext extends HeatmapsPipelineContext>(+ config: HeatmapsPipelineConfig+) {+ const {+ outputs,+ teamManager,+ eventIngestionRestrictionManager,+ eventFilterManager,+ cookielessManager,+ promiseScheduler,+ } = config++ const pipelineConfig: PipelineConfig = {+ outputs,+ promiseScheduler,+ }++ return newBatchingPipeline<TInput, void, TContext, EventFiltersBatchContext, TContext>(+ (beforeBatch) => beforeBatch.pipe(createEventFiltersBatchAppMetricsBeforeBatchStep(outputs)),+ (batch) =>+ batch+ .messageAware((b) =>+ b+ .sequentially((b) =>+ b+ .pipe(createParseHeadersStep())+ .pipe(createAllowEventsStep(['$$heatmap']))+ .pipe(createApplyBasicEventRestrictionsStep(eventIngestionRestrictionManager))+ .pipe(createParseKafkaMessageStep())+ .pipe(createResolveTeamStep(teamManager))+ .pipe(createValidateHistoricalMigrationStep())+ )+ .filterMap(addTeamToContext, (b) =>+ b+ .teamAware((b) =>+ b+ .sequentially((b) =>+ b+ .pipe(createValidateEventMetadataStep())+ .pipe(createValidateEventPropertiesStep())+ .pipe(createApplyEventFiltersStep(eventFilterManager))+ .pipe(createDropOldEventsStep())+ )+ // Cookieless events arrive with a sentinel distinct id; rewrite it to the+ // deterministic server-side hash (and derive the session) before extraction,+ // which keys heatmaps on distinct id and session id.+ .gather()+ .pipeBatch(createApplyCookielessProcessingStep(cookielessManager))+ .sequentially((b) =>+ b+ .pipe(createCheckHeatmapOptInStep())+ .pipe(createDisablePersonProcessingStep())+ .pipe(createNormalizeEventStep())+ .pipe(createPrepareEventStep())+ .pipe(createExtractHeatmapDataStep(outputs))+ .pipe(createSkipEmitEventStep())+ )+ )+ .handleIngestionWarnings(outputs)+ )+ )+ .handleResults(pipelineConfig)+ .handleSideEffects(promiseScheduler, { await: false }),+ (afterBatch) => afterBatch.pipe(createFlushEventFiltersBatchAppMetricsStep()),+ { concurrentBatches: 1 }+ )+}diff --git a/nodejs/src/ingestion/event-processing/skip-emit-event-step.ts b/nodejs/src/ingestion/heatmaps/skip-emit-event-step.tssimilarity index 100%rename from nodejs/src/ingestion/event-processing/skip-emit-event-step.tsrename to nodejs/src/ingestion/heatmaps/skip-emit-event-step.tsdiff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.tsindex 670285395b66..639b14cac0b5 100644--- a/nodejs/src/ingestion/ingestion-consumer.ts+++ b/nodejs/src/ingestion/ingestion-consumer.ts@@ -36,14 +36,7 @@ import {JoinedIngestionPipelineInput,createJoinedIngestionPipeline,} from './analytics'-import {- AiEventOutput,- AsyncOutput,- EventOutput,- HeatmapsOutput,- PersonDistinctIdsOutput,- PersonsOutput,-} from './analytics/outputs'+import { AiEventOutput, AsyncOutput, EventOutput, PersonDistinctIdsOutput, PersonsOutput } from './analytics/outputs'import { EventFilterManager, EventFilterManagerComponent } from './common/event-filters'import {AppMetricsOutput,@@ -73,7 +66,6 @@ export interface IngestionConsumerDeps {outputs: IngestionOutputs<| EventOutput| AiEventOutput- | HeatmapsOutput| IngestionWarningsOutput| DlqOutput| OverflowOutputdiff --git a/nodejs/src/ingestion/ingestion-e2e.test.ts b/nodejs/src/ingestion/ingestion-e2e.test.tsindex e59d49618785..4aee800b7b6b 100644--- a/nodejs/src/ingestion/ingestion-e2e.test.ts+++ b/nodejs/src/ingestion/ingestion-e2e.test.ts@@ -4598,34 +4598,6 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:})})- testWithTeamIngester(- 'should drop $$heatmap events when team.heatmaps_opt_in=false',- { teamOverrides: { heatmaps_opt_in: false } },- async ({ ingester, team, kafkaProducer, token }) => {- const distinctId = new UUIDT().toString()- await ingester.handleKafkaBatch(- createKafkaMessages(- [- new EventBuilder(team, distinctId)- .withEvent('$$heatmap')- .withProperties({- $heatmap_data: {- 'http://localhost:3000/': [- { x: 100, y: 200, target_fixed: false, type: 'click' },- ],- },- })- .build(),- ],- token- )- )-- await waitForKafkaMessages(kafkaProducer)- const events = await fetchEvents(clickhouse, team.id)- expect(events.length).toBe(0)- }- )testWithTeamIngester('should route $ai_generation events through AI subpipeline with full enrichment',diff --git a/nodejs/src/ingestion/ingestion-testing-consumer.test.ts b/nodejs/src/ingestion/ingestion-testing-consumer.test.tsdeleted file mode 100644index 45dae464c386..000000000000--- a/nodejs/src/ingestion/ingestion-testing-consumer.test.ts+++ /dev/null@@ -1,408 +0,0 @@-import { mockProducer, mockProducerObserver } from '~/tests/helpers/mocks/producer.mock'--import { DateTime } from 'luxon'-import { Message } from 'node-rdkafka'--import { forSnapshot } from '~/tests/helpers/snapshots'-import { createTeam, getFirstTeam, getTeam, resetTestDatabase } from '~/tests/helpers/sql'--import { Hub, PipelineEvent, Team } from '../../src/types'-import { closeHub, createHub } from '../../src/utils/db/hub'-import { UUIDT } from '../utils/utils'-import { IngestionTestingConsumer } from './ingestion-testing-consumer'--const DEFAULT_TEST_TIMEOUT = 5000-jest.setTimeout(DEFAULT_TEST_TIMEOUT)--jest.mock('../utils/posthog', () => {- const original = jest.requireActual('../utils/posthog')- return {- ...original,- captureException: jest.fn(),- }-})--// Mock the IngestionWarningLimiter to always allow warnings (prevents rate limiting between tests)-jest.mock('../utils/token-bucket', () => {- const mockConsume = jest.fn().mockReturnValue(true)- return {- ...jest.requireActual('../utils/token-bucket'),- IngestionWarningLimiter: {- consume: mockConsume,- },- }-})--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: '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('IngestionTestingConsumer', () => {- let ingester: IngestionTestingConsumer- let hub: Hub- let team: Team- let team2: Team- let fixedTime: DateTime-- const createIngestionTestingConsumer = async (- hub: Hub,- overrides?: ConstructorParameters<typeof IngestionTestingConsumer>[2]- ) => {- const ingester = new IngestionTestingConsumer(hub, { ...hub, kafkaProducer: mockProducer }, overrides)- // NOTE: We don't actually use kafka so we skip instantiation for faster tests- ingester['kafkaConsumer'] = {- connect: jest.fn(),- disconnect: jest.fn(),- isHealthy: jest.fn(),- } as any- await ingester.start()- return ingester- }-- 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: '$pageview',- ...event,- properties: {- $current_url: 'http://localhost:8000',- ...(event?.properties || {}),- },- })-- const createKafkaMessages = (events: PipelineEvent[], token?: string): Message[] => {- return events.map((event) => createKafkaMessage(event, token ?? team.api_token))- }-- 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- await resetTestDatabase()- hub = await createHub()-- team = await getFirstTeam(hub.postgres)- const team2Id = await createTeam(hub.postgres, team.organization_id, 'THIS IS NOT A TOKEN FOR TEAM 3')- team2 = (await getTeam(hub.postgres, team2Id))!-- ingester = await createIngestionTestingConsumer(hub)- })-- afterEach(async () => {- await ingester.stop()- await closeHub(hub)- })-- afterAll(() => {- jest.useRealTimers()- })-- describe('general', () => {- it('should have the correct config', () => {- expect(ingester['name']).toMatchInlineSnapshot(`"ingestion-testing-consumer-events_plugin_ingestion_test"`)- expect(ingester['groupId']).toMatchInlineSnapshot(`"events-ingestion-consumer"`)- expect(ingester['topic']).toMatchInlineSnapshot(`"events_plugin_ingestion_test"`)- expect(ingester['dlqTopic']).toMatchInlineSnapshot(`"events_plugin_ingestion_dlq_test"`)- })-- it('should process a standard event', async () => {- await ingester.handleKafkaBatch(createKafkaMessages([createEvent()]))-- expect(forSnapshot(mockProducerObserver.getProducedKafkaMessages())).toMatchSnapshot()- })-- it('should process multiple events', async () => {- const events = [- createEvent({ distinct_id: 'user-1' }),- createEvent({ distinct_id: 'user-2' }),- createEvent({ distinct_id: 'user-1', event: '$identify' }),- ]- await ingester.handleKafkaBatch(createKafkaMessages(events))-- const producedMessages =- mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')- expect(producedMessages).toHaveLength(3)- })-- it('should not produce person-related kafka messages', async () => {- // Send an event with $set properties that would normally trigger person updates- const events = [- createEvent({- properties: {- $current_url: 'http://localhost:8000',- $set: { email: '[email protected]' },- $set_once: { first_seen: '2025-01-01' },- },- }),- ]- await ingester.handleKafkaBatch(createKafkaMessages(events))-- const allMessages = mockProducerObserver.getProducedKafkaMessages()-- // Should have event messages but NO person messages- const personMessages = allMessages.filter(- (m) =>- m.topic === 'clickhouse_person_test' ||- m.topic === 'clickhouse_person_distinct_id2_test' ||- m.topic === 'clickhouse_person_unique_id_test'- )- expect(personMessages).toHaveLength(0)-- // Should still produce the event itself- const eventMessages = allMessages.filter((m) => m.topic === 'clickhouse_events_json_test')- expect(eventMessages).toHaveLength(1)- })-- it('should not produce group-related kafka messages for $groupidentify', async () => {- const events = [- createEvent({- event: '$groupidentify',- properties: {- $group_type: 'company',- $group_key: 'posthog',- $group_set: { name: 'PostHog' },- },- }),- ]- await ingester.handleKafkaBatch(createKafkaMessages(events))-- const allMessages = mockProducerObserver.getProducedKafkaMessages()-- // Should NOT produce group messages- const groupMessages = allMessages.filter((m) => m.topic === 'clickhouse_groups_test')- expect(groupMessages).toHaveLength(0)-- // Should still produce the event itself- const eventMessages = allMessages.filter((m) => m.topic === 'clickhouse_events_json_test')- expect(eventMessages).toHaveLength(1)- })-- it('should set processPerson to false in produced events', async () => {- await ingester.handleKafkaBatch(createKafkaMessages([createEvent()]))-- const eventMessages = mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')- expect(eventMessages).toHaveLength(1)-- const eventData = eventMessages[0].value- expect(eventData.person_mode).toBe('propertyless')- })-- it('should use a deterministic fake person uuid', async () => {- // Send two events for the same user- const events = [createEvent({ distinct_id: 'user-1' }), createEvent({ distinct_id: 'user-1' })]- await ingester.handleKafkaBatch(createKafkaMessages(events))-- const eventMessages = mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')- expect(eventMessages).toHaveLength(2)-- // Both events should have the same person_id (deterministic from team_id + distinct_id)- expect(eventMessages[0].value.person_id).toBe(eventMessages[1].value.person_id)- })-- it('should drop events with invalid token', async () => {- await ingester.handleKafkaBatch(createKafkaMessages([createEvent()], 'invalid-token'))-- const eventMessages = mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')- expect(eventMessages).toHaveLength(0)- })-- it('should process events from multiple teams', async () => {- const events1 = createKafkaMessages([createEvent()], team.api_token)- const events2 = createKafkaMessages([createEvent()], team2.api_token)- await ingester.handleKafkaBatch([...events1, ...events2])-- const eventMessages = mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')- expect(eventMessages).toHaveLength(2)-- const teamIds = eventMessages.map((m) => m.value.team_id)- expect(teamIds).toContain(team.id)- expect(teamIds).toContain(team2.id)- })- })-- describe('heatmap subpipeline', () => {- it('should produce heatmap events to the heatmaps topic', async () => {- const events = [- createEvent({- event: '$$heatmap',- properties: {- $viewport_height: 800,- $viewport_width: 1200,- $session_id: 'session-1',- $heatmap_data: {- 'http://localhost:3000/': [- {- x: 1020,- y: 363,- target_fixed: false,- type: 'click',- },- ],- },- },- }),- ]- await ingester.handleKafkaBatch(createKafkaMessages(events))-- const allMessages = mockProducerObserver.getProducedKafkaMessages()- const heatmapMessages = allMessages.filter((m) => m.topic === 'clickhouse_heatmap_events_test')- expect(heatmapMessages).toHaveLength(1)-- // Should NOT produce to the regular events topic- const eventMessages = allMessages.filter((m) => m.topic === 'clickhouse_events_json_test')- expect(eventMessages).toHaveLength(0)- })-- it('should not produce person messages for heatmap events', async () => {- const events = [- createEvent({- event: '$$heatmap',- properties: {- $viewport_height: 800,- $viewport_width: 1200,- $session_id: 'session-1',- $heatmap_data: {- 'http://localhost:3000/': [{ x: 100, y: 200, target_fixed: false, type: 'click' }],- },- },- }),- ]- await ingester.handleKafkaBatch(createKafkaMessages(events))-- const allMessages = mockProducerObserver.getProducedKafkaMessages()- const personMessages = allMessages.filter(- (m) => m.topic === 'clickhouse_person_test' || m.topic === 'clickhouse_person_distinct_id2_test'- )- expect(personMessages).toHaveLength(0)- })- })-- describe('AI event subpipeline', () => {- it('should process $ai_generation events', async () => {- const events = [- createEvent({- event: '$ai_generation',- properties: {- $ai_model: 'gpt-4',- $ai_provider: 'openai',- $ai_input_tokens: 100,- $ai_output_tokens: 50,- $ai_input: 'What is the meaning of life?',- $ai_output: 'The meaning of life is 42.',- },- }),- ]- await ingester.handleKafkaBatch(createKafkaMessages(events))-- const eventMessages = mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')- expect(eventMessages).toHaveLength(1)- expect(eventMessages[0].value.event).toBe('$ai_generation')- })-- it('should not produce person messages for AI events', async () => {- const events = [- createEvent({- event: '$ai_generation',- properties: {- $ai_model: 'gpt-4',- $ai_provider: 'openai',- },- }),- ]- await ingester.handleKafkaBatch(createKafkaMessages(events))-- const allMessages = mockProducerObserver.getProducedKafkaMessages()- const personMessages = allMessages.filter(- (m) => m.topic === 'clickhouse_person_test' || m.topic === 'clickhouse_person_distinct_id2_test'- )- expect(personMessages).toHaveLength(0)- })- })-- describe('all subpipelines in one batch', () => {- it('should route different event types to their correct subpipelines', async () => {- const events = [- createEvent({ event: '$pageview', distinct_id: 'user-1' }),- createEvent({- event: '$$heatmap',- distinct_id: 'user-2',- properties: {- $viewport_height: 800,- $viewport_width: 1200,- $session_id: 'session-1',- $heatmap_data: {- 'http://localhost:3000/': [{ x: 10, y: 20, target_fixed: false, type: 'click' }],- },- },- }),- createEvent({- event: '$ai_generation',- distinct_id: 'user-3',- properties: {- $ai_model: 'gpt-4',- $ai_provider: 'openai',- $ai_input: 'hello',- $ai_output: 'world',- },- }),- ]- await ingester.handleKafkaBatch(createKafkaMessages(events))-- const allMessages = mockProducerObserver.getProducedKafkaMessages()-- // Regular event + AI event → clickhouse_events_json (no AI splitting in testing pipeline)- const eventMessages = allMessages.filter((m) => m.topic === 'clickhouse_events_json_test')- expect(eventMessages).toHaveLength(2) // pageview + ai_generation-- // Heatmap → clickhouse_heatmap_events- const heatmapMessages = allMessages.filter((m) => m.topic === 'clickhouse_heatmap_events_test')- expect(heatmapMessages).toHaveLength(1)-- // No person messages from any subpipeline- const personMessages = allMessages.filter(- (m) => m.topic === 'clickhouse_person_test' || m.topic === 'clickhouse_person_distinct_id2_test'- )- expect(personMessages).toHaveLength(0)- })- })-})diff --git a/nodejs/src/ingestion/ingestion-testing-consumer.ts b/nodejs/src/ingestion/ingestion-testing-consumer.tsdeleted file mode 100644index 4c0c3c5d9c9c..000000000000--- a/nodejs/src/ingestion/ingestion-testing-consumer.ts+++ /dev/null@@ -1,221 +0,0 @@-import { Message } from 'node-rdkafka'--import { instrumentFn } from '~/common/tracing/tracing-utils'--import { KAFKA_INGESTION_WARNINGS } from '../config/kafka-topics'-import { KafkaConsumerInterface, createKafkaConsumer } from '../kafka/consumer'-import { KafkaProducerWrapper } from '../kafka/producer'-import { HealthCheckResult, HealthCheckResultError, PluginServerService, PluginsServerConfig } from '../types'-import { logger } from '../utils/logger'-import { PromiseScheduler } from '../utils/promise-scheduler'-import { TeamManager } from '../utils/team-manager'-import { EVENTS_OUTPUT, HEATMAPS_OUTPUT } from './analytics/outputs'-import {- TestingJoinedIngestionPipelineConfig,- TestingJoinedIngestionPipelineContext,- TestingJoinedIngestionPipelineDeps,- TestingJoinedIngestionPipelineInput,- createTestingJoinedIngestionPipeline,-} from './analytics/testing-joined-ingestion-pipeline'-import { DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT } from './common/outputs'-import { latestOffsetTimestampGauge } from './ingestion-consumer'-import { IngestionOutputs } from './outputs/ingestion-outputs'-import { SingleIngestionOutput } from './outputs/single-ingestion-output'-import { BatchPipeline } from './pipelines/batch-pipeline.interface'-import { newBatchPipelineBuilder } from './pipelines/builders'-import { createOkContext } from './pipelines/helpers'--export type IngestionTestingConsumerFullConfig = Pick<- PluginsServerConfig,- | 'KAFKA_CLIENT_RACK'- | 'INGESTION_CONSUMER_CONSUME_TOPIC'- | 'INGESTION_CONSUMER_GROUP_ID'- | 'INGESTION_CONSUMER_DLQ_TOPIC'- | 'CLICKHOUSE_JSON_EVENTS_KAFKA_TOPIC'- | 'CLICKHOUSE_HEATMAPS_KAFKA_TOPIC'- | 'KAFKA_BATCH_START_LOGGING_ENABLED'->--export interface IngestionTestingConsumerDeps {- /** Single producer for all output (events, DLQ, internal messages) — writes to WarpStream */- kafkaProducer: KafkaProducerWrapper- teamManager: TeamManager-}--export class IngestionTestingConsumer {- protected name = 'ingestion-testing-consumer'- protected groupId: string- protected topic: string- protected dlqTopic: string- protected kafkaConsumer: KafkaConsumerInterface- isStopping = false- protected kafkaProducer?: KafkaProducerWrapper- public readonly promiseScheduler = new PromiseScheduler()-- private joinedPipeline!: BatchPipeline<- TestingJoinedIngestionPipelineInput,- void,- TestingJoinedIngestionPipelineContext,- TestingJoinedIngestionPipelineContext- >-- constructor(- private config: IngestionTestingConsumerFullConfig,- private deps: IngestionTestingConsumerDeps,- overrides: Partial<- Pick<- PluginsServerConfig,- 'INGESTION_CONSUMER_CONSUME_TOPIC' | 'INGESTION_CONSUMER_GROUP_ID' | 'INGESTION_CONSUMER_DLQ_TOPIC'- >- > = {}- ) {- this.groupId = overrides.INGESTION_CONSUMER_GROUP_ID ?? config.INGESTION_CONSUMER_GROUP_ID- this.topic = overrides.INGESTION_CONSUMER_CONSUME_TOPIC ?? config.INGESTION_CONSUMER_CONSUME_TOPIC- this.dlqTopic = overrides.INGESTION_CONSUMER_DLQ_TOPIC ?? config.INGESTION_CONSUMER_DLQ_TOPIC-- this.name = `ingestion-testing-consumer-${this.topic}`-- this.kafkaConsumer = createKafkaConsumer({- groupId: this.groupId,- topic: this.topic,- })-- // Single WarpStream producer used for all output (events, DLQ, internal messages)- this.kafkaProducer = this.deps.kafkaProducer- }-- public get service(): PluginServerService {- return {- id: this.name,- onShutdown: async () => await this.stop(),- healthcheck: () => this.isHealthy() ?? false,- }- }-- public async start(): Promise<void> {- const outputs = new IngestionOutputs({- [EVENTS_OUTPUT]: new SingleIngestionOutput(- EVENTS_OUTPUT,- this.config.CLICKHOUSE_JSON_EVENTS_KAFKA_TOPIC,- this.kafkaProducer!,- 'default'- ),- [HEATMAPS_OUTPUT]: new SingleIngestionOutput(- HEATMAPS_OUTPUT,- this.config.CLICKHOUSE_HEATMAPS_KAFKA_TOPIC,- this.kafkaProducer!,- 'default'- ),- [INGESTION_WARNINGS_OUTPUT]: new SingleIngestionOutput(- INGESTION_WARNINGS_OUTPUT,- KAFKA_INGESTION_WARNINGS,- this.kafkaProducer!,- 'default'- ),- [DLQ_OUTPUT]: new SingleIngestionOutput(DLQ_OUTPUT, this.dlqTopic, this.kafkaProducer!, 'default'),- })-- const joinedPipelineConfig: TestingJoinedIngestionPipelineConfig = {- groupId: this.groupId,- outputs,- }- const joinedPipelineDeps: TestingJoinedIngestionPipelineDeps = {- promiseScheduler: this.promiseScheduler,- teamManager: this.deps.teamManager,- }- this.joinedPipeline = createTestingJoinedIngestionPipeline(- newBatchPipelineBuilder<TestingJoinedIngestionPipelineInput, TestingJoinedIngestionPipelineContext>(),- joinedPipelineConfig,- joinedPipelineDeps- ).build()-- await this.kafkaConsumer.connect(async (messages) => {- return await instrumentFn(- {- key: `ingestionTestingConsumer.handleEachBatch`,- sendException: false,- },- async () => await this.handleKafkaBatch(messages)- )- })- }-- public async stop(): Promise<void> {- logger.info('🔁', `${this.name} - stopping`)- this.isStopping = true-- logger.info('🔁', `${this.name} - stopping batch consumer`)- await this.kafkaConsumer?.disconnect()- logger.info('👍', `${this.name} - stopped!`)- }-- public isHealthy(): HealthCheckResult {- if (!this.kafkaConsumer) {- return new HealthCheckResultError('Kafka consumer not initialized', {})- }- return this.kafkaConsumer.isHealthy()- }-- private runInstrumented<T>(name: string, func: () => Promise<T>): Promise<T> {- return instrumentFn<T>(`ingestionTestingConsumer.${name}`, func)- }-- private logBatchStart(messages: Message[]): void {- const podName = process.env.HOSTNAME || 'unknown'- const partitionEarliestMessages = new Map<number, Message>()- const partitionBatchSizes = new Map<number, number>()-- messages.forEach((message) => {- const existing = partitionEarliestMessages.get(message.partition)- if (!existing || message.offset < existing.offset) {- partitionEarliestMessages.set(message.partition, message)- }- partitionBatchSizes.set(message.partition, (partitionBatchSizes.get(message.partition) || 0) + 1)- })-- const partitionData = Array.from(partitionEarliestMessages.entries()).map(([partition, message]) => ({- partition,- offset: message.offset,- batchSize: partitionBatchSizes.get(partition) || 0,- }))-- logger.info('📖', `KAFKA_BATCH_START: ${this.name}`, {- pod: podName,- totalMessages: messages.length,- partitions: partitionData,- })- }-- public async handleKafkaBatch(messages: Message[]): Promise<{ backgroundTask?: Promise<any> }> {- if (this.config.KAFKA_BATCH_START_LOGGING_ENABLED) {- this.logBatchStart(messages)- }-- await this.runIngestionPipeline(messages)-- for (const message of messages) {- if (message.timestamp) {- latestOffsetTimestampGauge- .labels({ partition: message.partition, topic: message.topic, groupId: this.groupId })- .set(message.timestamp)- }- }-- return {- backgroundTask: this.runInstrumented('awaitScheduledWork', async () => {- await this.promiseScheduler.waitForAll()- }),- }- }-- private async runIngestionPipeline(messages: Message[]): Promise<void> {- const batch = messages.map((message) => createOkContext({ message }, { message }))-- this.joinedPipeline.feed(batch)-- // Drain the pipeline- while ((await this.joinedPipeline.next()) !== null) {- // Continue until all results are processed- }- }-}diff --git a/nodejs/src/servers/ingestion-general-server.ts b/nodejs/src/servers/ingestion-general-server.tsindex 1705ecc68404..823e212b461b 100644--- a/nodejs/src/servers/ingestion-general-server.ts+++ b/nodejs/src/servers/ingestion-general-server.ts@@ -36,15 +36,14 @@ import {RedisConnectionsConfig,getDefaultIngestionOutputsConfig,} from '../ingestion/config'-import { CookielessManager } from '../ingestion/cookieless/cookieless-manager'+import { CookielessManagerComponent } from '../ingestion/cookieless/cookieless-manager'+import { createHeatmapsConsumer } from '../ingestion/heatmaps'import { IngestionConsumer, IngestionConsumerDeps } from '../ingestion/ingestion-consumer'-import { IngestionTestingConsumer } from '../ingestion/ingestion-testing-consumer'import { buildGroupRepository, buildPersonRepository, createPersonHogClient } from '../ingestion/personhog'-import { KafkaProducerWrapper } from '../kafka/producer'import { PluginServerService, RedisPool } from '../types'import { ServerCommands } from '../utils/commands'import { PostgresRouter, PostgresRouterComponent } from '../utils/db/postgres'-import { RedisPoolComponent, createRedisPoolFromConfig } from '../utils/db/redis'+import { RedisPoolComponent } from '../utils/db/redis'import { GeoIPService } from '../utils/geoip'import { logger } from '../utils/logger'import { PubSub } from '../utils/pubsub'@@ -100,8 +99,6 @@ export class IngestionGeneralServer implements NodeServer {private postgres?: PostgresRouterprivate redisPool?: RedisPool- private cookielessRedisPool?: RedisPool- private cookielessManager?: CookielessManagerprivate pubsub?: PubSubprivate stopSharedServices?: () => Promise<void>@@ -147,29 +144,41 @@ export class IngestionGeneralServer implements NodeServer {poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,}))+ // Cookieless Redis is a separate pool, shared by every consumer that runs cookieless+ // processing (analytics, heatmaps, …).+ .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)))- // `teamManager` is built inside the extension via its component so- // it picks up `postgres` from the started infra scope's container- // and is owned by that scope. The server extracts it from the- // started container to pass on to CDP services etc.+ // Services are built off the started infra scope (postgres, redis pools, kafka). They're+ // owned by this scope, so consumers can `Scope.extend` off it to read shared services like+ // the team manager and cookieless manager without taking ownership of their lifecycle.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: { retryIntervalMs: 250, retryJitterMs: 250, maxElapsedMs: 5000 },- })- )+ 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: { retryIntervalMs: 250, retryJitterMs: 250, maxElapsedMs: 5000 },+ })+ )+ .add('cookielessManager', new CookielessManagerComponent(this.config, container.cookielessRedisPool)))const sharedServices = await sharedServicesScope.start()this.postgres = sharedServices.container.postgresthis.redisPool = sharedServices.container.redisPoolconst teamManager = sharedServices.container.teamManager+ const cookielessManager = sharedServices.container.cookielessManagerthis.stopSharedServices = sharedServices.stoplogger.info('👍', 'Postgres Router ready')logger.info('👍', 'Ingestion Redis ready')@@ -208,117 +217,112 @@ export class IngestionGeneralServer implements NodeServer {const integrationManager = new IntegrationManagerService(this.pubsub, this.postgres, encryptedFields)// 3. Ingestion-specific services- 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)const groupTypeManager = new GroupTypeManager(groupRepository, teamManager)const serviceLoaders: (() => Promise<PluginServerService>)[] = []- const isTestingMode = this.config.PLUGIN_SERVER_MODE === PluginServerMode.ingestion_v2_testingconst isCombinedMode = this.config.PLUGIN_SERVER_MODE === PluginServerMode.ingestion_v2_combined- if (isTestingMode) {+ // Producer registry is owned by `sharedInfraScope`; the+ // server reads it back from the started services. Outputs is+ // a typed view over it — built once here for analytics, and+ // separately by each consumer factory as needed.+ const ingestionProducerRegistry = sharedServices.container.producerRegistry+ const ingestionOutputs = createOutputsRegistry().build(ingestionProducerRegistry, this.config)+ const clickhouseGroupRepository = new ClickhouseGroupRepository(ingestionOutputs)++ const hogTransformerDeps: HogTransformerServiceDeps = {+ geoipService,+ postgres: this.postgres,+ pubSub: this.pubsub,+ encryptedFields,+ integrationManager,+ monitoringOutputs: ingestionOutputs,+ teamManager,+ }++ const ingestionDeps: IngestionConsumerDeps = {+ postgres: this.postgres,+ redisPool: this.redisPool,+ outputs: ingestionOutputs,+ teamManager,+ groupTypeManager,+ groupRepository,+ clickhouseGroupRepository,+ personRepository,+ cookielessManager,+ hogTransformer: createHogTransformerService(this.config, hogTransformerDeps),+ }++ const startClientWarnings = (override?: { topic: string; groupId: string }) => {serviceLoaders.push(async () => {- const kafkaWarpStreamProducer = await KafkaProducerWrapper.create(- this.config.KAFKA_CLIENT_RACK,- 'WARPSTREAM_PRODUCER'- )+ const consumerConfig = override+ ? {+ ...this.config,+ INGESTION_CONSUMER_CONSUME_TOPIC: override.topic,+ INGESTION_CONSUMER_GROUP_ID: override.groupId,+ }+ : this.config+ const consumerScope = createClientWarningsConsumer(consumerConfig, sharedServicesScope)+ const { consumer, stop } = await consumerScope.start()+ return ingestionConsumerService(consumer, stop)+ })+ }- const consumer = new IngestionTestingConsumer(this.config, {- kafkaProducer: kafkaWarpStreamProducer,- teamManager,- })- await consumer.start()- return consumer.service+ const startHeatmaps = (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+ const consumerScope = createHeatmapsConsumer(consumerConfig, sharedServicesScope)+ const { consumer, stop } = await consumerScope.start()+ return ingestionConsumerService(consumer, stop)})- } else {- // Producer registry is owned by `sharedInfraScope`; the- // server reads it back from the started services. Outputs is- // a typed view over it — built once here for analytics, and- // separately by each consumer factory as needed.- const ingestionProducerRegistry = sharedServices.container.producerRegistry- const ingestionOutputs = createOutputsRegistry().build(ingestionProducerRegistry, this.config)- const clickhouseGroupRepository = new ClickhouseGroupRepository(ingestionOutputs)-- const hogTransformerDeps: HogTransformerServiceDeps = {- geoipService,- postgres: this.postgres,- pubSub: this.pubsub,- encryptedFields,- integrationManager,- monitoringOutputs: ingestionOutputs,- teamManager,- }+ }- const ingestionDeps: IngestionConsumerDeps = {- postgres: this.postgres,- redisPool: this.redisPool,- outputs: ingestionOutputs,- teamManager,- groupTypeManager,- groupRepository,- clickhouseGroupRepository,- personRepository,- cookielessManager: this.cookielessManager,- hogTransformer: createHogTransformerService(this.config, hogTransformerDeps),- }+ if (isCombinedMode) {+ // Local dev / hobby: run multiple consumers for all ingestion topics in one process+ const consumersOptions = [+ { topic: KAFKA_EVENTS_PLUGIN_INGESTION, group_id: 'clickhouse-ingestion' },+ { topic: KAFKA_EVENTS_PLUGIN_INGESTION_HISTORICAL, group_id: 'clickhouse-ingestion-historical' },+ { topic: KAFKA_EVENTS_PLUGIN_INGESTION_OVERFLOW, group_id: 'clickhouse-ingestion-overflow' },+ ]- const startClientWarnings = (override?: { topic: string; groupId: string }) => {+ for (const consumerOption of consumersOptions) {serviceLoaders.push(async () => {- const consumerConfig = override- ? {- ...this.config,- INGESTION_CONSUMER_CONSUME_TOPIC: override.topic,- INGESTION_CONSUMER_GROUP_ID: override.groupId,- }- : this.config- const consumerScope = createClientWarningsConsumer(consumerConfig, sharedServicesScope)- 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 = [- { topic: KAFKA_EVENTS_PLUGIN_INGESTION, group_id: 'clickhouse-ingestion' },- { topic: KAFKA_EVENTS_PLUGIN_INGESTION_HISTORICAL, group_id: 'clickhouse-ingestion-historical' },- { topic: KAFKA_EVENTS_PLUGIN_INGESTION_OVERFLOW, group_id: 'clickhouse-ingestion-overflow' },- { topic: 'heatmaps_ingestion', group_id: 'heatmaps_ingestion' },- ]-- for (const consumerOption of consumersOptions) {- serviceLoaders.push(async () => {- const consumer = new IngestionConsumer(this.config, ingestionDeps, {- INGESTION_CONSUMER_CONSUME_TOPIC: consumerOption.topic,- INGESTION_CONSUMER_GROUP_ID: consumerOption.group_id,- })- await consumer.start()- return consumer.service+ const consumer = new IngestionConsumer(this.config, ingestionDeps, {+ INGESTION_CONSUMER_CONSUME_TOPIC: consumerOption.topic,+ INGESTION_CONSUMER_GROUP_ID: consumerOption.group_id,})- }-- startClientWarnings({- topic: 'ingestion-clientwarnings-main-1',- groupId: 'ingestion-clientwarnings-main',- })- } else if (this.config.INGESTION_PIPELINE === 'clientwarnings') {- startClientWarnings()- } else {- // Production ingestion-v2: single consumer using config-provided topic- serviceLoaders.push(async () => {- const consumer = new IngestionConsumer(this.config, ingestionDeps)await consumer.start()return consumer.service})}++ startClientWarnings({+ topic: 'ingestion-clientwarnings-main-1',+ groupId: 'ingestion-clientwarnings-main',+ })++ startHeatmaps({+ topic: 'heatmaps_ingestion',+ groupId: 'heatmaps_ingestion',+ })+ } else if (this.config.INGESTION_PIPELINE === 'clientwarnings') {+ startClientWarnings()+ } else if (this.config.INGESTION_PIPELINE === 'heatmaps') {+ startHeatmaps()+ } else {+ // Production ingestion-v2: single consumer using config-provided topic+ serviceLoaders.push(async () => {+ const consumer = new IngestionConsumer(this.config, ingestionDeps)+ await consumer.start()+ return consumer.service+ })}// ServerCommands is always created@@ -335,13 +339,9 @@ export class IngestionGeneralServer implements NodeServer {private getCleanupResources(): CleanupResources {return {kafkaProducers: [],- // `redisPool` and `postgres` are owned by `sharedInfraScope` and- // get torn down by `stopSharedServices()` below. Only- // cookielessRedisPool stays here — it's not on the scope.- redisPools: [this.cookielessRedisPool].filter(Boolean) as RedisPool[],+ redisPools: [],pubsub: this.pubsub,additionalCleanup: async () => {- this.cookielessManager?.shutdown()if (this.stopSharedServices) {await this.stopSharedServices()}diff --git a/nodejs/src/utils/event-ingestion-restrictions/manager.ts b/nodejs/src/utils/event-ingestion-restrictions/manager.tsindex a40c7e17f8ee..ed67aabe61db 100644--- a/nodejs/src/utils/event-ingestion-restrictions/manager.ts+++ b/nodejs/src/utils/event-ingestion-restrictions/manager.ts@@ -7,7 +7,7 @@ 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'+export type IngestionPipeline = 'analytics' | 'session_recordings' | 'errortracking' | 'clientwarnings' | 'heatmaps'const EMPTY_RESTRICTIONS: ReadonlySet<RestrictionType> = new Set()diff --git a/nodejs/src/utils/event-ingestion-restrictions/redis-schema.ts b/nodejs/src/utils/event-ingestion-restrictions/redis-schema.tsindex 1fea72558be2..59f893527495 100644--- a/nodejs/src/utils/event-ingestion-restrictions/redis-schema.ts+++ b/nodejs/src/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 fieldsconst pipelinesSchema = z- .array(z.enum(['analytics', 'session_recordings', 'errortracking', 'clientwarnings']))+ .array(z.enum(['analytics', 'session_recordings', 'errortracking', 'clientwarnings', 'heatmaps'])).optional()// Redis schema v0 (legacy) - single identifier per entry, no version fielddiff --git a/nodejs/tests/helpers/ingestion-e2e.ts b/nodejs/tests/helpers/ingestion-e2e.tsindex d2a82e9777cc..a904c11af142 100644--- a/nodejs/tests/helpers/ingestion-e2e.ts+++ b/nodejs/tests/helpers/ingestion-e2e.ts@@ -134,6 +134,11 @@ export function createKafkaMessage({ token: Buffer.from(token) },{ distinct_id: Buffer.from(event.distinct_id!) },]+ if (event.event) {+ // Capture sets the event name header on every message; pipeline steps that route by event+ // type (allow/deny lists) run before the body is parsed and read it from here.+ headers.push({ event: Buffer.from(event.event) })+ }if (event.timestamp) {const timestampMs = DateTime.fromISO(event.timestamp).toMillis()headers.push({ timestamp: Buffer.from(timestampMs.toString()) })diff --git a/nodejs/tests/helpers/ingestion-outputs.ts b/nodejs/tests/helpers/ingestion-outputs.tsindex 0519bd86adbc..cea662e80c1b 100644--- a/nodejs/tests/helpers/ingestion-outputs.ts+++ b/nodejs/tests/helpers/ingestion-outputs.ts@@ -17,7 +17,6 @@ import {AI_EVENTS_OUTPUT,ASYNC_OUTPUT,EVENTS_OUTPUT,- HEATMAPS_OUTPUT,PERSONS_OUTPUT,PERSON_DISTINCT_IDS_OUTPUT,} from '../../src/ingestion/analytics/outputs'@@ -30,6 +29,7 @@ import {OVERFLOW_OUTPUT,TOPHOG_OUTPUT,} from '../../src/ingestion/common/outputs'+import { HEATMAPS_OUTPUT } from '../../src/ingestion/heatmaps/outputs'import { IngestionOutputs } from '../../src/ingestion/outputs/ingestion-outputs'import { SingleIngestionOutput } from '../../src/ingestion/outputs/single-ingestion-output'import { KafkaProducerWrapper } from '../../src/kafka/producer'diff --git a/nodejs/tests/ingestion-general-server.test.ts b/nodejs/tests/ingestion-general-server.test.tsindex 457ff72bf0b8..0c5fe0aab0a7 100644--- a/nodejs/tests/ingestion-general-server.test.ts+++ b/nodejs/tests/ingestion-general-server.test.ts@@ -1,5 +1,12 @@import { PluginServerMode } from '../src/common/config'+import {+ KAFKA_APP_METRICS_2,+ KAFKA_CLICKHOUSE_HEATMAP_EVENTS,+ KAFKA_EVENTS_PLUGIN_INGESTION_DLQ,+ KAFKA_INGESTION_WARNINGS,+} from '../src/config/kafka-topics'import { IngestionGeneralServer } from '../src/servers/ingestion-general-server'+import { ensureKafkaTopics } from './helpers/kafka'import { resetTestDatabase } from './helpers/sql'jest.setTimeout(20000) // 20 sec timeout - longer indicates an issue@@ -8,6 +15,19 @@ describe('ingestion general server', () => {jest.retryTimes(3) // Flakey due to reliance on kafka/clickhouselet server: IngestionGeneralServer | null = null+ beforeAll(async () => {+ // Combined mode starts the clientwarnings and heatmaps consumers, which verify their output+ // topics exist and fail startup if they don't (unlike the analytics consumer, which only+ // logs). Create those topics so the check is deterministic rather than relying on ambient+ // topics left by other tests.+ await ensureKafkaTopics([+ KAFKA_CLICKHOUSE_HEATMAP_EVENTS,+ KAFKA_INGESTION_WARNINGS,+ KAFKA_EVENTS_PLUGIN_INGESTION_DLQ,+ KAFKA_APP_METRICS_2,+ ])+ })+beforeEach(async () => {jest.spyOn(process, 'exit').mockImplementation()@@ -40,13 +60,4 @@ describe('ingestion general server', () => {await server.start()expect(process.exit).not.toHaveBeenCalledWith(1)})-- it('should not error on startup - ingestion_v2_testing', async () => {- server = new IngestionGeneralServer({- LOG_LEVEL: 'debug',- PLUGIN_SERVER_MODE: PluginServerMode.ingestion_v2_testing,- })- await server.start()- expect(process.exit).not.toHaveBeenCalledWith(1)- })})