Skip to content

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

feat(ingestion): track parse timing and message sizes in tophog (#74239)

Paweł Ledwoń8621139e765a
diff --git a/nodejs/src/ingestion/common/common-ingestion-pipeline.test.ts b/nodejs/src/ingestion/common/common-ingestion-pipeline.test.ts
index 325b0f70adb3..1f047ecb5449 100644
--- a/nodejs/src/ingestion/common/common-ingestion-pipeline.test.ts
+++ b/nodejs/src/ingestion/common/common-ingestion-pipeline.test.ts
@@ -9,11 +9,13 @@ import { PromiseScheduler } from '~/common/utils/promise-scheduler'
import { TeamManager } from '~/common/utils/team-manager'
import { UUIDT } from '~/common/utils/utils'
import { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'
+import { TopHogRegistry, countResult } from '~/ingestion/framework/extensions/tophog'
import { createOkContext } from '~/ingestion/framework/helpers'
import { PipelineResult, dlq, drop, isDropResult, isOkResult, ok, redirect } from '~/ingestion/framework/results'
import { ProcessingStep } from '~/ingestion/framework/steps'
import { PluginEvent } from '~/plugin-scaffold'
import { createTestTeam } from '~/tests/helpers/team'
+import { RecordedTopHogMetric, createRecordingTopHog } from '~/tests/helpers/tophog'
import { EventHeaders, IncomingEvent, Team } from '~/types'
import { CommonIngestionPipelineConfig, newCommonIngestionPipeline } from './common-ingestion-pipeline'
@@ -61,6 +63,8 @@ describe('CommonIngestionPipelineBuilder', () => {
let mockTeamManager: jest.Mocked<TeamManager>
let promiseScheduler: PromiseScheduler
let config: CommonIngestionPipelineConfig<TestRedirectOutput>
+ let topHog: TopHogRegistry
+ let topHogRecords: Map<string, RecordedTopHogMetric[]>
const team = createTestTeam({ id: 42, api_token: 'token-42' })
@@ -177,8 +181,13 @@ describe('CommonIngestionPipelineBuilder', () => {
promiseScheduler = new PromiseScheduler()
+ const recording = createRecordingTopHog()
+ topHog = recording.registry
+ topHogRecords = recording.records
+
config = {
teamManager: mockTeamManager,
+ topHog,
outputs: new IngestionOutputs({
[DLQ_OUTPUT]: new SingleIngestionOutput(DLQ_OUTPUT, DLQ_TOPIC, mockKafkaProducer, 'test'),
[INGESTION_WARNINGS_OUTPUT]: new SingleIngestionOutput(
@@ -737,19 +746,18 @@ describe('CommonIngestionPipelineBuilder', () => {
expect(parseJSON(warnings[0].details).marker).toBe('sub-step')
})
- it('applies the resolveTeam wrap decorator around team resolution', async () => {
- const wrapObserved: string[] = []
+ it('records resolveTeam topHog metrics around team resolution', async () => {
const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
.parseHeaders()
.parseMessage()
.resolveTeam({
- wrap: (step) => async (input) => {
- const result = await step(input)
- wrapObserved.push(
- isOkResult(result) ? `ok:${result.value.team.id}` : `miss:${input.headers.distinct_id}`
- )
- return result
- },
+ topHog: [
+ countResult('teams_resolved', (result, input) =>
+ isOkResult(result)
+ ? { outcome: `ok:${result.value.team.id}` }
+ : { outcome: `miss:${input.headers.distinct_id}` }
+ ),
+ ],
})
.build()
@@ -758,12 +766,31 @@ describe('CommonIngestionPipelineBuilder', () => {
createMessage('user-1', 'test_event', 'unknown-token'),
])
- expect(wrapObserved).toEqual(['ok:42', 'miss:user-1'])
+ expect((topHogRecords.get('teams_resolved') ?? []).map((r) => r.key)).toEqual([
+ { outcome: 'ok:42' },
+ { outcome: 'miss:user-1' },
+ ])
const elements = batches.flatMap((batch) => batch.elements)
expect(isOkResult(elements[0].result)).toBe(true)
expect(isDropResult(elements[1].result)).toBe(true)
})
+ it('records parse timing and message sizes for every parsed message', async () => {
+ const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
+ .parseHeaders()
+ .parseMessage()
+ .resolveTeam()
+ .build()
+
+ await runPipeline(pipeline, [createMessage('user-0')])
+
+ const sizes = topHogRecords.get('message_size_by_token') ?? []
+ expect(sizes).toHaveLength(1)
+ expect(sizes[0].key).toEqual({ token: team.api_token })
+ expect(sizes[0].value).toBeGreaterThan(0)
+ expect(topHogRecords.get('parse_time_ms_by_token')).toHaveLength(1)
+ })
+
it('passes retry options through to chunk steps', async () => {
let attempts = 0
const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
diff --git a/nodejs/src/ingestion/common/common-ingestion-pipeline.ts b/nodejs/src/ingestion/common/common-ingestion-pipeline.ts
index 28146a062feb..f92448c42465 100644
--- a/nodejs/src/ingestion/common/common-ingestion-pipeline.ts
+++ b/nodejs/src/ingestion/common/common-ingestion-pipeline.ts
@@ -17,6 +17,7 @@ import { newBatchingPipeline } from '~/ingestion/framework/builders'
import { ChunkPipelineBuilder, GroupProcessingBuilder } from '~/ingestion/framework/builders/chunk-pipeline-builders'
import { PipelineBuilder, StartPipelineBuilder } from '~/ingestion/framework/builders/pipeline-builders'
import { GroupingFunction } from '~/ingestion/framework/concurrently-grouping-chunk-pipeline'
+import { TopHogMetricFactory, TopHogRegistry, createTopHogWrapper } from '~/ingestion/framework/extensions/tophog'
import { FanInFunction, FanOutFunction, FanOutSubContext } from '~/ingestion/framework/fan-out-fan-in-chunk-pipeline'
import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'
import { ok } from '~/ingestion/framework/results'
@@ -25,7 +26,12 @@ import { ProcessingStep } from '~/ingestion/framework/steps'
import { PluginEvent } from '~/plugin-scaffold'
import { EventHeaders, IncomingEvent, Team } from '~/types'
-import { createParseHeadersStep, createParseKafkaMessageStep, createResolveTeamStep } from './steps/event-preprocessing'
+import {
+ createParseHeadersStep,
+ createParseKafkaMessageStep,
+ createResolveTeamStep,
+ parseMessageTopHogMetrics,
+} from './steps/event-preprocessing'
import { addTeamToContext } from './subpipelines/helpers'
/**
@@ -76,6 +82,13 @@ export interface CommonIngestionPipelineConfig<ROut extends string = never> {
teamManager: TeamManager
outputs: IngestionOutputs<IngestionWarningsOutput | DlqOutput | ROut>
promiseScheduler: PromiseScheduler
+ /**
+ * TopHog registry for per-tenant metrics. The skeleton itself records
+ * parse timing and message sizes (see `parseMessageTopHogMetrics`);
+ * pipelines can layer their own metrics via the `parseMessage` /
+ * `resolveTeam` factory lists.
+ */
+ topHog: TopHogRegistry
/** Maximum number of batches accepted concurrently. Defaults to the framework default. */
concurrentBatches?: number
/**
@@ -273,12 +286,14 @@ export class CommonPreTeamStage<
private readonly chain: PreTeamChain<TInput, TContext, ROut, CBatch, TCurrent>
) {}
- /** Per-element step; consecutive pipes run in one sequential block. */
+ /** Per-element step; consecutive pipes run in one sequential block.
+ * `options.topHog` records metric factories around the step. */
pipe<U extends { message: Message; headers: EventHeaders }, R2 extends ROut>(
step: ProcessingStep<TCurrent, U, R2>,
- options?: { retry?: RetryOptions }
+ options?: { retry?: RetryOptions; topHog?: TopHogMetricFactory<TCurrent, U>[] }
): CommonPreTeamStage<TInput, TContext, ROut, CBatch, U> {
- return new CommonPreTeamStage(this.config, this.beforeBatchCallback, this.chain.extend(step, options))
+ const wrapped = options?.topHog?.length ? createTopHogWrapper(this.config.topHog)(step, options.topHog) : step
+ return new CommonPreTeamStage(this.config, this.beforeBatchCallback, this.chain.extend(wrapped, options))
}
/** Chunk-level step (e.g. rate-limit-to-overflow); closes the open sequential block. */
@@ -294,9 +309,23 @@ export class CommonPreTeamStage<
)
}
- /** Parse the message body; after this, body-dependent steps can be piped. */
- parseMessage(): CommonPreTeamStage<TInput, TContext, ROut, CBatch, TCurrent & { event: IncomingEvent }> {
- return this.pipe(createParseKafkaMessageStep())
+ /**
+ * Parse the message body; after this, body-dependent steps can be piped.
+ *
+ * Parse timing and raw message sizes are always recorded to topHog
+ * (`parseMessageTopHogMetrics`); `options.topHog` appends
+ * pipeline-specific metric factories on top.
+ */
+ parseMessage(options?: {
+ topHog?: TopHogMetricFactory<TCurrent, TCurrent & { event: IncomingEvent }>[]
+ }): CommonPreTeamStage<TInput, TContext, ROut, CBatch, TCurrent & { event: IncomingEvent }> {
+ const topHog = createTopHogWrapper(this.config.topHog)
+ return this.pipe(
+ topHog(createParseKafkaMessageStep<TCurrent>(), [
+ ...parseMessageTopHogMetrics<TCurrent, TCurrent & { event: IncomingEvent }>(),
+ ...(options?.topHog ?? []),
+ ])
+ )
}
/**
@@ -304,19 +333,19 @@ export class CommonPreTeamStage<
* open the team-aware scope: every step piped after this runs inside
* `handleIngestionWarnings`, with warnings routed to the resolved team.
*
- * `options.wrap` decorates the team-resolution step while preserving its
- * types — e.g. a topHog metrics wrapper.
+ * `options.topHog` records metric factories around the team-resolution
+ * step (e.g. a per-team resolved counter).
*/
resolveTeam(
this: CommonPreTeamStage<TInput, TContext, ROut, CBatch, TCurrent & { event: IncomingEvent }>,
options?: {
- wrap?: (
- step: ProcessingStep<TCurrent & { event: IncomingEvent }, TeamResolved<TCurrent>>
- ) => ProcessingStep<TCurrent & { event: IncomingEvent }, TeamResolved<TCurrent>, ROut>
+ topHog?: TopHogMetricFactory<TCurrent & { event: IncomingEvent }, TeamResolved<TCurrent>>[]
}
): CommonTeamStage<TInput, TContext, ROut, CBatch, TeamResolved<TCurrent>, TeamResolved<TCurrent>> {
const step = createResolveTeamStep<TCurrent & { event: IncomingEvent }>(this.config.teamManager)
- const resolved = this.chain.extend(options?.wrap ? options.wrap(step) : step)
+ const topHog = createTopHogWrapper(this.config.topHog)
+ const metrics = options?.topHog
+ const resolved = this.chain.extend(metrics?.length ? topHog(step, metrics) : step)
return new CommonTeamStage(
this.config,
this.beforeBatchCallback,
@@ -353,16 +382,18 @@ export class CommonTeamStage<
private readonly chain: TeamChain<TPost, TContext, ROut, TCurrent>
) {}
- /** Per-element step; consecutive pipes run in one sequential block. */
+ /** Per-element step; consecutive pipes run in one sequential block.
+ * `options.topHog` records metric factories around the step. */
pipe<U, R2 extends ROut>(
step: ProcessingStep<TCurrent, U, R2>,
- options?: { retry?: RetryOptions }
+ options?: { retry?: RetryOptions; topHog?: TopHogMetricFactory<TCurrent, U>[] }
): CommonTeamStage<TInput, TContext, ROut, CBatch, TPost, U> {
+ const wrapped = options?.topHog?.length ? createTopHogWrapper(this.config.topHog)(step, options.topHog) : step
return new CommonTeamStage(
this.config,
this.beforeBatchCallback,
this.preTeamTransform,
- this.chain.extend(step, options)
+ this.chain.extend(wrapped, options)
)
}
diff --git a/nodejs/src/ingestion/common/ingestion-consumer.ts b/nodejs/src/ingestion/common/ingestion-consumer.ts
index 1a20aa731726..95bb16e0ed79 100644
--- a/nodejs/src/ingestion/common/ingestion-consumer.ts
+++ b/nodejs/src/ingestion/common/ingestion-consumer.ts
@@ -1,12 +1,15 @@
import { Message } from 'node-rdkafka'
import { Gauge } from 'prom-client'
+import { TophogOutput } from '~/common/outputs'
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { instrumentFn } from '~/common/tracing/tracing-utils'
import { logger } from '~/common/utils/logger'
import { IngestionConsumerConfig } from '~/ingestion/config'
import { BatchResult, FeedResult } from '~/ingestion/framework/batching-pipeline'
import { createOkContext } from '~/ingestion/framework/helpers'
import { OkResultWithContext } from '~/ingestion/framework/pipeline.interface'
+import { TopHog, TopHogComponent } from '~/ingestion/framework/tophog'
import { HealthCheckResult, PluginServerService } from '~/types'
import { Scope, extend } from './scopes'
@@ -61,17 +64,33 @@ const latestOffsetTimestampGauge = new Gauge({
* consumer, and returns a live `CommonIngestionConsumer` that owns the
* started handle.
*/
-export class CommonIngestionConsumerScope<S extends ContainerWithPromiseScheduler> {
- private readonly innerScope: Scope<S & { kafkaConsumer: KafkaConsumerInterface }>
+export class CommonIngestionConsumerScope<
+ S extends ContainerWithPromiseScheduler & { outputs: IngestionOutputs<TophogOutput> },
+> {
+ private readonly innerScope: Scope<S & { topHog: TopHog } & { kafkaConsumer: KafkaConsumerInterface }>
constructor(
private readonly name: string,
config: CommonIngestionConsumerConfig,
scope: Scope<S>,
- pipelineFactory: PipelineFactory<S>
+ pipelineFactory: PipelineFactory<S & { topHog: TopHog }>
) {
const consumerName = this.name
- this.innerScope = extend(scope, `${consumerName}-consumer`, (container, builder) => {
+ // Every consumer gets a topHog registry scoped to its own outputs and
+ // pipeline/lane labels. It lives one scope above the consumer so its
+ // started value is in the container when the pipeline factory runs —
+ // and so its flush loop starts before, and stops after, the consumer.
+ const scopeWithTopHog = extend(scope, `${consumerName}-tophog`, (container, builder) =>
+ builder.add(
+ 'topHog',
+ new TopHogComponent({
+ outputs: container.outputs,
+ pipeline: config.INGESTION_PIPELINE ?? 'unknown',
+ lane: config.INGESTION_LANE ?? 'unknown',
+ })
+ )
+ )
+ this.innerScope = extend(scopeWithTopHog, `${consumerName}-consumer`, (container, builder) => {
const pipeline = pipelineFactory({ container })
const handler = new KafkaBatchHandler(config, consumerName, pipeline, container.promiseScheduler)
return builder.add(
diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/index.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/index.ts
index d9ffe6de0c90..9016351bcb69 100644
--- a/nodejs/src/ingestion/common/steps/event-preprocessing/index.ts
+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/index.ts
@@ -4,7 +4,7 @@ export { createApplyPersonProcessingRestrictionsStep } from './apply-person-proc
export { createDedupeFeatureFlagCalledStep } from './dedupe-feature-flag-called'
export { createEnrichSurveyPersonPropertiesStep } from './enrich-survey-person-properties'
export { createParseHeadersStep } from './parse-headers'
-export { createParseKafkaMessageStep } from './parse-kafka-message'
+export { createParseKafkaMessageStep, parseMessageTopHogMetrics } from './parse-kafka-message'
export { createOverflowLaneTTLRefreshStep } from './overflow-lane-ttl-refresh-step'
export {
createOnlyCookielessRateLimitToOverflowStep,
diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/parse-kafka-message.test.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/parse-kafka-message.test.ts
index a1bdb3828a51..e84a22f168b0 100644
--- a/nodejs/src/ingestion/common/steps/event-preprocessing/parse-kafka-message.test.ts
+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/parse-kafka-message.test.ts
@@ -1,9 +1,12 @@
import { Message } from 'node-rdkafka'
import { logger } from '~/common/utils/logger'
+import { TopHogRegistry, createTopHogWrapper } from '~/ingestion/framework/extensions/tophog'
import { PipelineResultType, dlq, ok } from '~/ingestion/framework/results'
+import { createRecordingTopHog } from '~/tests/helpers/tophog'
+import { EventHeaders } from '~/types'
-import { createParseKafkaMessageStep } from './parse-kafka-message'
+import { createParseKafkaMessageStep, parseMessageTopHogMetrics } from './parse-kafka-message'
// Mock dependencies
jest.mock('~/common/utils/logger')
@@ -462,6 +465,84 @@ describe('createParseKafkaMessageStep', () => {
})
})
+ describe('parseMessageTopHogMetrics', () => {
+ function createWrappedStep(registry: TopHogRegistry) {
+ return createTopHogWrapper(registry)(
+ createParseKafkaMessageStep<{ message: Message; headers: EventHeaders }>(),
+ parseMessageTopHogMetrics()
+ )
+ }
+
+ const baseHeaders = {
+ force_disable_person_processing: false,
+ historical_migration: false,
+ skip_heatmap_processing: false,
+ }
+
+ it('records sizes and timing keyed by token, including for messages that fail to parse', async () => {
+ const { registry, records } = createRecordingTopHog()
+ const wrapped = createWrappedStep(registry)
+
+ const malformed = Buffer.from('not json')
+ const result = await wrapped({
+ message: { value: malformed, partition: 7 } as Message,
+ headers: { ...baseHeaders, token: 'token-a' },
+ })
+
+ // The parse itself DLQ'd — the metrics below were still recorded
+ // from the raw message.
+ expect(result).toEqual(dlq('failed_parse_message', expect.any(Error)))
+ expect(records.get('messages_by_token')).toEqual([{ key: { token: 'token-a' }, value: 1 }])
+ expect(records.get('message_size_by_token')).toEqual([
+ { key: { token: 'token-a' }, value: malformed.length },
+ ])
+ expect(records.get('max_message_size_by_token')).toEqual([
+ { key: { token: 'token-a' }, value: malformed.length },
+ ])
+ expect(records.get('message_size_by_token_per_partition')).toEqual([
+ { key: { token: 'token-a', partition: '7' }, value: malformed.length },
+ ])
+ const timings = records.get('parse_time_ms_by_token')!
+ expect(timings).toHaveLength(1)
+ expect(timings[0].key).toEqual({ token: 'token-a' })
+ expect(timings[0].value).toBeGreaterThanOrEqual(0)
+ expect([...records.keys()].sort()).toEqual([
+ 'max_message_size_by_token',
+ 'message_size_by_token',
+ 'message_size_by_token_per_partition',
+ 'messages_by_token',
+ 'parse_time_ms_by_token',
+ ])
+ })
+
+ it('records a successful parse the same way, falling back to an unknown token key', async () => {
+ const { registry, records } = createRecordingTopHog()
+ const wrapped = createWrappedStep(registry)
+
+ const value = Buffer.from(
+ JSON.stringify({
+ data: JSON.stringify({ event: 'test_event', distinct_id: 'user' }),
+ uuid: VALID_UUID,
+ })
+ )
+ const result = await wrapped({
+ message: { value, partition: 0 } as Message,
+ headers: baseHeaders,
+ })
+
+ expect(result.type).toBe(PipelineResultType.OK)
+ expect(records.get('messages_by_token')).toEqual([{ key: { token: 'unknown' }, value: 1 }])
+ expect(records.get('message_size_by_token')).toEqual([{ key: { token: 'unknown' }, value: value.length }])
+ expect(records.get('max_message_size_by_token')).toEqual([
+ { key: { token: 'unknown' }, value: value.length },
+ ])
+ expect(records.get('message_size_by_token_per_partition')).toEqual([
+ { key: { token: 'unknown', partition: '0' }, value: value.length },
+ ])
+ expect(records.get('parse_time_ms_by_token')![0].key).toEqual({ token: 'unknown' })
+ })
+ })
+
describe('edge cases', () => {
it('should handle empty data field', async () => {
const mockMessage: Message = {
diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/parse-kafka-message.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/parse-kafka-message.ts
index 056efabc910f..d7dc8c648f83 100644
--- a/nodejs/src/ingestion/common/steps/event-preprocessing/parse-kafka-message.ts
+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/parse-kafka-message.ts
@@ -4,9 +4,36 @@ import { sanitizeEvent } from '~/common/utils/event'
import { parseJSON } from '~/common/utils/json-parse'
import { logger } from '~/common/utils/logger'
import { UUID } from '~/common/utils/utils'
+import { TopHogMetricFactory, count, max, sum, timer } from '~/ingestion/framework/extensions/tophog'
import { dlq, ok } from '~/ingestion/framework/results'
import { ProcessingStep } from '~/ingestion/framework/steps'
-import { IncomingEvent, PipelineEvent } from '~/types'
+import { EventHeaders, IncomingEvent, PipelineEvent } from '~/types'
+
+/**
+ * TopHog metrics for the parse step: parse timing and raw message sizes,
+ * keyed by token (the team is not resolved yet at parse time). Sizes are
+ * recorded from the raw Kafka message, so malformed events that DLQ at parse
+ * still show up — this is the earliest per-sender visibility the pipeline
+ * has. Wire via `.parseMessage({ wrap: (step) => topHog(step, parseMessageTopHogMetrics()) })`.
+ */
+export function parseMessageTopHogMetrics<
+ TInput extends { message: Message; headers: EventHeaders },
+ TOutput,
+>(): TopHogMetricFactory<TInput, TOutput>[] {
+ const byToken = (input: TInput) => ({ token: input.headers.token ?? 'unknown' })
+ const messageBytes = (input: TInput) => input.message.value?.length ?? 0
+ return [
+ count('messages_by_token', byToken),
+ timer('parse_time_ms_by_token', byToken),
+ sum('message_size_by_token', byToken, messageBytes),
+ max('max_message_size_by_token', byToken, messageBytes),
+ sum(
+ 'message_size_by_token_per_partition',
+ (input) => ({ ...byToken(input), partition: String(input.message.partition) }),
+ messageBytes
+ ),
+ ]
+}
export function createParseKafkaMessageStep<T extends { message: Message }>(): ProcessingStep<
T,
diff --git a/nodejs/src/ingestion/framework/tophog/index.ts b/nodejs/src/ingestion/framework/tophog/index.ts
index 6895faee5fde..d46b87c73b4b 100644
--- a/nodejs/src/ingestion/framework/tophog/index.ts
+++ b/nodejs/src/ingestion/framework/tophog/index.ts
@@ -1,2 +1,2 @@
-export { TopHog } from './tophog'
+export { TopHog, TopHogComponent } from './tophog'
export type { TopHogRequiredConfig, TopHogOptionalConfig } from './tophog'
diff --git a/nodejs/src/ingestion/framework/tophog/tophog.ts b/nodejs/src/ingestion/framework/tophog/tophog.ts
index f65ddbc77ea7..08ce6aeae851 100644
--- a/nodejs/src/ingestion/framework/tophog/tophog.ts
+++ b/nodejs/src/ingestion/framework/tophog/tophog.ts
@@ -1,6 +1,7 @@
import { TOPHOG_OUTPUT, TophogOutput } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { logger } from '~/common/utils/logger'
+import { Component, Started } from '~/ingestion/common/scopes/component'
import { AverageMetricTracker, MaxMetricTracker, SummingMetricTracker, Tracker } from './metric-tracker'
@@ -136,3 +137,22 @@ export class TopHog {
yield* this.averageTrackers.values()
}
}
+
+/**
+ * Lifecycle component for a consumer's TopHog registry: starts the flush loop
+ * with the scope, drains and stops it on teardown.
+ *
+ * TopHog is deliberately per-consumer, not process-shared: an instance bakes
+ * in the pipeline/lane labels its rows are stamped with and flushes through
+ * that consumer's outputs, and one server process can run several consumers
+ * off the same shared services scope.
+ */
+export class TopHogComponent implements Component<TopHog> {
+ constructor(private readonly config: TopHogRequiredConfig & Partial<TopHogOptionalConfig>) {}
+
+ start(): Promise<Started<TopHog>> {
+ const topHog = new TopHog(this.config)
+ topHog.start()
+ return Promise.resolve({ value: topHog, stop: () => topHog.stop() })
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/ai/consumer.ts b/nodejs/src/ingestion/pipelines/ai/consumer.ts
index 1eff73a63b09..41c06164bbab 100644
--- a/nodejs/src/ingestion/pipelines/ai/consumer.ts
+++ b/nodejs/src/ingestion/pipelines/ai/consumer.ts
@@ -33,8 +33,6 @@ import { eventRateStrategy } from '~/ingestion/common/overflow-redirect/overflow
import { Scope, extend } from '~/ingestion/common/scopes'
import { PromiseSchedulerComponent } from '~/ingestion/common/utils/promise-scheduler'
import { IngestionConsumerConfig, IngestionOutputsConfig } from '~/ingestion/config'
-import { createTopHogWrapper } from '~/ingestion/framework/extensions/tophog'
-import { TopHog } from '~/ingestion/framework/tophog'
import { RedisPool } from '~/types'
import { AiBlobStoreComponent } from './blob-offload/blob-store'
@@ -157,18 +155,6 @@ export function createAiConsumer(config: AiConsumerConfig, sharedScope: AiShared
)
// Personhog client owned by the AI scope (created from common, torn down with it).
.add('personhogClient', new PersonHogClientComponent(config))
- // TopHog metrics registry for this lane's outputs (drains per-team/partition counters).
- .add('topHog', {
- start: () => {
- const topHog = new TopHog({
- outputs: container.outputs,
- pipeline: config.INGESTION_PIPELINE ?? 'unknown',
- lane: config.INGESTION_LANE ?? 'unknown',
- })
- topHog.start()
- return Promise.resolve({ value: topHog, stop: () => topHog.stop() })
- },
- })
// Owned by the scope so the store's startup healthcheck runs at
// scope start, before any traffic is consumed.
.add('aiBlobStore', new AiBlobStoreComponent(config))
@@ -212,7 +198,7 @@ export function createAiConsumer(config: AiConsumerConfig, sharedScope: AiShared
cdpHogWatcherSampleRate: config.CDP_HOG_WATCHER_SAMPLE_RATE,
eventSchemaEnforcementEnabled: config.EVENT_SCHEMA_ENFORCEMENT_ENABLED,
eventSchemaEnforcementManager: new EventSchemaEnforcementManager(container.postgres),
- topHog: createTopHogWrapper(container.topHog),
+ topHog: container.topHog,
aiBlobStore: container.aiBlobStore.store,
aiBlobOffloadConfig,
})
diff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts
index 009266d43eee..ce9352d2113a 100644
--- a/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts
@@ -15,10 +15,10 @@ import { TeamManager } from '~/common/utils/team-manager'
import { UUIDT } from '~/common/utils/utils'
import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
import { DisabledOverflowRedirect } from '~/ingestion/common/overflow-redirect/disabled-overflow-redirect'
-import { TopHogWrapper } from '~/ingestion/framework/extensions/tophog'
import { createOkContext } from '~/ingestion/framework/helpers'
import { ok } from '~/ingestion/framework/results'
import { createTestTeam } from '~/tests/helpers/team'
+import { createNoopTopHog } from '~/tests/helpers/tophog'
import { AI_EVENTS_OUTPUT, EVENTS_OUTPUT } from './outputs'
import { AiIngestionPipelineConfig, createAiIngestionPipeline } from './pipeline'
@@ -174,8 +174,7 @@ describe('AiIngestionPipeline', () => {
cdpHogWatcherSampleRate: 1,
eventSchemaEnforcementEnabled: false,
eventSchemaEnforcementManager: {} as unknown as EventSchemaEnforcementManager,
- // No-op metrics wrapper — these tests assert pipeline output, not topHog counters.
- topHog: ((step) => step) as TopHogWrapper,
+ topHog: createNoopTopHog(),
aiBlobStore: null,
aiBlobOffloadConfig: {
isTeamEnabled: (): boolean => false,
diff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.ts
index d1581681db7a..adf8ca5f6f21 100644
--- a/nodejs/src/ingestion/pipelines/ai/pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.ts
@@ -48,7 +48,7 @@ import { createStripPersonUpdatePropertiesStep } from '~/ingestion/common/steps/
import { createRecordIngestionLagStep } from '~/ingestion/common/steps/record-ingestion-lag'
import { AI_EVENT_TYPES } from '~/ingestion/common/subpipelines/ai-event-types'
import { IngestionOverflowMode } from '~/ingestion/config'
-import { TopHogWrapper, sum, sumOk, sumResult } from '~/ingestion/framework/extensions/tophog'
+import { TopHogRegistry, sum, sumOk, sumResult } from '~/ingestion/framework/extensions/tophog'
import { isDropResult } from '~/ingestion/framework/results'
import { BlobStore } from './blob-offload/blob-store'
@@ -83,7 +83,7 @@ export interface AiIngestionPipelineConfig {
cdpHogWatcherSampleRate: number
eventSchemaEnforcementEnabled: boolean
eventSchemaEnforcementManager: EventSchemaEnforcementManager
- topHog: TopHogWrapper
+ topHog: TopHogRegistry
aiBlobStore: BlobStore | null
aiBlobOffloadConfig: OffloadAiBlobsConfig
}
@@ -143,6 +143,7 @@ export function createAiIngestionPipeline<
outputs,
promiseScheduler,
concurrentBatches,
+ topHog,
})
.beforeBatch((b) => b.pipe(createEventFiltersBatchAppMetricsBeforeBatchStep(outputs)))
// Header-only steps: allow only AI events, apply token restrictions.
@@ -184,8 +185,9 @@ export function createAiIngestionPipeline<
// that do transient-failure-prone I/O (hog transform, group-type
// fetch, emit) retry, matching the analytics per-distinct-id path.
.pipe(createNormalizeProcessPersonFlagStep())
- .pipe(
- topHog(createHogTransformEventStep(hogTransformer), [
+ .pipe(createHogTransformEventStep(hogTransformer), {
+ retry: { tries: 5, sleepMs: 100, name: 'hog_transform_event' },
+ topHog: [
sumOk(
'transformations_run',
(output) => ({ team_id: String(output.team.id) }),
@@ -214,9 +216,8 @@ export function createAiIngestionPipeline<
}),
(result) => (isDropResult(result) ? 1 : 0)
),
- ]),
- { retry: { tries: 5, sleepMs: 100, name: 'hog_transform_event' } }
- )
+ ],
+ })
.pipe(createNormalizeEventStep())
.pipe(createProcessAiEventStep())
// Blob offload: extract blobs sequentially (cheap, no I/O), then
@@ -246,8 +247,9 @@ export function createAiIngestionPipeline<
.pipe(createCreateEventStep(EVENTS_OUTPUT))
// Double-write to events + ai_events outputs.
.pipe(createSplitAiEventsStep())
- .pipe(
- topHog(createEmitEventStep({ outputs }), [
+ .pipe(createEmitEventStep({ outputs }), {
+ retry: { tries: 5, sleepMs: 100, name: 'emit_event' },
+ topHog: [
sum(
'emitted_events',
(input) => ({ team_id: String(input.teamId) }),
@@ -261,9 +263,8 @@ export function createAiIngestionPipeline<
}),
(input) => input.eventsToEmit.length
),
- ]),
- { retry: { tries: 5, sleepMs: 100, name: 'emit_event' } }
- )
+ ],
+ })
.pipe(createRecordIngestionLagStep())
.afterBatch((b) =>
b
diff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
index d93100ce94c1..82542aa2fcfc 100644
--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
@@ -189,6 +189,7 @@ export function createJoinedIngestionPipeline<
teamManager,
outputs,
promiseScheduler,
+ topHog,
// Batch stores are singleton persistent caches, but each batch receives a
// batch-bound view so entries can be reference-counted and released after
// that batch's flush lifecycle completes. The Rust consumer's per-worker
diff --git a/nodejs/src/ingestion/pipelines/clientwarnings/outputs/registry.ts b/nodejs/src/ingestion/pipelines/clientwarnings/outputs/registry.ts
index c1f59523c3fc..00947440d511 100644
--- a/nodejs/src/ingestion/pipelines/clientwarnings/outputs/registry.ts
+++ b/nodejs/src/ingestion/pipelines/clientwarnings/outputs/registry.ts
@@ -1,4 +1,4 @@
-import { APP_METRICS_OUTPUT, DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'
+import { APP_METRICS_OUTPUT, DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT, TOPHOG_OUTPUT } from '~/common/outputs'
import { IngestionOutputsBuilder } from '~/common/outputs/ingestion-outputs-builder'
/**
@@ -20,4 +20,8 @@ export function createOutputsRegistry() {
topicKey: 'INGESTION_OUTPUT_APP_METRICS_TOPIC',
producerKey: 'INGESTION_OUTPUT_APP_METRICS_PRODUCER',
})
+ .register(TOPHOG_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_TOPHOG_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_TOPHOG_PRODUCER',
+ })
}
diff --git a/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.test.ts b/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.test.ts
index 97396bcc3339..5c319b0b66af 100644
--- a/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.test.ts
@@ -1,7 +1,7 @@
import { Message } from 'node-rdkafka'
import { KafkaProducerWrapper } from '~/common/kafka/producer'
-import { APP_METRICS_OUTPUT, DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'
+import { APP_METRICS_OUTPUT, DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT, TOPHOG_OUTPUT } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'
@@ -12,6 +12,7 @@ import { UUIDT } from '~/common/utils/utils'
import { EventFilterManager } from '~/ingestion/common/event-filters'
import { createOkContext } from '~/ingestion/framework/helpers'
import { createTestTeam } from '~/tests/helpers/team'
+import { createNoopTopHog } from '~/tests/helpers/tophog'
import { ClientWarningsPipelineConfig, createClientWarningsPipeline } from './pipeline'
@@ -119,7 +120,9 @@ describe('ClientWarningsPipeline', () => {
mockKafkaProducer,
'test'
),
+ [TOPHOG_OUTPUT]: new SingleIngestionOutput(TOPHOG_OUTPUT, 'tophog_test', mockKafkaProducer, 'test'),
}),
+ topHog: createNoopTopHog(),
teamManager: mockTeamManager,
eventIngestionRestrictionManager: mockEventIngestionRestrictionManager,
eventFilterManager: mockEventFilterManager,
diff --git a/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.ts b/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.ts
index da4987879ee4..4680f676967a 100644
--- a/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.ts
@@ -1,6 +1,6 @@
import { Message } from 'node-rdkafka'
-import { AppMetricsOutput, DlqOutput, IngestionWarningsOutput } from '~/common/outputs'
+import { AppMetricsOutput, DlqOutput, IngestionWarningsOutput, TophogOutput } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
@@ -22,9 +22,10 @@ import { createApplyBasicEventRestrictionsStep } from '~/ingestion/common/steps/
import { createDropOldEventsStep } from '~/ingestion/common/steps/event-processing/drop-old-events-step'
import { createHandleClientIngestionWarningStep } from '~/ingestion/common/steps/event-processing/handle-client-ingestion-warning-step'
import { createRecordIngestionLagStep } from '~/ingestion/common/steps/record-ingestion-lag'
+import { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'
export interface ClientWarningsPipelineConfig {
- outputs: IngestionOutputs<IngestionWarningsOutput | DlqOutput | AppMetricsOutput>
+ outputs: IngestionOutputs<IngestionWarningsOutput | DlqOutput | AppMetricsOutput | TophogOutput>
teamManager: TeamManager
// The managers come from a started `Lifecycle`'s service map, where
// `start` and `stop` are stripped from the type — the pipeline only
@@ -32,6 +33,7 @@ export interface ClientWarningsPipelineConfig {
eventIngestionRestrictionManager: EventIngestionRestrictionManager
eventFilterManager: EventFilterManager
promiseScheduler: PromiseScheduler
+ topHog: TopHogRegistry
}
interface ClientWarningsPipelineInput {
@@ -46,13 +48,15 @@ export function createClientWarningsPipeline<
TInput extends ClientWarningsPipelineInput,
TContext extends ClientWarningsPipelineContext,
>(config: ClientWarningsPipelineConfig) {
- const { outputs, teamManager, eventIngestionRestrictionManager, eventFilterManager, promiseScheduler } = config
+ const { outputs, teamManager, eventIngestionRestrictionManager, eventFilterManager, promiseScheduler, topHog } =
+ config
return newCommonIngestionPipeline<TInput, TContext>({
teamManager,
outputs,
promiseScheduler,
concurrentBatches: 1,
+ topHog,
})
.beforeBatch((b) => b.pipe(createEventFiltersBatchAppMetricsBeforeBatchStep(outputs)))
.parseHeaders()
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts
index 323064d23c11..1947777f9f97 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts
@@ -1072,7 +1072,7 @@ describe('ErrorTrackingPipeline', () => {
)
}
- it('records resolved_teams metric when team is resolved', async () => {
+ it('records messages_by_token metric for parsed messages', async () => {
const person = createTestPerson()
mockPersonRepository.fetchPersonsByDistinctIds.mockResolvedValue([person])
mockCymbalClient.processExceptions.mockResolvedValue([createCymbalResponse()])
@@ -1090,11 +1090,11 @@ describe('ErrorTrackingPipeline', () => {
expect(mockHogTransformer.transformEventAndProduceMessages).toHaveBeenCalledTimes(1)
const messages = getTopHogMessages()
- const resolvedTeamsMetric = messages.find((m) => m.metric === 'resolved_teams')
- expect(resolvedTeamsMetric).toBeDefined()
- expect(resolvedTeamsMetric.type).toBe('sum')
- expect(resolvedTeamsMetric.key.team_id).toBe('123')
- expect(resolvedTeamsMetric.value).toBe(1)
+ const messagesByToken = messages.find((m) => m.metric === 'messages_by_token')
+ expect(messagesByToken).toBeDefined()
+ expect(messagesByToken.type).toBe('sum')
+ expect(messagesByToken.key.token).toBe('test-token-123')
+ expect(messagesByToken.value).toBe(1)
})
it('records emitted_events metric when events are emitted', async () => {
@@ -1200,9 +1200,9 @@ describe('ErrorTrackingPipeline', () => {
const topHogMessages = getTopHogMessages()
- // resolved_teams should have count=3 (one per event)
- const resolvedTeamsMetric = topHogMessages.find((m) => m.metric === 'resolved_teams')
- expect(resolvedTeamsMetric.value).toBe(3)
+ // messages_by_token should have count=3 (one per parsed message)
+ const messagesByToken = topHogMessages.find((m) => m.metric === 'messages_by_token')
+ expect(messagesByToken.value).toBe(3)
// emitted_events should have value=3
const emittedEventsMetric = topHogMessages.find((m) => m.metric === 'emitted_events')
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts
index 2eac1155d406..c37611d21da6 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts
@@ -33,7 +33,7 @@ import { createReadOnlyProcessGroupsStep } from '~/ingestion/common/steps/event-
import { createRecordIngestionLagStep } from '~/ingestion/common/steps/record-ingestion-lag'
import { IngestionOverflowMode } from '~/ingestion/config'
import { BatchingContext, BatchingPipeline } from '~/ingestion/framework/batching-pipeline'
-import { TopHogRegistry, count, countOk, createTopHogWrapper } from '~/ingestion/framework/extensions/tophog'
+import { TopHogRegistry, count } from '~/ingestion/framework/extensions/tophog'
import { createBatch } from '~/ingestion/framework/helpers'
import { createAttachMessageBytesStep } from './attach-message-bytes-step'
@@ -138,13 +138,12 @@ export function createErrorTrackingPipeline(config: ErrorTrackingPipelineConfig)
topHog,
} = config
- const topHogWrapper = createTopHogWrapper(topHog)
-
const preCymbal = newCommonIngestionPipeline<ErrorTrackingPipelineInput, { message: Message }, OverflowOutput>({
teamManager,
outputs,
promiseScheduler,
concurrentBatches: 1,
+ topHog,
})
// Header-only steps: parse Kafka headers and apply token-level restrictions.
// Cheap; runs per-event before we touch the body.
@@ -161,14 +160,7 @@ export function createErrorTrackingPipeline(config: ErrorTrackingPipelineConfig)
// keys on the hashed distinct_id assigned by the cookieless step.
.pipeChunk(createSkipCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))
.parseMessage()
- .resolveTeam({
- wrap: (step) =>
- topHogWrapper(step, [
- countOk('resolved_teams', (output) => ({
- team_id: String(output.team.id),
- })),
- ]),
- })
+ .resolveTeam()
// Carry the Kafka message byte size through for Cymbal batch chunking.
.pipe(createAttachMessageBytesStep())
// Cookieless processing: rewrites event.distinct_id for cookieless
@@ -205,22 +197,17 @@ export function createErrorTrackingPipeline(config: ErrorTrackingPipelineConfig)
// Map group types to indexes (read-only, no new group types created)
.pipe(createReadOnlyProcessGroupsStep(groupTypeManager))
.pipe(createCreateEventStep(EVENTS_OUTPUT))
- .pipe(
- topHogWrapper(
- createEmitEventStep({
- outputs,
- }),
- [
- count('emitted_events', (input) => ({
- team_id: String(input.teamId),
- })),
- count('emitted_events_per_distinct_id', (input) => ({
- team_id: String(input.teamId),
- distinct_id: input.eventsToEmit[0]?.event.distinct_id ?? '',
- })),
- ]
- )
- )
+ .pipe(createEmitEventStep({ outputs }), {
+ topHog: [
+ count('emitted_events', (input) => ({
+ team_id: String(input.teamId),
+ })),
+ count('emitted_events_per_distinct_id', (input) => ({
+ team_id: String(input.teamId),
+ distinct_id: input.eventsToEmit[0]?.event.distinct_id ?? '',
+ })),
+ ],
+ })
.pipe(createRecordIngestionLagStep())
.build()
)
diff --git a/nodejs/src/ingestion/pipelines/heatmaps/outputs/registry.ts b/nodejs/src/ingestion/pipelines/heatmaps/outputs/registry.ts
index 7785028cee49..77c6b5a421ed 100644
--- a/nodejs/src/ingestion/pipelines/heatmaps/outputs/registry.ts
+++ b/nodejs/src/ingestion/pipelines/heatmaps/outputs/registry.ts
@@ -1,4 +1,4 @@
-import { APP_METRICS_OUTPUT, DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'
+import { APP_METRICS_OUTPUT, DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT, TOPHOG_OUTPUT } from '~/common/outputs'
import { IngestionOutputsBuilder } from '~/common/outputs/ingestion-outputs-builder'
import { HEATMAPS_OUTPUT } from './index'
@@ -26,4 +26,8 @@ export function createOutputsRegistry() {
topicKey: 'INGESTION_OUTPUT_APP_METRICS_TOPIC',
producerKey: 'INGESTION_OUTPUT_APP_METRICS_PRODUCER',
})
+ .register(TOPHOG_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_TOPHOG_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_TOPHOG_PRODUCER',
+ })
}
diff --git a/nodejs/src/ingestion/pipelines/heatmaps/pipeline.test.ts b/nodejs/src/ingestion/pipelines/heatmaps/pipeline.test.ts
index aac469396db6..5458a4fc3d37 100644
--- a/nodejs/src/ingestion/pipelines/heatmaps/pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/heatmaps/pipeline.test.ts
@@ -1,7 +1,7 @@
import { Message } from 'node-rdkafka'
import { KafkaProducerWrapper } from '~/common/kafka/producer'
-import { APP_METRICS_OUTPUT, DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'
+import { APP_METRICS_OUTPUT, DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT, TOPHOG_OUTPUT } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'
@@ -14,6 +14,7 @@ import { EventFilterManager } from '~/ingestion/common/event-filters'
import { createOkContext } from '~/ingestion/framework/helpers'
import { drop, ok } from '~/ingestion/framework/results'
import { createTestTeam } from '~/tests/helpers/team'
+import { createNoopTopHog } from '~/tests/helpers/tophog'
import { HEATMAPS_OUTPUT } from './outputs'
import { HeatmapsPipelineConfig, createHeatmapsPipeline } from './pipeline'
@@ -145,7 +146,9 @@ describe('HeatmapsPipeline', () => {
mockKafkaProducer,
'test'
),
+ [TOPHOG_OUTPUT]: new SingleIngestionOutput(TOPHOG_OUTPUT, 'tophog_test', mockKafkaProducer, 'test'),
}),
+ topHog: createNoopTopHog(),
teamManager: mockTeamManager,
eventIngestionRestrictionManager: mockEventIngestionRestrictionManager,
eventFilterManager: mockEventFilterManager,
diff --git a/nodejs/src/ingestion/pipelines/heatmaps/pipeline.ts b/nodejs/src/ingestion/pipelines/heatmaps/pipeline.ts
index ffa5ad6fb254..450b354b26cc 100644
--- a/nodejs/src/ingestion/pipelines/heatmaps/pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/heatmaps/pipeline.ts
@@ -1,6 +1,6 @@
import { Message } from 'node-rdkafka'
-import { AppMetricsOutput, DlqOutput, IngestionWarningsOutput } from '~/common/outputs'
+import { AppMetricsOutput, DlqOutput, IngestionWarningsOutput, TophogOutput } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
@@ -25,6 +25,7 @@ import { createDropOldEventsStep } from '~/ingestion/common/steps/event-processi
import { createNormalizeEventStep } from '~/ingestion/common/steps/event-processing/normalize-event-step'
import { createPrepareEventStep } from '~/ingestion/common/steps/event-processing/prepare-event-step'
import { createRecordIngestionLagStep } from '~/ingestion/common/steps/record-ingestion-lag'
+import { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'
import { createCheckHeatmapOptInStep } from './check-heatmap-opt-in-step'
import { createDisablePersonProcessingStep } from './disable-person-processing-step'
@@ -32,7 +33,7 @@ import { createExtractHeatmapDataStep } from './extract-heatmap-data-step'
import { HeatmapsOutput } from './outputs'
export interface HeatmapsPipelineConfig {
- outputs: IngestionOutputs<HeatmapsOutput | IngestionWarningsOutput | DlqOutput | AppMetricsOutput>
+ outputs: IngestionOutputs<HeatmapsOutput | IngestionWarningsOutput | DlqOutput | AppMetricsOutput | TophogOutput>
teamManager: TeamManager
// The managers come from a started `Lifecycle`'s service map, where
// `start` and `stop` are stripped from the type — the pipeline only
@@ -41,6 +42,7 @@ export interface HeatmapsPipelineConfig {
eventFilterManager: EventFilterManager
cookielessManager: CookielessManager
promiseScheduler: PromiseScheduler
+ topHog: TopHogRegistry
}
interface HeatmapsPipelineInput {
@@ -61,6 +63,7 @@ export function createHeatmapsPipeline<TInput extends HeatmapsPipelineInput, TCo
eventFilterManager,
cookielessManager,
promiseScheduler,
+ topHog,
} = config
return (
@@ -69,6 +72,7 @@ export function createHeatmapsPipeline<TInput extends HeatmapsPipelineInput, TCo
outputs,
promiseScheduler,
concurrentBatches: 1,
+ topHog,
})
.beforeBatch((b) => b.pipe(createEventFiltersBatchAppMetricsBeforeBatchStep(outputs)))
.parseHeaders()
diff --git a/nodejs/tests/helpers/tophog.ts b/nodejs/tests/helpers/tophog.ts
new file mode 100644
index 000000000000..ee968bfefa65
--- /dev/null
+++ b/nodejs/tests/helpers/tophog.ts
@@ -0,0 +1,32 @@
+import { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'
+
+/** A topHog registry that swallows every record — for tests that assert
+ * pipeline output, not metrics. */
+export function createNoopTopHog(): TopHogRegistry {
+ const recorder = { record: () => {} }
+ return {
+ registerSum: () => recorder,
+ registerMax: () => recorder,
+ registerAverage: () => recorder,
+ }
+}
+
+export type RecordedTopHogMetric = { key: Record<string, string>; value: number }
+
+/** A topHog registry that captures every record per metric name, so tests can
+ * assert exactly which keys and values each metric received. */
+export function createRecordingTopHog(): {
+ registry: TopHogRegistry
+ records: Map<string, RecordedTopHogMetric[]>
+} {
+ const records = new Map<string, RecordedTopHogMetric[]>()
+ const recorder = (name: string) => ({
+ record: (key: Record<string, string>, value: number) => {
+ records.set(name, [...(records.get(name) ?? []), { key, value }])
+ },
+ })
+ return {
+ registry: { registerSum: recorder, registerMax: recorder, registerAverage: recorder },
+ records,
+ }
+}