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(cdp): dead-letter events that build no invocation (#100792)

Meikel Ratz7caf1c624436
diff --git a/nodejs/src/cdp/_tests/examples.ts b/nodejs/src/cdp/_tests/examples.ts
index c16a69a69fc9..fceaa3139838 100644
--- a/nodejs/src/cdp/_tests/examples.ts
+++ b/nodejs/src/cdp/_tests/examples.ts
@@ -576,7 +576,40 @@ export const HOG_INPUTS_EXAMPLES: Record<string, Pick<HogFunctionType, 'inputs'
export const HOG_FILTERS_EXAMPLES: Record<string, Pick<HogFunctionType, 'filters'>> = {
no_filters: { filters: { events: [], actions: [], bytecode: ['_h', 29] } },
- broken_filters: { filters: { events: [], actions: [], bytecode: ['_H', 1, 29, 35, 35, 35] } },
+ /** Stamped against a runtime that is not the one running, so the throw classifies as `drift`. */
+ broken_filters: {
+ filters: { events: [], actions: [], bytecode: ['_H', 1, 29, 35, 35, 35], bytecode_contract: 'stale' },
+ },
+ /** The same throw with no stamp, so nothing can say whose fault it is. */
+ broken_filters_unstamped: { filters: { events: [], actions: [], bytecode: ['_H', 1, 29, 35, 35, 35] } },
+
+ /** Parses a JSON property off the event, so a malformed value is the event's own: `data`. */
+ filters_bad_event_json: {
+ filters: {
+ events: [],
+ actions: [],
+ bytecode: ['_H', 1, 32, 'payload', 32, 'properties', 1, 2, 2, 'jsonParse', 1],
+ bytecode_contract: 'stale',
+ },
+ },
+ /** Loops forever, so the VM stops it on its own budget: `limit`. */
+ filters_never_finish: {
+ filters: {
+ events: [],
+ actions: [],
+ bytecode: ['_H', 1, 33, 0, 36, 0, 33, 1, 6, 37, 0, 39, -9],
+ bytecode_contract: 'stale',
+ },
+ },
+ /** A pattern the regex engine refuses. It arrives through the standard library, so: `data`. */
+ filters_bad_regex: {
+ filters: {
+ events: [],
+ actions: [],
+ bytecode: ['_H', 1, 32, 'payload', 32, 'properties', 1, 2, 32, '(?=x)', 2, 'match', 2],
+ bytecode_contract: 'stale',
+ },
+ },
// Test account filter: filters out users with @posthog.com in their email
// This simulates filter_test_accounts: true with test_account_filters = [{key: "email", value: "@posthog.com", operator: "not_icontains", type: "person"}]
test_account_filter: {
diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.ts
index 1b3b04e320f1..ca8f6d512e58 100644
--- a/nodejs/src/cdp/cdp-services.ts
+++ b/nodejs/src/cdp/cdp-services.ts
@@ -12,7 +12,7 @@ import { TeamManager } from '~/common/utils/team-manager'
import type { CommonConfig } from '../common/config'
import { InternalCaptureService } from '../common/services/internal-capture'
import type { CdpConfig } from './config'
-import { WarehouseSourceWebhooksOutput } from './outputs/outputs'
+import { CdpEventsDlqOutput, WarehouseSourceWebhooksOutput } from './outputs/outputs'
import { CdpProducerName } from './outputs/producers'
import { createCdpOutputsRegistry } from './outputs/registry'
import { CapturedEventsService } from './services/captured-events/captured-events.service'
@@ -55,7 +55,12 @@ import { PosthogJwtAudience } from './utils/jwt-utils'
import { ScopedServiceJwt } from './utils/scoped-service-jwt'
/** Union of every output name resolved by `createCdpOutputsRegistry()`. */
-export type CdpOutput = AppMetricsOutput | LogEntriesOutput | HogInvocationResultsOutput | WarehouseSourceWebhooksOutput
+export type CdpOutput =
+ | AppMetricsOutput
+ | LogEntriesOutput
+ | HogInvocationResultsOutput
+ | WarehouseSourceWebhooksOutput
+ | CdpEventsDlqOutput
export type CdpOutputs = IngestionOutputs<CdpOutput>
@@ -181,6 +186,10 @@ export type CdpCoreServicesConfig = Pick<
| 'MESSAGE_ASSETS_PRODUCER'
| 'CDP_WAREHOUSE_SOURCE_WEBHOOKS_TOPIC'
| 'CDP_WAREHOUSE_SOURCE_WEBHOOKS_PRODUCER'
+ | 'CDP_DLQ_ENABLED'
+ | 'CDP_DLQ_BATCH_FAIL_RATIO'
+ | 'CDP_EVENTS_DLQ_TOPIC'
+ | 'CDP_EVENTS_DLQ_PRODUCER'
>
export interface CdpCoreServicesDeps {
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.ts
index 18fa43717580..c4cfe27596d6 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -1,5 +1,6 @@
import {
KAFKA_APP_METRICS_2,
+ KAFKA_CDP_EVENTS_DLQ,
KAFKA_EVENTS_JSON,
KAFKA_HOG_INVOCATION_RESULTS,
KAFKA_LOG_ENTRIES,
@@ -120,6 +121,15 @@ export type CdpConfig = ClickhouseConfig & {
CDP_RERUN_WORKER_BATCH_SIZE: number
CDP_WAREHOUSE_SOURCE_WEBHOOKS_TOPIC: string
CDP_WAREHOUSE_SOURCE_WEBHOOKS_PRODUCER: CdpProducerName
+ // Dead-letter queue for events that matched a function but produced no invocation.
+ // Off until the topics exist on the cluster — a missing topic would fail every batch.
+ CDP_DLQ_ENABLED: boolean
+ // Above this share of a batch failing unexpectedly, the batch fails instead of being parked.
+ // Low on purpose: a deploy that breaks the builder shows up in a small slice of a batch long
+ // before it reaches half of one, and stalling early costs less than draining the stream.
+ CDP_DLQ_BATCH_FAIL_RATIO: number
+ CDP_EVENTS_DLQ_TOPIC: string
+ CDP_EVENTS_DLQ_PRODUCER: CdpProducerName
CDP_EMAIL_TRACKING_URL: string
@@ -326,6 +336,12 @@ export function getDefaultCdpConfig(): CdpConfig {
CDP_RERUN_WORKER_BATCH_SIZE: 1,
CDP_WAREHOUSE_SOURCE_WEBHOOKS_TOPIC: KAFKA_WAREHOUSE_SOURCE_WEBHOOKS,
CDP_WAREHOUSE_SOURCE_WEBHOOKS_PRODUCER: WAREHOUSE_PRODUCER,
+ CDP_DLQ_ENABLED: false,
+ CDP_DLQ_BATCH_FAIL_RATIO: 0.1,
+ CDP_EVENTS_DLQ_TOPIC: KAFKA_CDP_EVENTS_DLQ,
+ // Same cyclotron Warpstream cluster as every other CDP topic — the replay worker
+ // consumes from there, and no ClickHouse table reads these topics.
+ CDP_EVENTS_DLQ_PRODUCER: WARPSTREAM_CYCLOTRON_PRODUCER,
CDP_EMAIL_TRACKING_URL: 'http://localhost:8010',
diff --git a/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts b/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts
index 953b39cb5106..ff4c4ef444e6 100644
--- a/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts
@@ -28,6 +28,7 @@ import { insertHogFlow as _insertHogFlow } from '../_tests/fixtures-hogflows'
import { GroupsManagerService } from '../services/managers/groups-manager.service'
import { HogWatcherState } from '../services/monitoring/hog-watcher.service'
import { HogFunctionInvocationGlobals, HogFunctionType } from '../types'
+import { currentRuntimeContractHash } from '../utils/filter-runtime'
import { CdpEventsConsumer } from './cdp-events.consumer'
jest.setTimeout(1000)
@@ -593,6 +594,262 @@ describe('CdpEventsConsumer', () => {
])
})
})
+
+ describe('dead letter queue', () => {
+ const handleBatch = async (messages: any[]): Promise<void> => {
+ const connect = processor['kafkaConsumer'].connect as jest.Mock
+ const { backgroundTask } = await connect.mock.calls[0][0](messages)
+ await backgroundTask
+ }
+
+ beforeEach(() => {
+ hub.CDP_DLQ_ENABLED = true
+ })
+
+ it('parks each event whose filter throws with its own bytes, naming only the function that failed', async () => {
+ const erroringFunction = await insertHogFunction({
+ ...HOG_EXAMPLES.input_printer,
+ ...HOG_INPUTS_EXAMPLES.secret_inputs,
+ ...HOG_FILTERS_EXAMPLES.broken_filters,
+ })
+ const healthyFunction = await insertHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...HOG_FILTERS_EXAMPLES.no_filters,
+ })
+ const events = [createIncomingEvent(team.id, {}), createIncomingEvent(team.id, {})]
+
+ await handleBatch(events.map((event, index) => createKafkaMessage(event, { offset: 10 + index })))
+
+ // Two events, so a failure traced back to the wrong message parks the other event's bytes.
+ const parked = mockProducerObserver.getProducedKafkaMessagesForTopic('cdp_events_dlq_test')
+ expect(parked).toHaveLength(2)
+ for (const [index, event] of events.entries()) {
+ const record = parked.find((message) => message.value?.uuid === event.uuid)
+ expect(record?.headers).toMatchObject({
+ dlq_step: 'filter',
+ dlq_team_id: String(team.id),
+ dlq_offset: String(10 + index),
+ dlq_hog_function_ids: erroringFunction.id,
+ dlq_class: 'drift',
+ })
+ }
+ const queued = mockQueueInvocations.mock.calls.flatMap(([invocations]: [any[]]) => invocations)
+ expect(queued.map((invocation: any) => invocation.functionId)).toEqual([
+ healthyFunction.id,
+ healthyFunction.id,
+ ])
+ })
+
+ it('queues nothing when the batch is abandoned because parking refused', async () => {
+ // A refusal that leaves invocations queued delivers them again on the reprocess.
+ jest.spyOn(processor['deadLetterService'], 'produceForBatch').mockRejectedValue(new Error('topic gone'))
+ await insertHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...HOG_FILTERS_EXAMPLES.no_filters,
+ })
+
+ await expect(handleBatch([createKafkaMessage(createIncomingEvent(team.id, {}))])).rejects.toThrow(
+ 'topic gone'
+ )
+
+ expect(mockQueueInvocations).not.toHaveBeenCalled()
+ })
+
+ it("parks nothing when the failure is the owner's to fix", async () => {
+ // An unstamped throw cannot be attributed, so it is the owner's until the backfill runs.
+ await insertHogFunction({
+ ...HOG_EXAMPLES.input_printer,
+ ...HOG_INPUTS_EXAMPLES.secret_inputs,
+ ...HOG_FILTERS_EXAMPLES.broken_filters_unstamped,
+ })
+
+ await handleBatch([createKafkaMessage(createIncomingEvent(team.id, {}))])
+
+ expect(mockProducerObserver.getProducedKafkaMessagesForTopic('cdp_events_dlq_test')).toHaveLength(0)
+ })
+
+ it.each([
+ ['data', 'filters_bad_event_json' as const, JSON.stringify({ payload: '{' })],
+ // The refusal reaches the VM through the standard library, which reports it as `data`.
+ ['data', 'filters_bad_regex' as const, JSON.stringify({ payload: 'abc' })],
+ ['limit', 'filters_never_finish' as const, '{}'],
+ ])(
+ "parks nothing when a %s failure is the owner's",
+ async (_class, fixture, properties) => {
+ // Both fail the same way on every attempt, so a replay cannot clear either.
+ await insertHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...HOG_FILTERS_EXAMPLES[fixture],
+ })
+
+ await handleBatch([createKafkaMessage(createIncomingEvent(team.id, { properties }))])
+
+ expect(mockProducerObserver.getProducedKafkaMessagesForTopic('cdp_events_dlq_test')).toHaveLength(0)
+ },
+ 20000
+ )
+
+ it('parks a refusal the compiler said could not happen, and says it is a bug', async () => {
+ // The stamp matches the runtime that is running, so the compiler accepted a program
+ // the VM then refused. Nothing else in the queue means what this means.
+ await insertHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ filters: {
+ ...HOG_FILTERS_EXAMPLES.broken_filters.filters,
+ bytecode_contract: currentRuntimeContractHash(),
+ },
+ })
+
+ await handleBatch([createKafkaMessage(createIncomingEvent(team.id, {}))])
+
+ const parked = mockProducerObserver.getProducedKafkaMessagesForTopic('cdp_events_dlq_test')
+ expect(parked).toHaveLength(1)
+ expect(parked[0].headers).toMatchObject({ dlq_class: 'bug' })
+ })
+
+ it('parks an event that throws unexpectedly instead of failing the whole batch', async () => {
+ // Nothing in the pipeline expects this, which is the point: an unanticipated bug
+ // used to reject the batch, restart the pod, and stall the partition forever.
+ const fn = await insertHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...HOG_FILTERS_EXAMPLES.no_filters,
+ })
+ // `mappings` is neither null nor an array, so the builder walks into `.map` on an
+ // object and throws where nothing catches it. Stands in for any shape of data or
+ // bug the per-function handling was not written for.
+ jest.spyOn(processor['hogFunctionManager'], 'getHogFunctionsForTeams').mockResolvedValue({
+ [team.id]: [{ ...fn, mappings: {} as any }],
+ })
+ const event = createIncomingEvent(team.id, {})
+
+ await expect(handleBatch([createKafkaMessage(event)])).resolves.toBeUndefined()
+
+ const parked = mockProducerObserver.getProducedKafkaMessagesForTopic('cdp_events_dlq_test')
+ expect(parked).toHaveLength(1)
+ expect(parked[0].headers).toMatchObject({
+ dlq_step: 'process',
+ // No function named, so a replay rebuilds all of them: none ran this time.
+ dlq_hog_function_ids: '',
+ })
+ })
+
+ it('fails the batch rather than dropping an unexpected throw while the queue is off', async () => {
+ // The flag ships off, so without this the catch above turns every unanticipated
+ // bug into a silently dropped event instead of a batch that retries.
+ hub.CDP_DLQ_ENABLED = false
+ const fn = await insertHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...HOG_FILTERS_EXAMPLES.no_filters,
+ })
+ jest.spyOn(processor['hogFunctionManager'], 'getHogFunctionsForTeams').mockResolvedValue({
+ [team.id]: [{ ...fn, mappings: {} as any }],
+ })
+
+ await expect(handleBatch([createKafkaMessage(createIncomingEvent(team.id, {}))])).rejects.toThrow()
+
+ expect(mockProducerObserver.getProducedKafkaMessagesForTopic('cdp_events_dlq_test')).toHaveLength(0)
+ })
+
+ it('parks a message it cannot parse', async () => {
+ await insertHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...HOG_FILTERS_EXAMPLES.no_filters,
+ })
+
+ await handleBatch([createKafkaMessage('not json at all')])
+
+ const parked = mockProducerObserver.getProducedKafkaMessagesForTopic('cdp_events_dlq_test')
+ expect(parked).toHaveLength(1)
+ expect(parked[0].headers).toMatchObject({ dlq_step: 'parse' })
+ })
+
+ it('fails the batch when the record cannot be written, so the offsets stay put', async () => {
+ // Also guards the ordering: the handler has to await the write. Without the await
+ // this rejects in the background and the consumer walks past the event anyway.
+ const erroring = await insertHogFunction({
+ ...HOG_EXAMPLES.input_printer,
+ ...HOG_INPUTS_EXAMPLES.secret_inputs,
+ ...HOG_FILTERS_EXAMPLES.broken_filters,
+ })
+ expect(erroring.id).toBeDefined()
+ // Spying here returns the observer's own spy, so it is re-armed rather than
+ // restored: restoring uninstalls the observer and every later assertion in this
+ // file passes against an empty recording.
+ mockProducerObserver.produceSpy.mockImplementation(({ topic }) =>
+ topic === 'cdp_events_dlq_test'
+ ? Promise.reject(new Error('broker rejected the record'))
+ : Promise.resolve()
+ )
+
+ try {
+ await expect(handleBatch([createKafkaMessage(createIncomingEvent(team.id, {}))])).rejects.toThrow(
+ 'broker rejected the record'
+ )
+ } finally {
+ mockProducerObserver.resetKafkaProducer()
+ }
+ })
+
+ it('parks a message whose failure was not an Error, with a reason a person can read', async () => {
+ // A thrown string carries no `message`. An undefined reason fails the produce, so
+ // the partition stalls on the very message the record exists to keep.
+ await insertHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...HOG_FILTERS_EXAMPLES.no_filters,
+ })
+ jest.spyOn(processor['hogFunctionManager'], 'getHogFunctionsForTeam').mockRejectedValue('kaboom' as any)
+
+ await handleBatch([createKafkaMessage(createIncomingEvent(team.id, {}))])
+
+ const parked = mockProducerObserver.getProducedKafkaMessagesForTopic('cdp_events_dlq_test')
+ expect(parked).toHaveLength(1)
+ expect(parked[0].headers).toMatchObject({ dlq_step: 'parse', dlq_reason: 'kaboom' })
+ })
+
+ it('fails the batch on a dependency outage while parsing, rather than parking every event', async () => {
+ await insertHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...HOG_FILTERS_EXAMPLES.no_filters,
+ })
+ const outage: Error & { isRetriable?: boolean } = new Error('Postgres is down')
+ outage.isRetriable = true
+ const lookup = jest
+ .spyOn(processor['hogFunctionManager'], 'getHogFunctionsForTeam')
+ .mockRejectedValue(outage)
+
+ await expect(handleBatch([createKafkaMessage(createIncomingEvent(team.id, {}))])).rejects.toThrow(
+ 'Postgres is down'
+ )
+
+ // The failed batch never reaches the write, so a failure recorded for it would be
+ // parked by the next batch instead.
+ lookup.mockRestore()
+ await handleBatch([createKafkaMessage(createIncomingEvent(team.id, {}))])
+
+ expect(mockProducerObserver.getProducedKafkaMessagesForTopic('cdp_events_dlq_test')).toHaveLength(0)
+ })
+
+ it('parks nothing when every function builds', async () => {
+ await insertHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...HOG_FILTERS_EXAMPLES.no_filters,
+ })
+
+ await handleBatch([createKafkaMessage(createIncomingEvent(team.id, {}))])
+
+ expect(mockProducerObserver.getProducedKafkaMessagesForTopic('cdp_events_dlq_test')).toHaveLength(0)
+ })
+ })
})
})
diff --git a/nodejs/src/cdp/consumers/cdp-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-events.consumer.ts
index ac9a28fa1636..f7d367318a80 100644
--- a/nodejs/src/cdp/consumers/cdp-events.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-events.consumer.ts
@@ -9,6 +9,8 @@ import { captureException } from '~/common/utils/posthog'
import { convertToHogFunctionInvocationGlobals } from '../../cdp/utils'
import { HealthCheckResult, PluginsServerConfig, RawClickHouseEvent } from '../../types'
+import { CDP_EVENTS_DLQ_OUTPUT } from '../outputs/outputs'
+import { CdpDeadLetterService } from '../services/dead-letter/cdp-dead-letter.service'
import { HogFlowInvocationPipeline } from '../services/hog-flow-invocation-pipeline.service'
import { HogFunctionInvocationPipeline } from '../services/hog-function-invocation-pipeline.service'
import { JobQueue } from '../services/job-queue/job-queue.interface'
@@ -28,6 +30,9 @@ export class CdpEventsConsumer<
private hogFunctionPipeline: HogFunctionInvocationPipeline
private hogFlowPipeline: HogFlowInvocationPipeline
+ private deadLetterService: CdpDeadLetterService
+ /** The message each set of globals was built from, so a failure can find its bytes. */
+ private messageByGlobals = new WeakMap<HogFunctionInvocationGlobals, Message>()
constructor(
config: TConfig,
@@ -40,6 +45,12 @@ export class CdpEventsConsumer<
this.hogQueue = jobQueues.hogQueue
this.hogflowQueue = jobQueues.hogflowQueue
this.kafkaConsumer = createKafkaConsumer({ groupId, topic })
+ this.deadLetterService = new CdpDeadLetterService(config, {
+ outputs: this.outputs,
+ output: CDP_EVENTS_DLQ_OUTPUT,
+ consumerGroup: groupId,
+ resolveMessage: (globals) => this.messageByGlobals.get(globals),
+ })
this.hogFunctionPipeline = new HogFunctionInvocationPipeline(config, {
hogFunctionManager: this.hogFunctionManager,
hogInputsService: this.hogInputsService,
@@ -51,6 +62,7 @@ export class CdpEventsConsumer<
quotaLimiting: deps.quotaLimiting,
redis: this.redis,
valkeyShadow: this.valkeyShadow,
+ deadLetterService: this.deadLetterService,
})
this.hogFlowPipeline = new HogFlowInvocationPipeline(config, {
hogFlowManager: this.hogFlowManager,
@@ -62,13 +74,18 @@ export class CdpEventsConsumer<
quotaLimiting: deps.quotaLimiting,
redis: this.redis,
valkeyShadow: this.valkeyShadow,
+ deadLetterService: this.deadLetterService,
})
}
public async processBatch(
- invocationGlobals: HogFunctionInvocationGlobals[]
+ invocationGlobals: HogFunctionInvocationGlobals[],
+ /** Runs after the build and before anything is queued, so a throw here queues nothing. */
+ beforeQueue?: () => Promise<void>
): Promise<{ backgroundTask: Promise<any>; invocations: CyclotronJobInvocation[] }> {
if (!invocationGlobals.length) {
+ // A batch whose every message failed to parse still has records to write.
+ await beforeQueue?.()
return { backgroundTask: Promise.resolve(), invocations: [] }
}
@@ -90,6 +107,8 @@ export class CdpEventsConsumer<
const invocationsToBeQueued = [...hogInvocations, ...hogflowInvocations]
+ await beforeQueue?.()
+
// Emit a `running` lifecycle row for each freshly-created invocation.
// This fires ONCE per invocation_id at creation — not on every dequeue
// — so the runs UI can show in-flight work without us writing duplicate
@@ -180,7 +199,11 @@ export class CdpEventsConsumer<
return
}
- events.push(convertToHogFunctionInvocationGlobals(clickHouseEvent, team, this.config.SITE_URL))
+ const globals = convertToHogFunctionInvocationGlobals(clickHouseEvent, team, this.config.SITE_URL)
+ // The one place holding both. A failure found later in the pipeline carries
+ // these globals, and this is how it gets back to the bytes to park.
+ this.messageByGlobals.set(globals, message)
+ events.push(globals)
} catch (e) {
// A dependency outage is not a poison message. Rethrowing fails the batch, so the
// offsets stay put and the consumer retries, instead of dropping every event of a
@@ -188,8 +211,17 @@ export class CdpEventsConsumer<
if (e?.isRetriable === true) {
throw e
}
+ // A thrown non-Error has no `message`, and an undefined reason fails the
+ // produce, which stalls the partition on the message this exists to keep.
+ const error = e instanceof Error ? e.message : String(e)
logger.error('Error parsing message', e)
- counterParseError.labels({ error: e.message }).inc()
+ counterParseError.labels({ error }).inc()
+ // Parked rather than dropped: a schema we cannot read today is often one a
+ // later version can.
+ this.deadLetterService.recordMessageFailure(message, {
+ step: 'parse',
+ error,
+ })
}
})
)
@@ -208,6 +240,7 @@ export class CdpEventsConsumer<
public override async start(): Promise<void> {
await super.start()
await this.startQueueProducers()
+ await this.deadLetterService.checkTopic()
// Start consuming messages
await this.kafkaConsumer.connect(async (messages) => {
logger.info('🔁', `${this.name} - handling batch`, {
@@ -216,7 +249,11 @@ export class CdpEventsConsumer<
return await instrumentFn('cdpConsumer.handleEachBatch', async () => {
const invocationGlobals = await this._parseKafkaBatch(messages)
- const { backgroundTask } = await this.processBatch(invocationGlobals)
+ // Awaited, not backgrounded: the offsets for these messages are stored once this
+ // handler resolves, so a record has to exist by then or the event is gone.
+ const { backgroundTask } = await this.processBatch(invocationGlobals, () =>
+ this.deadLetterService.produceForBatch(messages)
+ )
return { backgroundTask }
})
diff --git a/nodejs/src/cdp/outputs/outputs.ts b/nodejs/src/cdp/outputs/outputs.ts
index fefb8cd96ae8..6cda4e049958 100644
--- a/nodejs/src/cdp/outputs/outputs.ts
+++ b/nodejs/src/cdp/outputs/outputs.ts
@@ -9,3 +9,6 @@
export const WAREHOUSE_SOURCE_WEBHOOKS_OUTPUT = 'warehouse_source_webhooks' as const
export type WarehouseSourceWebhooksOutput = typeof WAREHOUSE_SOURCE_WEBHOOKS_OUTPUT
+
+export const CDP_EVENTS_DLQ_OUTPUT = 'cdp_events_dlq' as const
+export type CdpEventsDlqOutput = typeof CDP_EVENTS_DLQ_OUTPUT
diff --git a/nodejs/src/cdp/outputs/registry.ts b/nodejs/src/cdp/outputs/registry.ts
index 3fddd544bc31..94b64ebbfaf9 100644
--- a/nodejs/src/cdp/outputs/registry.ts
+++ b/nodejs/src/cdp/outputs/registry.ts
@@ -6,7 +6,7 @@ import {
} from '~/common/outputs'
import { IngestionOutputsBuilder } from '~/common/outputs/ingestion-outputs-builder'
-import { WAREHOUSE_SOURCE_WEBHOOKS_OUTPUT } from './outputs'
+import { CDP_EVENTS_DLQ_OUTPUT, WAREHOUSE_SOURCE_WEBHOOKS_OUTPUT } from './outputs'
/**
* Outputs the CDP deployments write to. Each output's topic + producer are
@@ -17,6 +17,7 @@ import { WAREHOUSE_SOURCE_WEBHOOKS_OUTPUT } from './outputs'
* (also used for legacy plugin app metrics since they share the
* `clickhouse_app_metrics2` schema).
* - `WAREHOUSE_SOURCE_WEBHOOKS_OUTPUT` — warehouse source webhook payloads.
+ * - `CDP_EVENTS_DLQ_OUTPUT` — events that matched a function but produced no invocation.
*/
export function createCdpOutputsRegistry() {
return new IngestionOutputsBuilder()
@@ -40,4 +41,8 @@ export function createCdpOutputsRegistry() {
topicKey: 'CDP_WAREHOUSE_SOURCE_WEBHOOKS_TOPIC',
producerKey: 'CDP_WAREHOUSE_SOURCE_WEBHOOKS_PRODUCER',
})
+ .register(CDP_EVENTS_DLQ_OUTPUT, {
+ topicKey: 'CDP_EVENTS_DLQ_TOPIC',
+ producerKey: 'CDP_EVENTS_DLQ_PRODUCER',
+ })
}
diff --git a/nodejs/src/cdp/services/dead-letter/cdp-dead-letter.service.test.ts b/nodejs/src/cdp/services/dead-letter/cdp-dead-letter.service.test.ts
new file mode 100644
index 000000000000..8d6ab9e5c30d
--- /dev/null
+++ b/nodejs/src/cdp/services/dead-letter/cdp-dead-letter.service.test.ts
@@ -0,0 +1,317 @@
+import { Message } from 'node-rdkafka'
+
+import { CdpOutputs } from '../../cdp-services'
+import { CDP_EVENTS_DLQ_OUTPUT } from '../../outputs/outputs'
+import { HogFunctionInvocationGlobals, InvocationBuildFailure } from '../../types'
+import { CdpDeadLetterService } from './cdp-dead-letter.service'
+
+describe('CdpDeadLetterService', () => {
+ let produce: jest.Mock
+ let outputs: CdpOutputs
+ let messagesByGlobals: Map<HogFunctionInvocationGlobals, Message>
+
+ const message = (uuid: string, offset = 10): Message =>
+ ({
+ value: Buffer.from(JSON.stringify({ uuid })),
+ key: Buffer.from(uuid),
+ topic: 'clickhouse_events_json',
+ partition: 3,
+ offset,
+ size: 0,
+ headers: [{ token: Buffer.from('phc_abc') }],
+ }) as unknown as Message
+
+ const globalsFor = (teamId: number, uuid: string): HogFunctionInvocationGlobals =>
+ ({ project: { id: teamId }, event: { uuid } }) as HogFunctionInvocationGlobals
+
+ const defaultGlobals = globalsFor(2, 'event-1')
+
+ const failure = (overrides: Partial<InvocationBuildFailure> = {}): InvocationBuildFailure => ({
+ sourceId: 'fn-1',
+ sourceKind: 'hog_function',
+ step: 'inputs',
+ error: 'Invalid arguments',
+ ...overrides,
+ })
+
+ const createService = (enabled = true): CdpDeadLetterService =>
+ new CdpDeadLetterService(
+ { CDP_DLQ_ENABLED: enabled, CDP_DLQ_BATCH_FAIL_RATIO: 0.1 },
+ {
+ outputs,
+ output: CDP_EVENTS_DLQ_OUTPUT,
+ consumerGroup: 'cdp-processed-events-consumer',
+ resolveMessage: (globals) => messagesByGlobals.get(globals),
+ }
+ )
+
+ beforeEach(() => {
+ produce = jest.fn().mockResolvedValue(undefined)
+ outputs = { produce } as unknown as CdpOutputs
+ messagesByGlobals = new Map()
+ messagesByGlobals.set(defaultGlobals, message('event-1'))
+ })
+
+ it('parks the original bytes with the source position and the failed function', async () => {
+ const service = createService()
+ service.recordBuildFailures(defaultGlobals, [failure()])
+
+ await service.produceForBatch([message('event-1')])
+
+ expect(produce).toHaveBeenCalledTimes(1)
+ expect(produce).toHaveBeenCalledWith(CDP_EVENTS_DLQ_OUTPUT, {
+ value: Buffer.from(JSON.stringify({ uuid: 'event-1' })),
+ key: Buffer.from('event-1'),
+ headers: {
+ token: 'phc_abc',
+ dlq_step: 'inputs',
+ dlq_reason: 'Invalid arguments',
+ dlq_class: '',
+ dlq_timestamp: expect.any(String),
+ dlq_topic: 'clickhouse_events_json',
+ dlq_partition: '3',
+ dlq_offset: '10',
+ dlq_consumer_group: 'cdp-processed-events-consumer',
+ dlq_team_id: '2',
+ dlq_hog_function_ids: 'fn-1',
+ dlq_hog_flow_ids: '',
+ dlq_kinds: 'hog_function',
+ },
+ })
+ })
+
+ it('parks only the failures we can fix, and says which class parked them', async () => {
+ // The owner's classes would fill the queue with events no rebuild can change.
+ const service = createService()
+ service.recordBuildFailures(defaultGlobals, [
+ failure({ sourceId: 'ours', errorClass: 'drift' }),
+ failure({ sourceId: 'theirs', errorClass: 'data' }),
+ failure({ sourceId: 'timed-out', errorClass: 'limit' }),
+ failure({ sourceId: 'unstamped', errorClass: 'legacy' }),
+ ])
+
+ await service.produceForBatch([message('event-1')])
+
+ expect(produce).toHaveBeenCalledTimes(1)
+ expect(produce).toHaveBeenCalledWith(
+ CDP_EVENTS_DLQ_OUTPUT,
+ expect.objectContaining({
+ headers: expect.objectContaining({ dlq_hog_function_ids: 'ours', dlq_class: 'drift' }),
+ })
+ )
+ })
+
+ it('parks nothing when every failure belongs to the owner', async () => {
+ const service = createService()
+ service.recordBuildFailures(defaultGlobals, [failure({ errorClass: 'data' }), failure({ errorClass: 'limit' })])
+
+ await service.produceForBatch([message('event-1')])
+
+ expect(produce).not.toHaveBeenCalled()
+ })
+
+ it('writes one record per event and step, naming every source that failed at that step', async () => {
+ const service = createService()
+ service.recordBuildFailures(defaultGlobals, [
+ failure({ sourceId: 'fn-1' }),
+ failure({ sourceId: 'fn-2' }),
+ failure({ sourceId: 'flow-1', sourceKind: 'hog_flow' }),
+ failure({ sourceId: 'fn-3', step: 'filter' }),
+ ])
+
+ await service.produceForBatch([message('event-1')])
+
+ expect(produce).toHaveBeenCalledTimes(2)
+ const byStep = Object.fromEntries(produce.mock.calls.map(([, m]) => [m.headers.dlq_step, m.headers]))
+ expect(byStep.inputs).toMatchObject({ dlq_hog_function_ids: 'fn-1,fn-2', dlq_hog_flow_ids: 'flow-1' })
+ expect(byStep.filter).toMatchObject({ dlq_hog_function_ids: 'fn-3', dlq_hog_flow_ids: '' })
+ })
+
+ it('parks a message that could not be parsed, naming no function', async () => {
+ const service = createService()
+ service.recordMessageFailure(message('event-1'), {
+ step: 'parse',
+ error: 'Unexpected end of JSON input',
+ })
+
+ await service.produceForBatch([])
+
+ expect(produce).toHaveBeenCalledTimes(1)
+ expect(produce.mock.calls[0][1].headers).toMatchObject({
+ dlq_step: 'parse',
+ dlq_reason: 'Unexpected end of JSON input',
+ // No team and no functions: a replay rebuilds everything the team has, because nothing
+ // was built the first time.
+ dlq_team_id: '',
+ dlq_hog_function_ids: '',
+ dlq_hog_flow_ids: '',
+ })
+ })
+
+ it('parks an event that threw outside the handled failures', async () => {
+ const service = createService()
+ service.recordProcessFailure(defaultGlobals, new Error('Cannot read properties of undefined'), 'hog_function')
+
+ await service.produceForBatch([message('event-1')])
+
+ expect(produce.mock.calls[0][1].headers).toMatchObject({
+ dlq_step: 'process',
+ dlq_team_id: '2',
+ dlq_hog_function_ids: '',
+ })
+ })
+
+ it('fails the batch instead of parking it when most of it throws unexpectedly', async () => {
+ const service = createService()
+ const messages = [10, 11, 12, 13].map((offset) => message(`event-${offset}`, offset))
+ for (const [index, uuid] of ['event-10', 'event-11', 'event-12'].entries()) {
+ const globals = globalsFor(2, uuid)
+ messagesByGlobals.set(globals, messages[index])
+ service.recordProcessFailure(globals, new Error('boom'), 'hog_function')
+ }
+
+ await expect(service.produceForBatch(messages)).rejects.toThrow('Refusing to dead-letter 3 of 4')
+ expect(produce).not.toHaveBeenCalled()
+ })
+
+ it('parks a lone unexpected failure rather than breaking on a small batch', async () => {
+ // A ratio says nothing about one message. Breaking here would stall the partition on the
+ // very event this path exists to park.
+ const service = createService()
+ service.recordProcessFailure(defaultGlobals, new Error('boom'), 'hog_function')
+
+ await service.produceForBatch([message('event-1')])
+
+ expect(produce).toHaveBeenCalledTimes(1)
+ })
+
+ it('counts events, not failures, when two pipelines both throw on the same event', async () => {
+ // The function and flow pipelines each record against one event, so counting entries let
+ // two bad events reach the floor of three and stall a partition early.
+ const service = createService()
+ const messages = [message('event-1', 10), message('event-2', 11)]
+ const second = globalsFor(2, 'event-2')
+ messagesByGlobals.set(second, messages[1])
+ for (const globals of [defaultGlobals, second]) {
+ service.recordProcessFailure(globals, new Error('from the function pipeline'), 'hog_function')
+ service.recordProcessFailure(globals, new Error('from the flow pipeline'), 'hog_function')
+ }
+
+ await service.produceForBatch(messages)
+
+ expect(produce).toHaveBeenCalledTimes(2)
+ })
+
+ it('reports that a disabled queue retained nothing, so a caller can let the error through', () => {
+ const service = createService(false)
+
+ expect(service.recordProcessFailure(defaultGlobals, new Error('boom'), 'hog_function')).toBe(false)
+ })
+
+ it('still parks a whole batch of filter and input failures', async () => {
+ // One broken builtin legitimately breaks every function in a batch. Those records are
+ // exactly what the replay needs, so the ratio must not apply to them.
+ //
+ // Sized to clear the breaker on every axis: three events is the floor, and three of four
+ // messages is past the ratio. Counting these would fail the batch here.
+ const service = createService()
+ const messages = [10, 11, 12, 13].map((offset) => message(`event-${offset}`, offset))
+ for (const [index, uuid] of ['event-10', 'event-11', 'event-12'].entries()) {
+ const globals = globalsFor(2, uuid)
+ messagesByGlobals.set(globals, messages[index])
+ service.recordBuildFailures(globals, [failure({ step: index === 0 ? 'filter' : 'inputs' })])
+ }
+
+ await service.produceForBatch(messages)
+
+ expect(produce).toHaveBeenCalledTimes(3)
+ })
+
+ it('gives each team its own record when two events collide on the same client-supplied ID', async () => {
+ // Event IDs come from the client, so two teams can send the same one on a topic that
+ // carries every team. Nothing here keys on the ID, so there is nothing to collide.
+ const service = createService()
+ const teamA = globalsFor(2, 'shared')
+ const teamB = globalsFor(3, 'shared')
+ const messageA = message('a', 10)
+ const messageB = message('b', 11)
+ messagesByGlobals.set(teamA, messageA)
+ messagesByGlobals.set(teamB, messageB)
+
+ service.recordBuildFailures(teamA, [failure({ sourceId: 'fn-a' })])
+ service.recordBuildFailures(teamB, [failure({ sourceId: 'fn-b' })])
+ await service.produceForBatch([messageA, messageB])
+
+ expect(produce).toHaveBeenCalledTimes(2)
+ const byTeam = Object.fromEntries(produce.mock.calls.map(([, m]) => [m.headers.dlq_team_id, m]))
+ expect(byTeam['2'].value).toEqual(messageA.value)
+ expect(byTeam['2'].headers.dlq_hog_function_ids).toBe('fn-a')
+ expect(byTeam['3'].value).toEqual(messageB.value)
+ expect(byTeam['3'].headers.dlq_hog_function_ids).toBe('fn-b')
+ })
+
+ it('produces nothing while the queue is disabled', async () => {
+ const service = createService(false)
+ service.recordBuildFailures(defaultGlobals, [failure()])
+
+ await service.produceForBatch([message('event-1')])
+
+ expect(produce).not.toHaveBeenCalled()
+ })
+
+ it('fails the batch when a record cannot be produced', async () => {
+ produce.mockRejectedValue(new Error('broker unavailable'))
+ const service = createService()
+ service.recordBuildFailures(defaultGlobals, [failure()])
+
+ await expect(service.produceForBatch([message('event-1')])).rejects.toThrow('broker unavailable')
+ })
+
+ it('fails the batch when a failure has no source message left to park', async () => {
+ // Nothing to write means nothing to replay, so advancing past the event loses it.
+ const service = createService()
+ const untracked = globalsFor(2, 'event-untracked')
+ service.recordBuildFailures(untracked, [failure()])
+
+ await expect(service.produceForBatch([message('event-untracked')])).rejects.toThrow('No source message')
+ expect(produce).not.toHaveBeenCalled()
+ })
+
+ it('parks every failure it accepted, across steps, events and sources', async () => {
+ // The one invariant that matters: nothing recorded may quietly fail to reach the topic.
+ // Counts the records rather than inspecting them, so a new step cannot slip through.
+ const service = createService()
+ const second = globalsFor(7, 'event-2')
+ const messages = [message('event-1', 10), message('event-2', 11), message('event-3', 12)]
+ messagesByGlobals.set(second, messages[1])
+
+ service.recordBuildFailures(defaultGlobals, [failure({ sourceId: 'fn-1' }), failure({ sourceId: 'fn-2' })])
+ service.recordBuildFailures(defaultGlobals, [failure({ sourceId: 'flow-1', sourceKind: 'hog_flow' })])
+ service.recordBuildFailures(second, [failure({ step: 'filter', sourceId: 'fn-3' })])
+ service.recordProcessFailure(second, new Error('boom'), 'hog_function')
+ service.recordMessageFailure(messages[2], { step: 'parse', error: 'not json' })
+
+ await service.produceForBatch(messages)
+
+ // event-1 inputs, event-2 filter, event-2 process, event-3 parse.
+ expect(produce).toHaveBeenCalledTimes(4)
+ const steps = produce.mock.calls.map((call) => call[1].headers.dlq_step).sort()
+ expect(steps).toEqual(['filter', 'inputs', 'parse', 'process'])
+ const named = produce.mock.calls
+ .flatMap((call) => [call[1].headers.dlq_hog_function_ids, call[1].headers.dlq_hog_flow_ids])
+ .filter(Boolean)
+ .flatMap((ids: string) => ids.split(','))
+ .sort()
+ expect(named).toEqual(['flow-1', 'fn-1', 'fn-2', 'fn-3'])
+ })
+
+ it('clears recorded failures so the next batch does not repark them', async () => {
+ const service = createService()
+ service.recordBuildFailures(defaultGlobals, [failure()])
+ await service.produceForBatch([message('event-1')])
+
+ await service.produceForBatch([message('event-1')])
+
+ expect(produce).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/nodejs/src/cdp/services/dead-letter/cdp-dead-letter.service.ts b/nodejs/src/cdp/services/dead-letter/cdp-dead-letter.service.ts
new file mode 100644
index 000000000000..273d37e5eca7
--- /dev/null
+++ b/nodejs/src/cdp/services/dead-letter/cdp-dead-letter.service.ts
@@ -0,0 +1,320 @@
+import { Message } from 'node-rdkafka'
+import { Counter } from 'prom-client'
+
+import { logger } from '~/common/utils/logger'
+
+import type { CdpOutputs } from '../../cdp-services'
+import type { CdpEventsDlqOutput } from '../../outputs/outputs'
+import type { DeadLetterStep, HogFunctionInvocationGlobals, InvocationBuildFailure } from '../../types'
+import type { HogErrorClass } from '../../utils/hog-error-classification'
+
+/** In memory only. What leaves is the original event bytes plus string headers. */
+type PendingFailure = {
+ /** Absent when nothing was built for the event, so no single function is at fault. */
+ sourceId?: string
+ sourceKind?: 'hog_function' | 'hog_flow'
+ step: DeadLetterStep
+ error: string
+ errorClass?: HogErrorClass
+}
+
+/**
+ * Only these can be fixed by us, so only these are worth a replay. A replay reproduces the
+ * owner's classes unchanged: the event still lacks the property, the program still exhausts its
+ * budget. `legacy` is bytecode with no stamp, so whose fault it is cannot be established.
+ */
+const PARKED_CLASSES: ReadonlySet<HogErrorClass> = new Set<HogErrorClass>(['drift', 'bug', 'platform'])
+
+/** A step that runs no VM produces no class, and those failures are ours by construction. */
+const isOurs = (failure: { errorClass?: HogErrorClass }): boolean =>
+ failure.errorClass === undefined || PARKED_CLASSES.has(failure.errorClass)
+
+export type CdpDlqOutput = CdpEventsDlqOutput
+
+const counterDeadLetterMessages = new Counter({
+ name: 'cdp_dead_letter_messages_total',
+ help: 'An event was parked on a CDP dead-letter topic',
+ labelNames: ['output', 'step'],
+})
+
+const counterFailuresByClass = new Counter({
+ name: 'cdp_dead_letter_build_failures_total',
+ help: 'A build failure the dead-letter service saw, by class and whether it was parked',
+ labelNames: ['step', 'class', 'parked'],
+})
+
+const counterDeadLetterProduceFailures = new Counter({
+ name: 'cdp_dead_letter_produce_failures_total',
+ help: 'A CDP dead-letter record could not be produced, so its batch failed',
+ labelNames: ['output'],
+})
+
+const counterProcessFailures = new Counter({
+ name: 'cdp_dead_letter_process_failures_total',
+ help: 'An event threw outside the failures the pipeline handles per function',
+ labelNames: ['output'],
+})
+
+const counterDeadLetterBatchFailures = new Counter({
+ name: 'cdp_dead_letter_batch_failures_total',
+ help: 'A batch failed instead of being dead-lettered, because too much of it was failing',
+ labelNames: ['output'],
+})
+
+/** An error message can quote a template value, so it is truncated and never indexed. */
+const MAX_REASON_BYTES = 1024
+
+/** A ratio says nothing on a small batch: one bad event in a batch of one is 100% of it. */
+const MIN_UNEXPECTED_TO_BREAK = 3
+
+export interface CdpDeadLetterServiceConfig {
+ CDP_DLQ_ENABLED: boolean
+ CDP_DLQ_BATCH_FAIL_RATIO: number
+}
+
+export class DeadLetterCircuitBreakerError extends Error {
+ constructor(parked: number, batchSize: number) {
+ super(
+ `Refusing to dead-letter ${parked} of ${batchSize} messages: an unexpected failure this ` +
+ 'wide is a bug in this deployment, not poison in the stream'
+ )
+ this.name = 'DeadLetterCircuitBreakerError'
+ }
+}
+
+export interface CdpDeadLetterServiceOptions {
+ outputs: CdpOutputs
+ output: CdpDlqOutput
+ consumerGroup: string
+ resolveMessage: (globals: HogFunctionInvocationGlobals) => Message | undefined
+}
+
+/**
+ * Parks events that matched a function but produced no invocation.
+ *
+ * Headers name the functions that failed, so a replay rebuilds only those.
+ *
+ * Known gap: a function with mappings is named as a whole, so a replay re-runs a mapping that
+ * already delivered. Mappings carry no stable id, only a position that moves when the config is
+ * edited. Accepted over a schema change.
+ */
+/**
+ * What the invocation pipelines need from a dead-letter service.
+ *
+ * Narrow on purpose, so a consumer with no topic to park on can still be told what failed. The
+ * replay worker passes a collector rather than nothing, because a rebuild that fails the same way
+ * a second time has to block the run instead of committing past the record.
+ */
+export interface InvocationFailureSink {
+ recordBuildFailures(globals: HogFunctionInvocationGlobals, failures: InvocationBuildFailure[]): void
+ /** False means the event was not retained, so the caller must let the error through. */
+ recordProcessFailure(
+ globals: HogFunctionInvocationGlobals,
+ error: unknown,
+ sourceKind: 'hog_function' | 'hog_flow'
+ ): boolean
+}
+
+export class CdpDeadLetterService implements InvocationFailureSink {
+ /** Kept grouped by event, which is the shape the records are written in. */
+ private failures: { globals: HogFunctionInvocationGlobals; failures: PendingFailure[] }[] = []
+ private messageFailures: { message: Message; failure: PendingFailure }[] = []
+
+ constructor(
+ private config: CdpDeadLetterServiceConfig,
+ private options: CdpDeadLetterServiceOptions
+ ) {}
+
+ /** Without this a misrouted topic hides until the first event that needed parking. */
+ public async checkTopic(): Promise<void> {
+ if (!this.config.CDP_DLQ_ENABLED) {
+ return
+ }
+ const failures = await this.options.outputs.checkTopics()
+ if (failures.includes(this.options.output)) {
+ throw new Error(
+ `CDP_DLQ_ENABLED is on but the dead-letter topic for ${this.options.output} is not reachable — ` +
+ 'refusing to start, because events would be dropped the moment one needed parking'
+ )
+ }
+ }
+
+ public recordBuildFailures(globals: HogFunctionInvocationGlobals, failures: InvocationBuildFailure[]): void {
+ if (!this.config.CDP_DLQ_ENABLED || !failures.length) {
+ return
+ }
+ const ours = failures.filter(isOurs)
+ for (const failure of failures) {
+ counterFailuresByClass
+ .labels({ step: failure.step, class: failure.errorClass ?? 'unknown', parked: String(isOurs(failure)) })
+ .inc()
+ }
+ if (!ours.length) {
+ return
+ }
+ this.failures.push({ globals, failures: ours })
+ }
+
+ /**
+ * Names no single source, because the throw was not attributable to one, but does name the kind.
+ *
+ * The two pipelines run against the same event, so one can queue its invocations while the
+ * other throws. Without the kind a replay would rebuild both, re-delivering whatever the
+ * healthy pipeline already sent.
+ *
+ * False means the event was not retained, so the caller must let the error through.
+ */
+ public recordProcessFailure(
+ globals: HogFunctionInvocationGlobals,
+ error: unknown,
+ sourceKind: 'hog_function' | 'hog_flow'
+ ): boolean {
+ if (!this.config.CDP_DLQ_ENABLED) {
+ return false
+ }
+ this.failures.push({
+ globals,
+ failures: [{ step: 'process', sourceKind, error: error instanceof Error ? error.message : String(error) }],
+ })
+ counterProcessFailures.labels({ output: this.options.output }).inc()
+ return true
+ }
+
+ /** For a message that never became an event, so there are no globals to attach it to. */
+ public recordMessageFailure(message: Message, failure: Omit<PendingFailure, 'sourceId' | 'sourceKind'>): void {
+ if (!this.config.CDP_DLQ_ENABLED) {
+ return
+ }
+ this.messageFailures.push({ message, failure })
+ }
+
+ /**
+ * Produces one record per event and step, then clears the buffer.
+ *
+ * A produce failure rethrows: advancing past the source message with no record loses the event.
+ */
+ public async produceForBatch(messages: Message[]): Promise<void> {
+ const failures = this.failures
+ const messageFailures = this.messageFailures
+ this.failures = []
+ this.messageFailures = []
+
+ if (!failures.length && !messageFailures.length) {
+ return
+ }
+
+ // Stalling the partition beats parking a whole batch: draining the stream into a side topic
+ // leaves lag, health and throughput all reading normal, so nobody notices. `filter` and
+ // `inputs` never count, because one broken builtin legitimately breaks a whole batch and
+ // those records are the point.
+ const unexpected = new Set(
+ failures
+ .filter((entry) => entry.failures.some((failure) => failure.step === 'process'))
+ .map((entry) => entry.globals)
+ ).size
+ if (
+ unexpected >= MIN_UNEXPECTED_TO_BREAK &&
+ messages.length &&
+ unexpected > messages.length * this.config.CDP_DLQ_BATCH_FAIL_RATIO
+ ) {
+ counterDeadLetterBatchFailures.labels({ output: this.options.output }).inc()
+ throw new DeadLetterCircuitBreakerError(unexpected, messages.length)
+ }
+
+ // Grouped on the globals object itself, so one record covers one event and one step. Both
+ // pipelines record against the same event, so an event can arrive here more than once.
+ const records = new Map<HogFunctionInvocationGlobals, Map<DeadLetterStep, PendingFailure[]>>()
+ for (const entry of failures) {
+ const byStep = records.get(entry.globals) ?? new Map<DeadLetterStep, PendingFailure[]>()
+ for (const failure of entry.failures) {
+ const forStep = byStep.get(failure.step)
+ if (forStep) {
+ forStep.push(failure)
+ } else {
+ byStep.set(failure.step, [failure])
+ }
+ }
+ records.set(entry.globals, byStep)
+ }
+
+ try {
+ await Promise.all([
+ ...messageFailures.map(({ message, failure }) => this.produceRecord(message, null, [failure])),
+ ...[...records.entries()].flatMap(([globals, byStep]) => {
+ const message = this.options.resolveMessage(globals)
+ if (!message) {
+ // A consumer that stopped tracking a message it built globals from. There
+ // are no bytes to park, so failing the batch is the only way to keep the
+ // event. This throws inside the try below, so it is counted and logged.
+ throw new Error(
+ `No source message for a build failure on team ${globals.project.id}: the event ` +
+ 'cannot be parked, so the batch fails rather than advancing past it'
+ )
+ }
+ return [...byStep.values()].map((group) => this.produceRecord(message, globals.project.id, group))
+ }),
+ ])
+ } catch (error) {
+ counterDeadLetterProduceFailures.labels({ output: this.options.output }).inc()
+ logger.error('🔴', '[CdpDeadLetterService] Failed to produce dead-letter records', { error })
+ throw error
+ }
+ }
+
+ private async produceRecord(message: Message, teamId: number | null, group: PendingFailure[]): Promise<void> {
+ const step: DeadLetterStep = group[0].step
+ const hogFunctionIds = group.flatMap((f) => (f.sourceKind === 'hog_function' && f.sourceId ? [f.sourceId] : []))
+ const hogFlowIds = group.flatMap((f) => (f.sourceKind === 'hog_flow' && f.sourceId ? [f.sourceId] : []))
+ const kinds = [...new Set(group.flatMap((f) => (f.sourceKind ? [f.sourceKind] : [])))]
+
+ await this.options.outputs.produce(this.options.output, {
+ value: message.value,
+ key: message.key ?? null,
+ headers: {
+ ...copyHeaders(message),
+
+ // Mechanism. What the replay worker reads. `dlq_step` marks the record as one of
+ // ours, and the id lists say what to rebuild — empty means rebuild every source
+ // for the team, because nothing was built the first time.
+ dlq_step: step,
+ dlq_hog_function_ids: hogFunctionIds.join(','),
+ dlq_hog_flow_ids: hogFlowIds.join(','),
+ // Which kinds a replay may rebuild. Carries the whole answer when no id is named:
+ // empty means nothing was built at all, so both kinds are in scope.
+ dlq_kinds: kinds.join(','),
+
+ // Diagnostics. Nothing branches on these. They are what a person has to work with
+ // when they open the topic and need to know what failed, for whom, and where it
+ // came from, without deserializing the bodies.
+ dlq_reason: truncate(group[0].error, MAX_REASON_BYTES),
+ dlq_class: group[0].errorClass ?? '',
+ dlq_timestamp: new Date().toISOString(),
+ dlq_team_id: teamId === null ? '' : String(teamId),
+ dlq_topic: message.topic,
+ dlq_partition: String(message.partition),
+ dlq_offset: String(message.offset),
+ dlq_consumer_group: this.options.consumerGroup,
+ },
+ })
+
+ counterDeadLetterMessages.labels({ output: this.options.output, step }).inc()
+ }
+}
+
+function copyHeaders(message: Message): Record<string, string> {
+ const copied: Record<string, string> = {}
+ for (const header of message.headers ?? []) {
+ for (const [key, value] of Object.entries(header)) {
+ if (value === undefined) {
+ continue
+ }
+ copied[key] = Buffer.isBuffer(value) ? value.toString() : String(value)
+ }
+ }
+ return copied
+}
+
+function truncate(value: string, maxBytes: number): string {
+ const buffer = Buffer.from(value, 'utf8')
+ return buffer.byteLength <= maxBytes ? value : buffer.subarray(0, maxBytes).toString('utf8')
+}
diff --git a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.ts b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.ts
index 02cbc73091c0..6e4ae9c5d948 100644
--- a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.ts
+++ b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.ts
@@ -57,7 +57,9 @@ describe('HogFlowInvocationPipeline', () => {
} as unknown as jest.Mocked<HogFlowManagerService>
hogFlowExecutor = {
- buildHogFlowInvocations: jest.fn().mockResolvedValue({ invocations: [], metrics: [], logs: [] }),
+ buildHogFlowInvocations: jest
+ .fn()
+ .mockResolvedValue({ invocations: [], metrics: [], logs: [], buildFailures: [] }),
} as unknown as jest.Mocked<HogFlowExecutorService>
hogWatcher = {
@@ -107,7 +109,12 @@ describe('HogFlowInvocationPipeline', () => {
it('returns invocations for matching hogflows and queues triggered metric', async () => {
const inv = makeHogFlowInvocation()
- hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
+ hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({
+ invocations: [inv],
+ metrics: [],
+ logs: [],
+ buildFailures: [],
+ })
hogWatcher.getEffectiveStates.mockResolvedValue({ [inv.hogFlow.id]: { state: HogWatcherState.healthy } } as any)
rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])
@@ -125,9 +132,20 @@ describe('HogFlowInvocationPipeline', () => {
)
})
+ it('rejects rather than dropping an event when no dead-letter service can keep it', async () => {
+ hogFlowExecutor.buildHogFlowInvocations.mockRejectedValue(new Error('builder walked off a cliff'))
+
+ await expect(pipeline.buildInvocations([makeGlobals()])).rejects.toThrow('builder walked off a cliff')
+ })
+
it('drops rate-limited invocations with metric + log', async () => {
const inv = makeHogFlowInvocation()
- hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
+ hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({
+ invocations: [inv],
+ metrics: [],
+ logs: [],
+ buildFailures: [],
+ })
hogWatcher.getEffectiveStates.mockResolvedValue({ [inv.hogFlow.id]: { state: HogWatcherState.healthy } } as any)
rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: true }]])
@@ -144,7 +162,12 @@ describe('HogFlowInvocationPipeline', () => {
it('drops quota-limited invocations', async () => {
// hogflow quota helper short-circuits when billable_action_types is empty
const inv = makeHogFlowInvocation('flow-1', { billable_action_types: ['function_email'] })
- hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
+ hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({
+ invocations: [inv],
+ metrics: [],
+ logs: [],
+ buildFailures: [],
+ })
hogWatcher.getEffectiveStates.mockResolvedValue({ [inv.hogFlow.id]: { state: HogWatcherState.healthy } } as any)
rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])
quotaLimiting.isTeamQuotaLimited.mockResolvedValue(true)
@@ -155,7 +178,12 @@ describe('HogFlowInvocationPipeline', () => {
it('drops invocations for disabled hogflows', async () => {
const inv = makeHogFlowInvocation()
- hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
+ hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({
+ invocations: [inv],
+ metrics: [],
+ logs: [],
+ buildFailures: [],
+ })
hogWatcher.getEffectiveStates.mockResolvedValue({
[inv.hogFlow.id]: { state: HogWatcherState.disabled },
} as any)
@@ -172,7 +200,12 @@ describe('HogFlowInvocationPipeline', () => {
it('sets queuePriority=2 for degraded hogflows but does not change queue', async () => {
const inv = makeHogFlowInvocation()
- hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
+ hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({
+ invocations: [inv],
+ metrics: [],
+ logs: [],
+ buildFailures: [],
+ })
hogWatcher.getEffectiveStates.mockResolvedValue({
[inv.hogFlow.id]: { state: HogWatcherState.degraded },
} as any)
@@ -187,7 +220,12 @@ describe('HogFlowInvocationPipeline', () => {
it('drops masked invocations', async () => {
const inv = makeHogFlowInvocation()
- hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
+ hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({
+ invocations: [inv],
+ metrics: [],
+ logs: [],
+ buildFailures: [],
+ })
hogWatcher.getEffectiveStates.mockResolvedValue({ [inv.hogFlow.id]: { state: HogWatcherState.healthy } } as any)
rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])
hogMasker.filterByMasking.mockResolvedValue({ masked: [inv], notMasked: [], release: async () => {} })
diff --git a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts
index ab169cd31354..f6472523649a 100644
--- a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts
+++ b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts
@@ -18,6 +18,7 @@ import {
MinimalAppMetric,
} from '../types'
import { dualRead } from '../utils/dual-store'
+import { InvocationFailureSink } from './dead-letter/cdp-dead-letter.service'
import { HogFlowExecutorService } from './hogflows/hogflow-executor.service'
import { HogFlowManagerService } from './hogflows/hogflow-manager.service'
import { shouldBlockHogFlowDueToQuota } from './hogflows/hogflow-quota-limiting'
@@ -41,6 +42,8 @@ export interface HogFlowInvocationPipelineDeps {
quotaLimiting: QuotaLimiting
redis: RedisV2
valkeyShadow: CdpValkeyShadowPools
+ /** Absent for consumers that have no dead-letter topic; their build failures stay metrics-only. */
+ deadLetterService?: InvocationFailureSink
}
/**
@@ -91,15 +94,26 @@ export class HogFlowInvocationPipeline {
? teamHogFlows.filter((flow) => eligibilityFn(flow, globals))
: teamHogFlows
- const { invocations, metrics, logs } = await this.deps.hogFlowExecutor.buildHogFlowInvocations(
- eligibleFlows,
- globals
- )
+ try {
+ const { invocations, metrics, logs, buildFailures } =
+ await this.deps.hogFlowExecutor.buildHogFlowInvocations(eligibleFlows, globals)
- this.deps.hogFunctionMonitoringService.queueAppMetrics(metrics, 'hog_flow')
- this.deps.hogFunctionMonitoringService.queueLogs(logs, 'hog_flow')
+ this.deps.hogFunctionMonitoringService.queueAppMetrics(metrics, 'hog_flow')
+ this.deps.hogFunctionMonitoringService.queueLogs(logs, 'hog_flow')
+ this.deps.deadLetterService?.recordBuildFailures(globals, buildFailures)
- return invocations
+ return invocations
+ } catch (error) {
+ // See the same guard in HogFunctionInvocationPipeline: one workflow that
+ // throws unexpectedly must not stall the partition for everyone else.
+ if (error?.isRetriable === true) {
+ throw error
+ }
+ if (!this.deps.deadLetterService?.recordProcessFailure(globals, error, 'hog_flow')) {
+ throw error
+ }
+ return []
+ }
})
)
).flat()
diff --git a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.ts b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.ts
index f40f60dc75d5..4331e37ee249 100644
--- a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.ts
+++ b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.ts
@@ -9,7 +9,9 @@ import { HogWatcherService, HogWatcherState } from './monitoring/hog-watcher.ser
jest.mock('../utils/invocation-utils', () => ({
...jest.requireActual('../utils/invocation-utils'),
- buildHogFunctionInvocations: jest.fn().mockResolvedValue({ invocations: [], metrics: [], logs: [] }),
+ buildHogFunctionInvocations: jest
+ .fn()
+ .mockResolvedValue({ invocations: [], metrics: [], logs: [], buildFailures: [] }),
}))
// Mock the rate limiter to give us deterministic control
@@ -126,7 +128,12 @@ describe('HogFunctionInvocationPipeline', () => {
it('returns invocations for matching hog functions and queues triggered + billing metrics', async () => {
const fn = makeHogFunction()
const inv = makeInvocation(fn, 'evt-uuid-1')
- jest.mocked(buildHogFunctionInvocations).mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
+ jest.mocked(buildHogFunctionInvocations).mockResolvedValue({
+ invocations: [inv],
+ metrics: [],
+ logs: [],
+ buildFailures: [],
+ })
hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.healthy } } as any)
rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])
@@ -146,10 +153,36 @@ describe('HogFunctionInvocationPipeline', () => {
expect(billingCall).toBeDefined()
})
+ it('rejects rather than dropping an event when no dead-letter service can keep it', async () => {
+ // This pipeline is built without a dead-letter service by the person-update, data
+ // warehouse, internal-event and replay consumers. Returning [] there loses the event with
+ // no record and no metric, so the batch has to fail instead.
+ jest.mocked(buildHogFunctionInvocations).mockRejectedValue(new Error('builder walked off a cliff'))
+
+ await expect(
+ pipeline.buildInvocations([makeGlobals()], { hogTypes: ['destination'], filterFn: () => true })
+ ).rejects.toThrow('builder walked off a cliff')
+ })
+
+ it('rejects on a retriable build error instead of treating the event as poison', async () => {
+ const error: Error & { isRetriable?: boolean } = new Error('Postgres is down')
+ error.isRetriable = true
+ jest.mocked(buildHogFunctionInvocations).mockRejectedValue(error)
+
+ await expect(
+ pipeline.buildInvocations([makeGlobals()], { hogTypes: ['destination'], filterFn: () => true })
+ ).rejects.toThrow('Postgres is down')
+ })
+
it('drops invocations in disabled watcher state', async () => {
const fn = makeHogFunction()
const inv = makeInvocation(fn)
- jest.mocked(buildHogFunctionInvocations).mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
+ jest.mocked(buildHogFunctionInvocations).mockResolvedValue({
+ invocations: [inv],
+ metrics: [],
+ logs: [],
+ buildFailures: [],
+ })
hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.disabled } } as any)
rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])
@@ -168,7 +201,12 @@ describe('HogFunctionInvocationPipeline', () => {
it('routes degraded invocations to hogoverflow queue when overflow enabled', async () => {
const fn = makeHogFunction()
const inv = makeInvocation(fn)
- jest.mocked(buildHogFunctionInvocations).mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
+ jest.mocked(buildHogFunctionInvocations).mockResolvedValue({
+ invocations: [inv],
+ metrics: [],
+ logs: [],
+ buildFailures: [],
+ })
hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.degraded } } as any)
rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])
@@ -185,7 +223,12 @@ describe('HogFunctionInvocationPipeline', () => {
it('drops quota-limited invocations', async () => {
const fn = makeHogFunction()
const inv = makeInvocation(fn)
- jest.mocked(buildHogFunctionInvocations).mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
+ jest.mocked(buildHogFunctionInvocations).mockResolvedValue({
+ invocations: [inv],
+ metrics: [],
+ logs: [],
+ buildFailures: [],
+ })
hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.healthy } } as any)
rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])
quotaLimiting.isTeamQuotaLimited.mockResolvedValue(true)
@@ -201,7 +244,12 @@ describe('HogFunctionInvocationPipeline', () => {
it('drops masked invocations', async () => {
const fn = makeHogFunction()
const inv = makeInvocation(fn)
- jest.mocked(buildHogFunctionInvocations).mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
+ jest.mocked(buildHogFunctionInvocations).mockResolvedValue({
+ invocations: [inv],
+ metrics: [],
+ logs: [],
+ buildFailures: [],
+ })
hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.healthy } } as any)
rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])
hogMasker.filterByMasking.mockResolvedValue({ masked: [inv], notMasked: [], release: async () => {} })
@@ -223,7 +271,12 @@ describe('HogFunctionInvocationPipeline', () => {
const fn2 = makeHogFunction({ id: 'fn-2' })
const inv1 = makeInvocation(fn1, 'evt-same')
const inv2 = makeInvocation(fn2, 'evt-same')
- jest.mocked(buildHogFunctionInvocations).mockResolvedValue({ invocations: [inv1, inv2], metrics: [], logs: [] })
+ jest.mocked(buildHogFunctionInvocations).mockResolvedValue({
+ invocations: [inv1, inv2],
+ metrics: [],
+ logs: [],
+ buildFailures: [],
+ })
hogWatcher.getEffectiveStates.mockResolvedValue({
[fn1.id]: { state: HogWatcherState.healthy },
[fn2.id]: { state: HogWatcherState.healthy },
@@ -247,7 +300,12 @@ describe('HogFunctionInvocationPipeline', () => {
it('does not drop rate-limited invocations (monitoring-only)', async () => {
const fn = makeHogFunction()
const inv = makeInvocation(fn)
- jest.mocked(buildHogFunctionInvocations).mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
+ jest.mocked(buildHogFunctionInvocations).mockResolvedValue({
+ invocations: [inv],
+ metrics: [],
+ logs: [],
+ buildFailures: [],
+ })
hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.healthy } } as any)
rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: true }]])
diff --git a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts
index 1c554155d12c..f35e925a4bbc 100644
--- a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts
+++ b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts
@@ -17,6 +17,7 @@ import {
} from '../types'
import { dualRead } from '../utils/dual-store'
import { buildHogFunctionInvocations } from '../utils/invocation-utils'
+import { InvocationFailureSink } from './dead-letter/cdp-dead-letter.service'
import { HogInputsService } from './hog-inputs.service'
import { HogFunctionManagerService } from './managers/hog-function-manager.service'
import { HogFunctionMonitoringService } from './monitoring/hog-function-monitoring.service'
@@ -42,6 +43,8 @@ export interface HogFunctionInvocationPipelineDeps {
quotaLimiting: QuotaLimiting
redis: RedisV2
valkeyShadow: CdpValkeyShadowPools
+ /** Absent for consumers that have no dead-letter topic; their build failures stay metrics-only. */
+ deadLetterService?: InvocationFailureSink
}
export interface BuildHogFunctionInvocationsOptions {
@@ -93,16 +96,35 @@ export class HogFunctionInvocationPipeline {
? hogFunctionsByTeam[globals.project.id].filter((fn) => opts.invocationFilterFn!(fn, globals))
: hogFunctionsByTeam[globals.project.id]
- const { invocations, metrics, logs } = await buildHogFunctionInvocations(
- this.deps.hogInputsService,
- teamHogFunctions,
- globals
- )
+ try {
+ const { invocations, metrics, logs, buildFailures } = await buildHogFunctionInvocations(
+ this.deps.hogInputsService,
+ teamHogFunctions,
+ globals
+ )
- this.deps.hogFunctionMonitoringService.queueAppMetrics(metrics, 'hog_function')
- this.deps.hogFunctionMonitoringService.queueLogs(logs, 'hog_function')
+ this.deps.hogFunctionMonitoringService.queueAppMetrics(metrics, 'hog_function')
+ this.deps.hogFunctionMonitoringService.queueLogs(logs, 'hog_function')
+ this.deps.deadLetterService?.recordBuildFailures(globals, buildFailures)
- return invocations
+ return invocations
+ } catch (error) {
+ // Anything the per-function handling did not expect: a filter global that
+ // cannot be built, a bug in the builder itself. Without this the whole batch
+ // fails and the partition stalls on one event, forever, until someone
+ // deploys a fix. Retriable errors still fail the batch, because a dependency
+ // being down is not the event's fault.
+ if (error?.isRetriable === true) {
+ throw error
+ }
+ // Swallowing the event is only safe once it is parked. A consumer with no
+ // dead-letter service, or one running with the flag off, fails the batch
+ // instead, which is what kept the event before any of this existed.
+ if (!this.deps.deadLetterService?.recordProcessFailure(globals, error, 'hog_function')) {
+ throw error
+ }
+ return []
+ }
})
)
).flat()
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
index d3496a7ff75c..149753dc5adb 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
@@ -13,6 +13,7 @@ import {
HogFunctionCapturedEvent,
HogFunctionFilterGlobals,
HogFunctionInvocationGlobals,
+ InvocationBuildFailure,
LogEntry,
LogEntryLevel,
MessageAssetRow,
@@ -183,10 +184,12 @@ export class HogFlowExecutorService {
invocations: CyclotronJobInvocationHogFlow[]
metrics: MinimalAppMetric[]
logs: LogEntry[]
+ buildFailures: InvocationBuildFailure[]
}> {
const metrics: MinimalAppMetric[] = []
const logs: LogEntry[] = []
const invocations: CyclotronJobInvocationHogFlow[] = []
+ const buildFailures: InvocationBuildFailure[] = []
// TRICKY: The frontend generates filters matching the Clickhouse event type so we are converting back
const filterGlobals = convertToHogFunctionFilterGlobal(triggerGlobals)
@@ -222,6 +225,17 @@ export class HogFlowExecutorService {
)
logs.push(...filterResults.logs)
+ // Checked against undefined, not for truthiness: a thrown error whose message is empty is
+ // still a failure, and treating it as success drops the event with no record of it.
+ if (filterResults.error !== undefined) {
+ buildFailures.push({
+ sourceId: hogFlow.id,
+ sourceKind: 'hog_flow',
+ step: 'filter',
+ error: String(filterResults.error),
+ })
+ }
+
if (!filterResults.match) {
continue
}
@@ -234,6 +248,7 @@ export class HogFlowExecutorService {
invocations,
metrics,
logs,
+ buildFailures,
}
}
diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.ts
index 6f6426113c9c..4f268fefb5c4 100644
--- a/nodejs/src/cdp/types.ts
+++ b/nodejs/src/cdp/types.ts
@@ -13,6 +13,7 @@ import {
PersonPropertyFilter,
Team,
} from '../types'
+import type { HogErrorClass } from './utils/hog-error-classification'
export type HogBytecode = any[]
@@ -290,6 +291,25 @@ export type AppMetricType = MinimalAppMetric & {
app_source: MetricLogSource
}
+/**
+ * Where an event stopped, for a record on a dead-letter topic.
+ *
+ * `filter` and `inputs` are the two failures the pipeline expects and handles per function.
+ * `parse` and `process` are the ones it does not: a message it cannot read, and anything else
+ * that throws while an event is being turned into invocations. Those two exist so an unanticipated
+ * bug parks the event rather than stalling the partition it arrived on.
+ */
+export type DeadLetterStep = 'parse' | 'filter' | 'inputs' | 'process'
+
+export type InvocationBuildFailure = {
+ sourceId: string
+ sourceKind: 'hog_function' | 'hog_flow'
+ step: DeadLetterStep
+ error: string
+ /** Who has to act on it. Only our own classes are worth parking, see HogErrorClass. */
+ errorClass?: HogErrorClass
+}
+
export interface HogFunctionTiming {
kind: 'hog' | 'async_function'
duration_ms: number
diff --git a/nodejs/src/cdp/utils/invocation-utils.test.ts b/nodejs/src/cdp/utils/invocation-utils.test.ts
index 3b1bead59e61..473f1708ac48 100644
--- a/nodejs/src/cdp/utils/invocation-utils.test.ts
+++ b/nodejs/src/cdp/utils/invocation-utils.test.ts
@@ -324,10 +324,13 @@ describe('Invocation utils', () => {
new Error('Unsupported unit for dateDiff: super secret')
)
- const { logs } = await buildHogFunctionInvocations(hogInputsService, [fn], pageviewGlobals())
+ const { logs, buildFailures } = await buildHogFunctionInvocations(hogInputsService, [fn], pageviewGlobals())
expect(logs[0].message).toContain('Unsupported unit for dateDiff: ***REDACTED***')
expect(logs[0].message).not.toContain('super secret')
+ // The failure is redacted on its own path, and it leaves the process as a header on the parked record.
+ expect(buildFailures[0].error).toContain('Unsupported unit for dateDiff: ***REDACTED***')
+ expect(buildFailures[0].error).not.toContain('super secret')
jest.restoreAllMocks()
})
diff --git a/nodejs/src/cdp/utils/invocation-utils.ts b/nodejs/src/cdp/utils/invocation-utils.ts
index c609d50e0c7e..ca8abcb91ffc 100644
--- a/nodejs/src/cdp/utils/invocation-utils.ts
+++ b/nodejs/src/cdp/utils/invocation-utils.ts
@@ -11,6 +11,7 @@ import {
HogFunctionFilterGlobals,
HogFunctionInvocationGlobals,
HogFunctionInvocationGlobalsWithInputs,
+ InvocationBuildFailure,
LogEntry,
MinimalAppMetric,
} from '../types'
@@ -48,7 +49,8 @@ export function createInvocation(
/**
* Matches a batch of hog functions against one event's globals and builds an invocation per match,
- * resolving each one's inputs. Filter metrics/logs come back alongside for the caller to queue.
+ * resolving each one's inputs. Filter metrics/logs come back alongside for the caller to queue, as
+ * do the functions that matched but produced no invocation, which the caller dead-letters.
*/
export async function buildHogFunctionInvocations(
hogInputsService: HogInputsService,
@@ -58,10 +60,12 @@ export async function buildHogFunctionInvocations(
invocations: CyclotronJobInvocationHogFunction[]
metrics: MinimalAppMetric[]
logs: LogEntry[]
+ buildFailures: InvocationBuildFailure[]
}> {
const metrics: MinimalAppMetric[] = []
const logs: LogEntry[] = []
const invocations: CyclotronJobInvocationHogFunction[] = []
+ const buildFailures: InvocationBuildFailure[] = []
// TRICKY: The frontend generates filters matching the Clickhouse event type so we are converting back
const filterGlobals = convertToHogFunctionFilterGlobal(triggerGlobals)
@@ -82,6 +86,18 @@ export async function buildHogFunctionInvocations(
metrics.push(...filterResults.metrics)
logs.push(...filterResults.logs)
+ // Checked against undefined, not for truthiness: a thrown error whose message is empty is
+ // still a failure, and treating it as success drops the event with no record of it.
+ if (filterResults.error !== undefined) {
+ buildFailures.push({
+ sourceId: hogFunction.id,
+ sourceKind: 'hog_function',
+ step: 'filter',
+ error: String(filterResults.error),
+ errorClass: filterResults.errorClass,
+ })
+ }
+
return filterResults.match
}
@@ -106,6 +122,21 @@ export async function buildHogFunctionInvocations(
return createInvocation(globalsWithInputs, hogFunction)
} catch (error) {
+ const errorClass = classifyHogError(error, {
+ bytecodeContract: bytecodeContractOf(error),
+ runtimeContract: currentRuntimeContractHash(),
+ })
+
+ buildFailures.push({
+ sourceId: hogFunction.id,
+ sourceKind: 'hog_function',
+ step: 'inputs',
+ // The VM quotes the argument it choked on, and an argument can be a secret input.
+ // This message leaves the process as a header on the parked record.
+ error: sanitizeLogMessage([error.message], getConfiguredSensitiveValues(hogFunction)),
+ errorClass,
+ })
+
logs.push({
team_id: hogFunction.team_id,
log_source: 'hog_function',
@@ -122,13 +153,7 @@ export async function buildHogFunctionInvocations(
),
})
- hogFunctionInputsErrors.inc({
- type: hogFunction.type,
- class: classifyHogError(error, {
- bytecodeContract: bytecodeContractOf(error),
- runtimeContract: currentRuntimeContractHash(),
- }),
- })
+ hogFunctionInputsErrors.inc({ type: hogFunction.type, class: errorClass })
metrics.push({
team_id: hogFunction.team_id,
@@ -181,6 +206,7 @@ export async function buildHogFunctionInvocations(
invocations,
metrics,
logs,
+ buildFailures,
}
}
diff --git a/nodejs/src/common/config/kafka-topics.ts b/nodejs/src/common/config/kafka-topics.ts
index 289c67d05064..5bb4224ce450 100644
--- a/nodejs/src/common/config/kafka-topics.ts
+++ b/nodejs/src/common/config/kafka-topics.ts
@@ -82,6 +82,11 @@ export const KAFKA_MESSAGE_ASSETS = `${prefix}clickhouse_message_assets${suffix}
// CDP topics
export const KAFKA_CDP_FUNCTION_OVERFLOW = `${prefix}cdp_function_overflow${suffix}`
export const KAFKA_CDP_INTERNAL_EVENTS = `${prefix}cdp_internal_events${suffix}`
+// Dead-letter topic for the CDP events consumer. A record holds the original message bytes and
+// `dlq_*` headers naming the functions that could not be built, so a replay can rebuild exactly
+// those after a forward fix. One topic per consumer, so a replay never touches another consumer's
+// records. It carries full event payloads, so retention is bounded the way the source topic is.
+export const KAFKA_CDP_EVENTS_DLQ = `${prefix}cdp_events_dlq${suffix}`
export const KAFKA_CDP_CLICKHOUSE_BEHAVIORAL_COHORTS_MATCHES = `${prefix}clickhouse_behavioral_cohorts_matches${suffix}`
export const KAFKA_COHORT_MEMBERSHIP_CHANGED = `${prefix}cohort_membership_changed${suffix}`
// One completion marker per processor partition, certifying that a reconcile run replayed a