:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cdp): add a dead-letter replay consumer (#100830)
Meikel Ratz766dbac5b64f
diff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.tsindex e84e6d7f2754..7aa0daeb6e37 100644--- a/nodejs/src/capabilities.ts+++ b/nodejs/src/capabilities.ts@@ -181,6 +181,12 @@ export function getPluginServerCapabilities(return {cdpRerunWorker: true,}+ // Deliberately absent from CAPABILITIES_CDP: a replay is a bounded, operator-triggered run,+ // not something a local or combined stack should start on its own.+ case PluginServerMode.cdp_dlq_replay:+ return {+ cdpDlqReplay: true,+ }case PluginServerMode.ingestion_v2:case PluginServerMode.ingestion_v2_combined:throw new Error(`Mode ${mode} is handled by IngestionGeneralServer, not PluginServer`)diff --git a/nodejs/src/cdp/cdp-dlq-replay-e2e.serial.test.ts b/nodejs/src/cdp/cdp-dlq-replay-e2e.serial.test.tsnew file mode 100644index 000000000000..acba711c5e38--- /dev/null+++ b/nodejs/src/cdp/cdp-dlq-replay-e2e.serial.test.ts@@ -0,0 +1,716 @@+import { createMockJobQueue } from '~/tests/helpers/mocks/job-queue.mock'+import { MockKafkaProducerWrapper } from '~/tests/helpers/mocks/producer.mock'+import { mockFetch } from '~/tests/helpers/mocks/request.mock'++import { randomUUID } from 'crypto'+import { Message } from 'node-rdkafka'+import { register } from 'prom-client'++import { KAFKA_CDP_EVENTS_DLQ, KAFKA_EVENTS_JSON } from '~/common/config/kafka-topics'+import { KafkaConsumer } from '~/common/kafka/consumer/consumer-v1'+import { KafkaProducerWrapper } from '~/common/kafka/producer'+import { closeHub, createHub } from '~/common/utils/db/hub'+import { PostgresUse } from '~/common/utils/db/postgres'+import { parseJSON } from '~/common/utils/json-parse'+import { createCdpConsumerDeps } from '~/tests/helpers/cdp'+import { waitForExpect } from '~/tests/helpers/expectations'+import { TEST_KAFKA_TOPICS, createKafkaTestTopicName, ensureKafkaTopics } from '~/tests/helpers/kafka'+import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'++import { Hub, Team } from '../types'+import { FixtureHogFlowBuilder } from './_tests/builders/hogflow.builder'+import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from './_tests/examples'+import { createIncomingEvent, insertHogFunction } from './_tests/fixtures'+import { insertHogFlow } from './_tests/fixtures-hogflows'+import { CdpCyclotronWorker } from './consumers/cdp-cyclotron-worker.consumer'+import { CdpDlqReplayConsumer } from './consumers/cdp-dlq-replay.consumer'+import { CdpEventsConsumer } from './consumers/cdp-events.consumer'+import { CyclotronJobQueueKafka } from './services/job-queue/job-queue-kafka'+import { CyclotronJobQueuePostgresV2 } from './services/job-queue/job-queue-postgres-v2'+import { JobQueue } from './services/job-queue/job-queue.interface'+import { HogFunctionType } from './types'++const ActualKafkaProducerWrapper = jest.requireActual('~/common/kafka/producer').KafkaProducerWrapper++// Truncated bytecode: resolving this input throws, the way a narrowed builtin arity did. Stamped+// against another runtime, so the failure is ours and gets parked.+const BROKEN_INPUTS: HogFunctionType['inputs'] = {+ url: { order: 0, value: 'https://example.com', bytecode: ['_H', 1, 2], bytecode_contract: 'stale' },+}++describe('CDP dead-letter replay', () => {+ jest.setTimeout(60000)++ let hub: Hub+ let team: Team+ let kafkaProducer: KafkaProducerWrapper+ let eventsConsumer: CdpEventsConsumer | undefined+ let replayConsumer: CdpDlqReplayConsumer | undefined+ let cyclotronWorker: CdpCyclotronWorker | undefined+ let dlqTopic: string+ let eventsTopic: string+ let readCount: number++ beforeEach(async () => {+ MockKafkaProducerWrapper.create = jest.fn((...args) => ActualKafkaProducerWrapper.create(...args))++ // The dead-letter topic is per test. It is not deleted between runs, so a shared one would+ // hand each run the records every earlier run parked and there would be nothing to assert.+ // Both topics are per test. Topics are not deleted between runs, so a shared one would+ // hand each run everything every earlier run produced and there would be nothing to assert.+ dlqTopic = createKafkaTestTopicName(KAFKA_CDP_EVENTS_DLQ)+ eventsTopic = createKafkaTestTopicName(KAFKA_EVENTS_JSON)+ readCount = 0+ await ensureKafkaTopics([...TEST_KAFKA_TOPICS, dlqTopic, eventsTopic])+ await resetTestDatabase()++ hub = await createHub()+ hub.CDP_DLQ_ENABLED = true+ hub.CDP_EVENTS_DLQ_TOPIC = dlqTopic+ hub.CDP_DLQ_REPLAY_TOPIC = dlqTopic+ kafkaProducer = await ActualKafkaProducerWrapper.create(hub.KAFKA_CLIENT_RACK)+ team = await getFirstTeam(hub.postgres)+ })++ afterEach(async () => {+ await Promise.all([eventsConsumer?.stop(), replayConsumer?.stop(), cyclotronWorker?.stop()])+ eventsConsumer = undefined+ replayConsumer = undefined+ cyclotronWorker = undefined+ await kafkaProducer.disconnect()+ await closeHub(hub)+ })++ /**+ * Starts the real events consumer against this test's own events topic.+ *+ * Its own topic and group, so the events one test produces are not read by another, and so a+ * group that has never committed still sees a record produced after it connects.+ */+ const startEventsConsumer = async (queues: { hogQueue: JobQueue; hogflowQueue: JobQueue }): Promise<void> => {+ eventsConsumer = new CdpEventsConsumer(+ hub,+ createCdpConsumerDeps(hub, kafkaProducer),+ queues,+ eventsTopic,+ `e2e-events-${eventsTopic}`+ )+ await eventsConsumer.start()+ }++ /**+ * Produces an event and waits for the consumer to park it.+ *+ * Nothing here calls the consumer's own methods. The record has to arrive because the consumer+ * read the event, failed to build it, and wrote the record itself, which is the half of the+ * loop these tests would otherwise take on trust.+ */+ const parkEvent = async (expected = 1, properties?: Record<string, unknown>): Promise<Message[]> => {+ const event = createIncomingEvent(team.id, properties ? { properties: JSON.stringify(properties) } : {})+ await kafkaProducer.produce({+ topic: eventsTopic,+ value: Buffer.from(JSON.stringify(event)),+ key: Buffer.from(event.uuid),+ })+ await kafkaProducer.flush()+ return await readDlqRecords(expected)+ }++ /** Stands in for the forward fix: the same function, with inputs that now resolve. */+ const repairInputs = async (fn: HogFunctionType): Promise<void> => {+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `UPDATE posthog_hogfunction SET inputs = $1 WHERE id = $2`,+ [JSON.stringify(HOG_INPUTS_EXAMPLES.simple_fetch.inputs), fn.id],+ 'repair-hog-function-inputs'+ )+ }++ /** Reads the parked records back off the topic, waiting until the consumer has produced them. */+ const readDlqRecords = async (expected = 1): Promise<Message[]> => {+ const consumer = new KafkaConsumer(+ {+ topic: dlqTopic,+ groupId: `e2e-read-${dlqTopic}-${++readCount}`,+ autoCommit: false,+ autoOffsetStore: false,+ },+ { 'auto.offset.reset': 'earliest' } as never+ )+ const messages: Message[] = []+ await consumer.connect((batch) => {+ messages.push(...batch)+ return Promise.resolve()+ })+ await waitForExpect(() => expect(messages.length).toBeGreaterThanOrEqual(expected), 30000)+ await consumer.disconnect()+ return messages+ }++ /** Stands in for the forward fix on the filter side. */+ const repairFilters = async (fn: HogFunctionType): Promise<void> => {+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `UPDATE posthog_hogfunction SET filters = $1 WHERE id = $2`,+ [JSON.stringify(HOG_FILTERS_EXAMPLES.no_filters.filters), fn.id],+ 'repair-hog-function-filters'+ )+ }++ it('parks an event that cannot build, then rebuilds only that function after the fix', async () => {+ const broken = await insertHogFunction(hub.postgres, team.id, {+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ type: 'destination',+ inputs_schema: [{ key: 'url', type: 'string', label: 'Webhook URL', required: true }],+ inputs: BROKEN_INPUTS,+ })+ const healthy = await insertHogFunction(hub.postgres, team.id, {+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_INPUTS_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ type: 'destination',+ })++ // --- park -------------------------------------------------------------------------+ const sourceQueue = createMockJobQueue()+ await startEventsConsumer({ hogQueue: sourceQueue, hogflowQueue: sourceQueue })++ await parkEvent()++ // The healthy function delivered on the first pass. That is what the replay must not repeat.+ expect(sourceQueue.queueInvocations).toHaveBeenCalledWith([expect.objectContaining({ functionId: healthy.id })])++ // --- fix, then replay -------------------------------------------------------------+ await repairInputs(broken)++ const replayQueue = createMockJobQueue()+ replayConsumer = new CdpDlqReplayConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: replayQueue,+ hogflowQueue: replayQueue,+ })+ await replayConsumer.start()++ await waitForExpect(() => {+ expect(replayQueue.queueInvocations).toHaveBeenCalledWith([+ expect.objectContaining({ functionId: broken.id }),+ ])+ }, 30000)++ // Only the parked function was rebuilt: every invocation the replay queued is that one.+ const replayed = replayQueue.queueInvocations.mock.calls.flatMap(([invocations]: [any[]]) => invocations)+ expect(replayed.map((invocation: any) => invocation.functionId)).toEqual([broken.id])+ expect(replayed[0].queueMetadata).toMatchObject({ replayed_from_dlq: true })+ expect(replayConsumer.counts.replayed).toBe(1)+ })++ it('rebuilds each function once when one event is parked twice', async () => {+ // A record is written per event and per step, so an event that fails the filter for one+ // function and the inputs for another is parked twice. Both records name the same event.+ const brokenFilter = await insertHogFunction(hub.postgres, team.id, {+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_INPUTS_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.broken_filters,+ type: 'destination',+ })+ const brokenInputs = await insertHogFunction(hub.postgres, team.id, {+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ type: 'destination',+ inputs_schema: [{ key: 'url', type: 'string', label: 'Webhook URL', required: true }],+ inputs: BROKEN_INPUTS,+ })++ const sourceQueue = createMockJobQueue()+ await startEventsConsumer({ hogQueue: sourceQueue, hogflowQueue: sourceQueue })++ await parkEvent(2)++ await repairInputs(brokenInputs)+ await repairFilters(brokenFilter)++ const replayQueue = createMockJobQueue()+ replayConsumer = new CdpDlqReplayConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: replayQueue,+ hogflowQueue: replayQueue,+ })+ await replayConsumer.start()++ await waitForExpect(() => {+ expect(replayConsumer!.counts.queued).toBe(2)+ }, 30000)++ // Both parked functions come back, each exactly once, through the live consumer. This only+ // covers the union while CONSUMER_BATCH_SIZE is large enough to hand both records to one+ // batch, which is why the case below passes them in directly.+ const replayed = replayQueue.queueInvocations.mock.calls.flatMap(([invocations]: [any[]]) => invocations)+ expect(replayed.map((invocation: any) => invocation.functionId).sort()).toEqual(+ [brokenFilter.id, brokenInputs.id].sort()+ )+ })++ it('sends the delivery for real: parked, fixed, replayed, and the destination is called', async () => {+ // Everything else here stops once an invocation is queued. This one runs the invocation+ // through cyclotron as well, so the whole loop is covered: the event fails to build, the+ // bytes land on a real topic, a real consumer group reads them back, the invocation is+ // rebuilt, and the destination is actually called.+ const broken = await insertHogFunction(hub.postgres, team.id, {+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ type: 'destination',+ inputs_schema: HOG_INPUTS_EXAMPLES.simple_fetch.inputs_schema,+ inputs: { ...HOG_INPUTS_EXAMPLES.simple_fetch.inputs, ...BROKEN_INPUTS },+ })++ const kafkaQueue = new CyclotronJobQueueKafka(hub.KAFKA_CLIENT_RACK, hub, hub.CONSUMER_BATCH_SIZE)+ const postgresQueue = new CyclotronJobQueuePostgresV2(hub.CONSUMER_BATCH_SIZE, hub)++ await startEventsConsumer({ hogQueue: kafkaQueue, hogflowQueue: postgresQueue })++ await parkEvent()++ // Nothing was delivered: the only destination on this event could not be built.+ expect(mockFetch).not.toHaveBeenCalled()++ // The forward fix, then the replay, with cyclotron running to execute what it queues.+ await repairInputs(broken)+ cyclotronWorker = new CdpCyclotronWorker(hub, createCdpConsumerDeps(hub, kafkaProducer), kafkaQueue)+ await cyclotronWorker.start()++ replayConsumer = new CdpDlqReplayConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: kafkaQueue,+ hogflowQueue: postgresQueue,+ })+ await replayConsumer.start()++ await waitForExpect(() => {+ expect(mockFetch).toHaveBeenCalledTimes(1)+ }, 30000)++ expect(mockFetch.mock.calls[0][0]).toBe('https://example.com/posthog-webhook')+ }, 60000)++ it('rebuilds one event once when both its records arrive in the same batch', async () => {+ // Batch size is the deployment's, so two records for one event can land together. Without+ // the union the second record's targets overwrite the first's: one destination is never+ // replayed and the event is rebuilt twice, queueing the other one twice.+ const brokenFilter = await insertHogFunction(hub.postgres, team.id, {+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_INPUTS_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.broken_filters,+ type: 'destination',+ })+ const brokenInputs = await insertHogFunction(hub.postgres, team.id, {+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ type: 'destination',+ inputs_schema: [{ key: 'url', type: 'string', label: 'Webhook URL', required: true }],+ inputs: BROKEN_INPUTS,+ })++ const sourceQueue = createMockJobQueue()+ await startEventsConsumer({ hogQueue: sourceQueue, hogflowQueue: sourceQueue })+ const records = await parkEvent(2)+ expect(records).toHaveLength(2)++ await repairInputs(brokenInputs)+ await repairFilters(brokenFilter)++ const replayQueue = createMockJobQueue()+ replayConsumer = new CdpDlqReplayConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: replayQueue,+ hogflowQueue: replayQueue,+ })+ await replayConsumer.replayBatch(records)++ const queued = replayQueue.queueInvocations.mock.calls.flatMap(([invocations]: [any[]]) => invocations)+ expect(queued.map((invocation: any) => invocation.functionId).sort()).toEqual(+ [brokenFilter.id, brokenInputs.id].sort()+ )+ })++ it('does not re-send a destination when only the workflow pipeline threw', async () => {+ // Both pipelines run against the same event. If destinations build and queue while the+ // workflow pipeline throws, the record names no id — and without the kind on it a replay+ // would rebuild the destinations that already delivered.+ const healthy = await insertHogFunction(hub.postgres, team.id, {+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_INPUTS_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ type: 'destination',+ })++ const sourceQueue = createMockJobQueue()+ await startEventsConsumer({ hogQueue: sourceQueue, hogflowQueue: sourceQueue })++ // Only the workflow side throws, so the destination is built and delivered as normal. The+ // executor rather than the pipeline, so the pipeline's own catch is what handles it.+ jest.spyOn(eventsConsumer!['hogFlowExecutor'], 'buildHogFlowInvocations').mockRejectedValue(+ new Error('workflow builder walked off a cliff')+ )++ const records = await parkEvent()+ expect(records).toHaveLength(1)++ // The destination built and delivered on the first pass, while the workflow side threw.+ expect(sourceQueue.queueInvocations).toHaveBeenCalledWith([expect.objectContaining({ functionId: healthy.id })])++ const replayQueue = createMockJobQueue()+ replayConsumer = new CdpDlqReplayConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: replayQueue,+ hogflowQueue: replayQueue,+ })+ await replayConsumer.replayBatch(records)++ // The record names hog_flow, so the destination that already delivered is not rebuilt.+ const queued = replayQueue.queueInvocations.mock.calls.flatMap(([invocations]: [any[]]) => invocations)+ expect(queued.map((invocation: any) => invocation.functionId)).not.toContain(healthy.id)+ })++ it('blocks instead of committing when the destination still fails to build', async () => {+ // The fix is not deployed yet. A filter or input that throws is handled per function, so+ // the rebuild comes back as an empty invocation list and no error — the worker has to read+ // that as a failed replay, or it commits past a delivery that never happened.+ const broken = await insertHogFunction(hub.postgres, team.id, {+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ type: 'destination',+ inputs_schema: [{ key: 'url', type: 'string', label: 'Webhook URL', required: true }],+ inputs: BROKEN_INPUTS,+ })++ const sourceQueue = createMockJobQueue()+ await startEventsConsumer({ hogQueue: sourceQueue, hogflowQueue: sourceQueue })+ const records = await parkEvent()++ // No repair. Replaying now must not consume the record.+ const replayQueue = createMockJobQueue()+ replayConsumer = new CdpDlqReplayConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: replayQueue,+ hogflowQueue: replayQueue,+ })++ await expect(replayConsumer.replayBatch(records)).rejects.toThrow('still fail to build')+ expect(replayQueue.queueInvocations).not.toHaveBeenCalled()++ // With the fix applied the same records go through, so the block was about the bug and not+ // about the records being unreadable. A second worker, because the first cached the+ // function as it was before the repair.+ await repairInputs(broken)+ await replayConsumer.stop()+ const fixedQueue = createMockJobQueue()+ replayConsumer = new CdpDlqReplayConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: fixedQueue,+ hogflowQueue: fixedQueue,+ })+ await replayConsumer.replayBatch(records)+ expect(fixedQueue.queueInvocations).toHaveBeenCalledWith([expect.objectContaining({ functionId: broken.id })])+ })++ it('parks a workflow that cannot build, then replays it onto the workflow queue', async () => {+ // Every other case here is a destination. A workflow is the other source kind, and its+ // invocations go to a different queue, so nothing else covers that wiring.+ const flow = await insertHogFlow(+ hub.postgres,+ new FixtureHogFlowBuilder()+ .withTeamId(team.id)+ .withSimpleWorkflow({+ trigger: { type: 'event', filters: HOG_FILTERS_EXAMPLES.broken_filters.filters as any },+ })+ .build()+ )++ const sourceQueue = createMockJobQueue()+ await startEventsConsumer({ hogQueue: sourceQueue, hogflowQueue: sourceQueue })+ const records = await parkEvent()+ expect(records).toHaveLength(1)+ const headers = Object.assign({}, ...(records[0].headers ?? []).map((h: any) => h))+ expect(headers.dlq_hog_flow_ids.toString()).toBe(flow.id)+ expect(headers.dlq_kinds.toString()).toBe('hog_flow')++ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `UPDATE posthog_hogflow SET trigger = $1 WHERE id = $2`,+ [JSON.stringify({ type: 'event', filters: HOG_FILTERS_EXAMPLES.no_filters.filters }), flow.id],+ 'repair-hog-flow-trigger'+ )++ // Separate queues, so the assertion is about which one the workflow landed on.+ const hogQueue = createMockJobQueue()+ const hogflowQueue = createMockJobQueue()+ replayConsumer = new CdpDlqReplayConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue,+ hogflowQueue,+ })+ await replayConsumer.replayBatch(records)++ expect(hogflowQueue.queueInvocations).toHaveBeenCalledWith([expect.objectContaining({ functionId: flow.id })])+ expect(hogQueue.queueInvocations).toHaveBeenCalledWith([])+ })++ it('parks bytes it cannot read, and blocks on them until a version can', async () => {+ // The one step whose records are unreadable by construction: that is why they were parked.+ await insertHogFunction(hub.postgres, team.id, {+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_INPUTS_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ type: 'destination',+ })++ const sourceQueue = createMockJobQueue()+ await startEventsConsumer({ hogQueue: sourceQueue, hogflowQueue: sourceQueue })+ await kafkaProducer.produce({+ topic: eventsTopic,+ value: Buffer.from('not an event at all'),+ key: null,+ })+ await kafkaProducer.flush()++ const records = await readDlqRecords()+ const headers = Object.assign({}, ...(records[0].headers ?? []).map((h: any) => h))+ expect(headers.dlq_step.toString()).toBe('parse')+ // Nothing was built, so a replay is not restricted to either pipeline.+ expect(headers.dlq_kinds.toString()).toBe('')++ const replayQueue = createMockJobQueue()+ replayConsumer = new CdpDlqReplayConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: replayQueue,+ hogflowQueue: replayQueue,+ })++ // Still unreadable to this version, so the batch fails and the offset stays put.+ await expect(replayConsumer.replayBatch(records)).rejects.toThrow()+ expect(replayQueue.queueInvocations).not.toHaveBeenCalled()+ })++ it('drains records that were parked long before it ever joined the topic', async () => {+ // The deployment sits at zero replicas, so records always land before the worker connects.+ // Reading from the start of the topic is what makes scaling it up drain the backlog rather+ // than sit at the tip reporting a clean run.+ const fn = await insertHogFunction(hub.postgres, team.id, {+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ type: 'destination',+ inputs_schema: [{ key: 'url', type: 'string', label: 'Webhook URL', required: true }],+ inputs: BROKEN_INPUTS,+ })++ const sourceQueue = createMockJobQueue()+ await startEventsConsumer({ hogQueue: sourceQueue, hogflowQueue: sourceQueue })+ // Awaited, so the record is on the topic before the worker ever connects.+ await parkEvent()+ await repairInputs(fn)++ // Only now does the worker start, the way scaling from zero does.+ const drainQueue = createMockJobQueue()+ replayConsumer = new CdpDlqReplayConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: drainQueue,+ hogflowQueue: drainQueue,+ })+ await replayConsumer.start()++ await waitForExpect(() => {+ expect(drainQueue.queueInvocations).toHaveBeenCalledWith([expect.objectContaining({ functionId: fn.id })])+ }, 30000)+ })++ it('crashes on a record that still fails, commits nothing, and replays it once the fix is out', async () => {+ // The consumer loop rejecting is what takes the process down, and Kubernetes restarts it into+ // the same record until the fix ships. That crash loop is the intended way to block.+ const broken = await insertHogFunction(hub.postgres, team.id, {+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ type: 'destination',+ inputs_schema: [{ key: 'url', type: 'string', label: 'Webhook URL', required: true }],+ inputs: BROKEN_INPUTS,+ })++ const sourceQueue = createMockJobQueue()+ await startEventsConsumer({ hogQueue: sourceQueue, hogflowQueue: sourceQueue })+ await parkEvent()++ const blockedQueue = createMockJobQueue()+ replayConsumer = new CdpDlqReplayConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: blockedQueue,+ hogflowQueue: blockedQueue,+ })+ await replayConsumer.start()+ await expect((replayConsumer['kafkaConsumer'] as any).consumerLoop).rejects.toThrow('still fail to build')+ expect(blockedQueue.queueInvocations).not.toHaveBeenCalled()++ // The restart after the fix reads the same record, so the crash committed nothing.+ await repairInputs(broken)+ await replayConsumer.stop()+ const fixedQueue = createMockJobQueue()+ replayConsumer = new CdpDlqReplayConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: fixedQueue,+ hogflowQueue: fixedQueue,+ })+ await replayConsumer.start()++ await waitForExpect(() => {+ expect(fixedQueue.queueInvocations).toHaveBeenCalledWith([+ expect.objectContaining({ functionId: broken.id }),+ ])+ }, 30000)+ })++ it('sends nothing again after a restart, only what was parked since', async () => {+ // The committed offsets are the only record of what was sent. Without them every scale-up+ // would send the whole topic again.+ const broken = await insertHogFunction(hub.postgres, team.id, {+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ type: 'destination',+ inputs_schema: [{ key: 'url', type: 'string', label: 'Webhook URL', required: true }],+ inputs: BROKEN_INPUTS,+ })++ const sourceQueue = createMockJobQueue()+ await startEventsConsumer({ hogQueue: sourceQueue, hogflowQueue: sourceQueue })+ const [first] = await parkEvent()+ await repairInputs(broken)++ const firstQueue = createMockJobQueue()+ replayConsumer = new CdpDlqReplayConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: firstQueue,+ hogflowQueue: firstQueue,+ })+ await replayConsumer.start()+ await waitForExpect(() => expect(firstQueue.queueInvocations).toHaveBeenCalled(), 30000)+ await replayConsumer.stop()++ // A record parked while the consumer was down, so the next run has something to read.+ const later = { ...parseJSON(first.value!.toString()), uuid: randomUUID() }+ await kafkaProducer.produce({+ topic: dlqTopic,+ value: Buffer.from(JSON.stringify(later)),+ key: Buffer.from(later.uuid),+ headers: Object.fromEntries(+ (first.headers ?? []).flatMap((header) =>+ Object.entries(header).map(([key, value]) => [key, value.toString()])+ )+ ),+ })+ await kafkaProducer.flush()++ const secondQueue = createMockJobQueue()+ replayConsumer = new CdpDlqReplayConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: secondQueue,+ hogflowQueue: secondQueue,+ })+ await replayConsumer.start()+ await waitForExpect(() => expect(secondQueue.queueInvocations).toHaveBeenCalled(), 30000)++ const replayed = secondQueue.queueInvocations.mock.calls.flatMap(([invocations]: [any[]]) => invocations)+ expect(replayed.map((invocation: any) => invocation.state.globals.event.uuid)).toEqual([later.uuid])+ })++ it("passes over a record whose source now fails for the owner's reasons", async () => {+ // A data or limit failure fails the same way on every attempt. Blocking on it would wedge the+ // consumer on a record no fix of ours can clear.+ const fn = await insertHogFunction(hub.postgres, team.id, {+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ type: 'destination',+ inputs_schema: [{ key: 'url', type: 'string', label: 'Webhook URL', required: true }],+ inputs: BROKEN_INPUTS,+ })++ const sourceQueue = createMockJobQueue()+ await startEventsConsumer({ hogQueue: sourceQueue, hogflowQueue: sourceQueue })+ const records = await parkEvent(1, { payload: '{' })++ // Our bug is fixed, but the owner has since added a filter that cannot parse this event.+ await repairInputs(fn)+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `UPDATE posthog_hogfunction SET filters = $1 WHERE id = $2`,+ [JSON.stringify(HOG_FILTERS_EXAMPLES.filters_bad_event_json.filters), fn.id],+ 'owner-breaks-the-filter'+ )++ const replayQueue = createMockJobQueue()+ replayConsumer = new CdpDlqReplayConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: replayQueue,+ hogflowQueue: replayQueue,+ })++ await expect(replayConsumer.replayBatch(records)).resolves.toBeUndefined()+ const queued = replayQueue.queueInvocations.mock.calls.flatMap(([invocations]: [any[]]) => invocations)+ expect(queued).toEqual([])+ })++ const replayedRecords = async (outcome: string): Promise<number> => {+ const metric = await register.getSingleMetric('cdp_dlq_replay_records_total')!.get()+ return metric.values.find((value) => value.labels.outcome === outcome)?.value ?? 0+ }++ it('skips a record whose team no longer exists instead of blocking on it', async () => {+ // No fix brings a deleted team back, so blocking would wedge the worker until someone moved+ // the offset by hand.+ const fn = await insertHogFunction(hub.postgres, team.id, {+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ type: 'destination',+ inputs_schema: [{ key: 'url', type: 'string', label: 'Webhook URL', required: true }],+ inputs: BROKEN_INPUTS,+ })++ const sourceQueue = createMockJobQueue()+ await startEventsConsumer({ hogQueue: sourceQueue, hogflowQueue: sourceQueue })+ const [parked] = await parkEvent()+ await repairInputs(fn)+ const orphaned = {+ ...parked,+ value: Buffer.from(JSON.stringify({ ...parseJSON(parked.value!.toString()), team_id: 999_999 })),+ }++ const replayQueue = createMockJobQueue()+ replayConsumer = new CdpDlqReplayConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: replayQueue,+ hogflowQueue: replayQueue,+ })+ const before = await replayedRecords('unreplayable')++ await expect(replayConsumer.replayBatch([orphaned])).resolves.toBeUndefined()++ const queued = replayQueue.queueInvocations.mock.calls.flatMap(([invocations]: [any[]]) => invocations)+ expect(queued).toEqual([])+ expect((await replayedRecords('unreplayable')) - before).toBe(1)+ })++ it('counts an event whose named destination was turned off before the replay', async () => {+ // The offset commits either way. Without this count a drained topic reads as all delivered.+ const fn = await insertHogFunction(hub.postgres, team.id, {+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ type: 'destination',+ inputs_schema: [{ key: 'url', type: 'string', label: 'Webhook URL', required: true }],+ inputs: BROKEN_INPUTS,+ })++ const sourceQueue = createMockJobQueue()+ await startEventsConsumer({ hogQueue: sourceQueue, hogflowQueue: sourceQueue })+ const records = await parkEvent()+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `UPDATE posthog_hogfunction SET enabled = false WHERE id = $1`,+ [fn.id],+ 'disable-hog-function'+ )++ const replayQueue = createMockJobQueue()+ replayConsumer = new CdpDlqReplayConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: replayQueue,+ hogflowQueue: replayQueue,+ })+ const before = await replayedRecords('filtered_out')++ await replayConsumer.replayBatch(records)++ const queued = replayQueue.queueInvocations.mock.calls.flatMap(([invocations]: [any[]]) => invocations)+ expect(queued).toEqual([])+ expect((await replayedRecords('filtered_out')) - before).toBe(1)+ })+})diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex c4cfe27596d6..989a22974424 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -130,6 +130,8 @@ export type CdpConfig = ClickhouseConfig & {CDP_DLQ_BATCH_FAIL_RATIO: numberCDP_EVENTS_DLQ_TOPIC: stringCDP_EVENTS_DLQ_PRODUCER: CdpProducerName+ // Replay worker. Scaled to zero replicas; an operator scales it up to drain the topic.+ CDP_DLQ_REPLAY_TOPIC: stringCDP_EMAIL_TRACKING_URL: string@@ -342,6 +344,7 @@ export function getDefaultCdpConfig(): CdpConfig {// 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_DLQ_REPLAY_TOPIC: KAFKA_CDP_EVENTS_DLQ,CDP_EMAIL_TRACKING_URL: 'http://localhost:8010',diff --git a/nodejs/src/cdp/consumers/cdp-dlq-replay.consumer.ts b/nodejs/src/cdp/consumers/cdp-dlq-replay.consumer.tsnew file mode 100644index 000000000000..2f8a787c6a73--- /dev/null+++ b/nodejs/src/cdp/consumers/cdp-dlq-replay.consumer.ts@@ -0,0 +1,392 @@+import { Message } from 'node-rdkafka'+import { Counter } from 'prom-client'++import { KafkaConsumerInterface, createKafkaConsumer } from '~/common/kafka/consumer'+import type { RdKafkaConsumerConfig } from '~/common/kafka/consumer/consumer-v1'+import { instrumentFn } from '~/common/tracing/tracing-utils'+import { logger } from '~/common/utils/logger'++import { HealthCheckResult, PluginsServerConfig } from '../../types'+import type { InvocationFailureSink } from '../services/dead-letter/cdp-dead-letter.service'+import {+ DeadLetterRecord,+ SourceKind,+ partitionReplayFailures,+ readDeadLetterRecord,+ readParkedEvent,+ replayTargetIds,+ replayTargetKinds,+} from '../services/dead-letter/replay-policy'+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'+import { HogFunctionInvocationGlobals, HogFunctionTypeType, InvocationBuildFailure } from '../types'+import { convertToHogFunctionInvocationGlobals } from '../utils'+import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'++const counterReplayRecords = new Counter({+ name: 'cdp_dlq_replay_records_total',+ help: 'A dead-letter record was read by the replay worker',+ labelNames: ['outcome'],+})++const counterReplayInvocations = new Counter({+ name: 'cdp_dlq_replay_invocations_total',+ help: 'An invocation was rebuilt and queued by the replay worker',+})++const TEAM_MISSING = 'team_missing'++/** The group is fixed, so its committed offsets are what stop a record being replayed twice. */+const REPLAY_GROUP_ID = 'cdp-dlq-replay'++/**+ * Catches what the pipelines would otherwise report to a dead-letter topic.+ *+ * A filter or an input that throws is handled per function: the builder returns it here and the+ * pipeline carries on, so a rebuild that fails the same way it did the first time comes back as an+ * empty invocation list and no error. Without this the worker would commit past a record whose+ * delivery never happened. Collecting them lets the batch fail instead.+ *+ * `recordProcessFailure` answers false, which is what a pipeline with no sink at all would see, so+ * an unexpected error keeps failing the batch where it is thrown.+ */+class ReplayFailureCollector implements InvocationFailureSink {+ public failures: InvocationBuildFailure[] = []+ public failedEvents = new Set<HogFunctionInvocationGlobals>()++ public recordBuildFailures(globals: HogFunctionInvocationGlobals, failures: InvocationBuildFailure[]): void {+ this.failures.push(...failures)+ if (failures.length) {+ this.failedEvents.add(globals)+ }+ }++ public recordProcessFailure(): boolean {+ return false+ }++ public clear(): void {+ this.failures = []+ this.failedEvents = new Set()+ }+}++export interface CdpDlqReplayCounts {+ replayed: number+ queued: number+}++/**+ * Rebuilds invocations for events parked on a dead-letter topic.+ *+ * The deployment runs at zero replicas. An operator scales it to one once the bug that parked the+ * records is fixed and deployed, and back to zero to stop it. There is no enabled flag: the worker+ * always drains while it is running, so there is no state where it holds a Kafka client it is not+ * using and no health check that has to explain one.+ *+ * Three rules the rest of this class exists to keep:+ *+ * It never produces to the source topic. ClickHouse consumes `clickhouse_events_json`, so putting+ * an event back there would duplicate it in the events table. The worker rebuilds invocations and+ * queues those instead, which is also why the generic DLQ replay tooling does not fit here.+ *+ * It rebuilds only the functions a record names. An event that failed for one function out of five+ * already reached the other four, and rebuilding all five would deliver to them twice.+ *+ * It commits offsets only once every invocation in the batch is queued. Anything else leaves them+ * where they are and fails the batch, so a record that cannot be replayed blocks rather than being+ * skipped. Scaling it back to zero is how an operator unblocks it and fixes forward. Batch size is+ * the deployment's `CONSUMER_BATCH_SIZE`: nothing here depends on it, but it decides how much of a+ * batch waits behind one record that will not replay.+ */+export class CdpDlqReplayConsumer extends CdpConsumerBase<PluginsServerConfig> {+ protected name = 'CdpDlqReplayConsumer'+ protected hogTypes: HogFunctionTypeType[] = ['destination']++ private kafkaConsumer: KafkaConsumerInterface+ private hogFunctionPipeline: HogFunctionInvocationPipeline+ private hogFlowPipeline: HogFlowInvocationPipeline+ private buildFailures = new ReplayFailureCollector()++ public readonly counts: CdpDlqReplayCounts = { replayed: 0, queued: 0 }++ constructor(+ config: PluginsServerConfig,+ deps: CdpConsumerBaseDeps,+ private jobQueues: { hogQueue: JobQueue; hogflowQueue: JobQueue }+ ) {+ super(config, deps)++ // Offsets are left to the consumer, which stores them once the batch handler resolves. That+ // is the guarantee this worker needs: the handler awaits the rebuild and the queueing, so a+ // record is only committed after its invocations exist, and a throw anywhere leaves the+ // offset where it was.+ //+ // `auto.offset.reset` is set rather than inherited, because KAFKA_CONSUMER_AUTO_OFFSET_RESET+ // applies to every consumer in the deployment. This one runs at zero replicas, so records+ // always land before it connects: a `latest` value would skip the backlog it was scaled up+ // to drain and report a clean run having replayed nothing.+ this.kafkaConsumer = createKafkaConsumer({ groupId: REPLAY_GROUP_ID, topic: config.CDP_DLQ_REPLAY_TOPIC }, {+ 'auto.offset.reset': 'earliest',+ } as RdKafkaConsumerConfig)++ this.hogFunctionPipeline = new HogFunctionInvocationPipeline(config, {+ hogFunctionManager: this.hogFunctionManager,+ hogInputsService: this.hogInputsService,+ hogWatcher: this.hogWatcher,+ hogWatcherMirror: this.hogWatcherMirror,+ hogMasker: this.hogMasker,+ hogFunctionMonitoringService: this.hogFunctionMonitoringService,+ cdpUsageReporter: this.cdpUsageReporter,+ quotaLimiting: deps.quotaLimiting,+ redis: this.redis,+ valkeyShadow: this.valkeyShadow,+ deadLetterService: this.buildFailures,+ })+ this.hogFlowPipeline = new HogFlowInvocationPipeline(config, {+ hogFlowManager: this.hogFlowManager,+ hogFlowExecutor: this.hogFlowExecutor,+ hogWatcher: this.hogWatcher,+ hogWatcherMirror: this.hogWatcherMirror,+ hogMasker: this.hogMasker,+ hogFunctionMonitoringService: this.hogFunctionMonitoringService,+ quotaLimiting: deps.quotaLimiting,+ redis: this.redis,+ valkeyShadow: this.valkeyShadow,+ deadLetterService: this.buildFailures,+ })+ }++ /**+ * Rebuilds one batch and queues the invocations.+ *+ * Everything here either succeeds for every record in the batch or throws. A record that cannot+ * be rebuilt — bytes that will not parse, a team that no longer exists — throws like any other+ * failure, so the offset stays put and the worker blocks on it. An operator turns the worker+ * off and either fixes forward or moves the group's offset past that record by hand.+ */+ public async replayBatch(messages: Message[]): Promise<void> {+ this.buildFailures.clear()+ const selected: { message: Message; record: DeadLetterRecord }[] = []+ for (const message of messages) {+ const record = readDeadLetterRecord(message)+ if (!record) {+ throw new Error(+ `Dead-letter record at ${message.topic}:${message.partition}:${message.offset} has no ` ++ 'dlq_step header, so there is nothing to rebuild from it'+ )+ }+ selected.push({ message, record })+ }+ if (!selected.length) {+ return+ }++ // Which sources each event may rebuild, held against the globals object the rebuild runs+ // from. One event can be parked more than once, because a record is written per event and+ // step: once at `filter` for one function, once at `inputs` for another. Their targets are+ // merged and the event is rebuilt once.+ //+ // Team and event UUID only group the candidates, and the parked bytes decide. A UUID comes+ // from the client, so one team can send two different events under the same one, and+ // merging those would hand a destination parked for one of them the other's payload. A+ // record parks the source bytes untouched, so two records for the same event compare equal.+ const eventKey = (globals: HogFunctionInvocationGlobals): string =>+ `${globals.project.id}:${globals.event.uuid}`+ const parkedByKey = new Map<string, { globals: HogFunctionInvocationGlobals; value: Buffer }[]>()+ const targetsByEvent = new Map<HogFunctionInvocationGlobals, Set<string> | null>()+ const kindsByEvent = new Map<HogFunctionInvocationGlobals, Set<SourceKind> | null>()+ const globalsList: HogFunctionInvocationGlobals[] = []++ const resolved = await Promise.all(selected.map(({ message }) => this.toGlobals(message)))++ let teamMissing = 0+ for (const [index, { message, record }] of selected.entries()) {+ const globals = resolved[index]+ if (globals === TEAM_MISSING) {+ teamMissing += 1+ continue+ }+ if (!globals) {+ throw new Error(+ `Could not rebuild an event from ${message.topic}:${message.partition}:${message.offset} — ` ++ 'refusing to commit past a parked event that was never replayed'+ )+ }+ const targets = replayTargetIds(record)+ const kinds = replayTargetKinds(record)+ // Present for every selected record: readDeadLetterRecord refuses one with no payload.+ const value = message.value!+ const key = eventKey(globals)+ const candidates = parkedByKey.get(key) ?? []+ const sameEvent = candidates.find((parked) => parked.value.equals(value))?.globals+ if (sameEvent) {+ const existingTargets = targetsByEvent.get(sameEvent)!+ const existingKinds = kindsByEvent.get(sameEvent)!+ // `null` is "everything", so a union with anything stays `null`.+ targetsByEvent.set(+ sameEvent,+ existingTargets === null || targets === null ? null : new Set([...existingTargets, ...targets])+ )+ kindsByEvent.set(+ sameEvent,+ existingKinds === null || kinds === null ? null : new Set([...existingKinds, ...kinds])+ )+ } else {+ candidates.push({ globals, value })+ parkedByKey.set(key, candidates)+ targetsByEvent.set(globals, targets)+ kindsByEvent.set(globals, kinds)+ globalsList.push(globals)+ }+ this.counts.replayed += 1+ }++ if (teamMissing) {+ counterReplayRecords.labels({ outcome: 'unreplayable' }).inc(teamMissing)+ }++ await this.groupsManager.addGroupsToGlobalsList(globalsList)++ // Both pipelines hand the predicates back the globals object they were given, so the lookup+ // is by identity rather than by any value read off the event.+ const allows = (id: string, globals: HogFunctionInvocationGlobals): boolean => {+ const targets = targetsByEvent.get(globals)+ return targets === null || targets === undefined ? targets === null : targets.has(id)+ }++ // A record that names a kind but no id is a pipeline that threw while the other one queued+ // its invocations. Rebuilding the kind it does not name would deliver those a second time.+ const allowsKind = (kind: SourceKind, globals: HogFunctionInvocationGlobals): boolean => {+ const kinds = kindsByEvent.get(globals)+ return kinds === null || kinds === undefined ? kinds === null : kinds.has(kind)+ }++ const [hogInvocations, hogflowInvocations] = await Promise.all([+ this.hogFunctionPipeline.buildInvocations(globalsList, {+ hogTypes: this.hogTypes,+ filterFn: (fn) => (fn.filters?.source ?? 'events') === 'events',+ invocationFilterFn: (fn, globals) => allowsKind('hog_function', globals) && allows(fn.id, globals),+ }),+ this.hogFlowPipeline.buildInvocations(globalsList, {+ eligibilityFn: (flow, globals) =>+ flow.trigger.type === 'event' && allowsKind('hog_flow', globals) && allows(flow.id, globals),+ }),+ ])++ // A filter or an input that throws does not reject the build, so an empty invocation list is+ // how a still-broken destination looks from here. Zero invocations on its own is not enough+ // to go on: a deleted, disabled, quota-limited or masked destination is also correctly+ // built and correctly not delivered.+ const { blocking, unreplayable } = partitionReplayFailures(this.buildFailures.failures)+ if (unreplayable) {+ counterReplayRecords.labels({ outcome: 'unreplayable' }).inc(unreplayable)+ }+ if (blocking.length) {+ const [first] = blocking+ throw new Error(+ `${blocking.length} source(s) in this batch still fail to build, ` ++ `first ${first.sourceKind} ${first.sourceId} at ${first.step}: ${first.error}. ` ++ 'Refusing to commit past records whose delivery did not happen'+ )+ }++ for (const invocation of [...hogInvocations, ...hogflowInvocations]) {+ // Marks the invocation as recovered so a `replayed` app metric can be added later+ // without changing the queue payload format.+ invocation.queueMetadata = { ...(invocation.queueMetadata as object), replayed_from_dlq: true }+ this.invocationResultsService.invocationResultsRowsService.queueLifecycleRow(invocation, 'running')+ }++ // A disabled, quota-limited or masked source is correctly not delivered, and the offset still+ // commits. Counting those events keeps a drained topic from reading as "everything was sent".+ const queuedEvents = new Set([+ ...hogInvocations.map((invocation) => `${invocation.teamId}:${invocation.state.globals.event.uuid}`),+ ...hogflowInvocations.map((invocation) => `${invocation.teamId}:${invocation.state?.event?.uuid}`),+ ])+ const filteredOut = globalsList.filter(+ (globals) =>+ !this.buildFailures.failedEvents.has(globals) &&+ !queuedEvents.has(`${globals.project.id}:${globals.event.uuid}`)+ ).length+ if (filteredOut) {+ counterReplayRecords.labels({ outcome: 'filtered_out' }).inc(filteredOut)+ }++ this.counts.queued += hogInvocations.length + hogflowInvocations.length+ // Records and invocations are different things: one record can rebuild several invocations+ // or none. Counting invocations under a record-shaped label made every outcome rate wrong.+ counterReplayRecords.labels({ outcome: 'rebuilt' }).inc(globalsList.length)+ counterReplayInvocations.inc(hogInvocations.length + hogflowInvocations.length)++ await Promise.all([+ this.jobQueues.hogQueue.queueInvocations(hogInvocations),+ this.jobQueues.hogflowQueue.queueInvocations(hogflowInvocations),+ this.hogFunctionMonitoringService.flush(),+ this.invocationResultsService.invocationResultsRowsService.flush(),+ ])+ }++ /**+ * Rebuilds the globals from the parked bytes, resolving everything around the event fresh.+ *+ * The event body is replayed exactly as it arrived, but everything the pipeline reads around it+ * is read again now: the team, the groups, and the person. `convertToHogFunctionInvocationGlobals`+ * would otherwise hand the destination the person snapshot frozen into the event at capture,+ * which can be months stale by the time a replay runs, while groups were already being resolved+ * fresh. A destination receiving a delivery today should see today's person.+ *+ * Errors are not caught. The caller turns a null into a thrown batch, and anything thrown here+ * reaches the same place, because the worker blocks on a record it cannot replay rather than+ * committing past it. A team that no longer exists is the exception: no fix brings its events+ * back, so the caller counts the record and moves on.+ */+ private async toGlobals(message: Message): Promise<HogFunctionInvocationGlobals | typeof TEAM_MISSING | null> {+ const event = readParkedEvent(message)+ if (!event) {+ return null+ }+ // getTeam throws when the lookup fails, so null means the team is gone and so is any chance+ // of delivering its events.+ const team = await this.deps.teamManager.getTeam(event.team_id)+ if (!team) {+ return TEAM_MISSING+ }+ const globals = convertToHogFunctionInvocationGlobals(event, team, this.config.SITE_URL)+ const person = await this.personsManager.getCyclotronPerson(event.team_id, event.distinct_id, 'distinct_id', {+ forceFresh: true,+ })+ // Keep the frozen snapshot when the person cannot be resolved: deleted, merged away, or+ // never written. Sending the destination nothing would be a bigger change than sending+ // it what the event carried.+ return person ? { ...globals, person } : globals+ }++ public override async start(): Promise<void> {+ await super.start()+ await Promise.all([this.jobQueues.hogQueue.startAsProducer(), this.jobQueues.hogflowQueue.startAsProducer()])++ logger.info('☠️', 'cdp_dlq_replay_start', { topic: this.config.CDP_DLQ_REPLAY_TOPIC })++ await this.kafkaConsumer.connect(async (messages) => {+ if (!messages.length) {+ return+ }++ await instrumentFn('cdpDlqReplay.handleEachBatch', () => this.replayBatch(messages))++ logger.info('☠️', 'cdp_dlq_replay_progress', this.counts)+ })+ }++ public override async stop(): Promise<void> {+ await this.kafkaConsumer.disconnect()+ await Promise.all([this.jobQueues.hogQueue.stopProducer(), this.jobQueues.hogflowQueue.stopProducer()])+ await super.stop()+ }++ public isHealthy(): HealthCheckResult {+ return this.kafkaConsumer.isHealthy()+ }+}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.tsindex 273d37e5eca7..b0c91bbdd05c 100644--- a/nodejs/src/cdp/services/dead-letter/cdp-dead-letter.service.ts+++ b/nodejs/src/cdp/services/dead-letter/cdp-dead-letter.service.ts@@ -26,7 +26,7 @@ type PendingFailure = {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 =>+export const isOurFailure = (failure: { errorClass?: HogErrorClass }): boolean =>failure.errorClass === undefined || PARKED_CLASSES.has(failure.errorClass)export type CdpDlqOutput = CdpEventsDlqOutput@@ -143,10 +143,14 @@ export class CdpDeadLetterService implements InvocationFailureSink {if (!this.config.CDP_DLQ_ENABLED || !failures.length) {return}- const ours = failures.filter(isOurs)+ const ours = failures.filter(isOurFailure)for (const failure of failures) {counterFailuresByClass- .labels({ step: failure.step, class: failure.errorClass ?? 'unknown', parked: String(isOurs(failure)) })+ .labels({+ step: failure.step,+ class: failure.errorClass ?? 'unknown',+ parked: String(isOurFailure(failure)),+ }).inc()}if (!ours.length) {diff --git a/nodejs/src/cdp/services/dead-letter/replay-policy.test.ts b/nodejs/src/cdp/services/dead-letter/replay-policy.test.tsnew file mode 100644index 000000000000..08a843414da2--- /dev/null+++ b/nodejs/src/cdp/services/dead-letter/replay-policy.test.ts@@ -0,0 +1,134 @@+import { Message } from 'node-rdkafka'++import type { InvocationBuildFailure } from '../../types'+import {+ partitionReplayFailures,+ readDeadLetterRecord,+ readParkedEvent,+ replayTargetIds,+ replayTargetKinds,+} from './replay-policy'++describe('replay policy', () => {+ const message = (headers: Record<string, string>, value: string | null = '{"team_id":2}'): Message =>+ ({+ value: value === null ? null : Buffer.from(value),+ headers: Object.entries(headers).map(([key, header]) => ({ [key]: Buffer.from(header) })),+ topic: 'cdp_events_dlq',+ partition: 0,+ offset: 1,+ size: 0,+ }) as unknown as Message++ it('reads a record from its headers without touching the payload', () => {+ const record = readDeadLetterRecord(+ message({+ dlq_step: 'inputs',+ dlq_reason: 'Invalid arguments',+ dlq_team_id: '2',+ dlq_hog_function_ids: 'fn-1,fn-2',+ dlq_hog_flow_ids: 'flow-1',+ dlq_kinds: 'hog_function,hog_flow',+ })+ )++ expect(record).toEqual({+ hogFunctionIds: ['fn-1', 'fn-2'],+ hogFlowIds: ['flow-1'],+ kinds: ['hog_function', 'hog_flow'],+ })+ })++ it.each([+ ['no step header', message({})],+ ['a step header but no value', message({ dlq_step: 'inputs' }, null)],+ ])('returns null for %s', (_label, built) => {+ expect(readDeadLetterRecord(built)).toBeNull()+ })++ it('targets only the sources a record names, across both kinds', () => {+ const record = readDeadLetterRecord(+ message({ dlq_step: 'filter', dlq_hog_function_ids: 'fn-1', dlq_hog_flow_ids: 'flow-1' })+ )!++ expect(replayTargetIds(record)).toEqual(new Set(['fn-1', 'flow-1']))+ })++ it('targets only the kind that threw when a record names a kind but no source', () => {+ // The pipeline that did not throw already queued its invocations for this event.+ const record = readDeadLetterRecord(message({ dlq_step: 'process', dlq_kinds: 'hog_flow' }))!++ expect(replayTargetIds(record)).toBeNull()+ expect(replayTargetKinds(record)).toEqual(new Set(['hog_flow']))+ })++ it('targets every kind when a record names none, because nothing was built', () => {+ expect(replayTargetKinds(readDeadLetterRecord(message({ dlq_step: 'parse' }))!)).toBeNull()+ })++ it('targets everything when a record names nothing, because nothing was built', () => {+ const record = readDeadLetterRecord(message({ dlq_step: 'process' }))!++ expect(replayTargetIds(record)).toBeNull()+ })++ it('does not rebuild an event whose payload names no team', () => {+ expect(readParkedEvent(message({ dlq_step: 'parse' }, '{"uuid":"abc"}'))).toBeNull()+ })++ it('throws on bytes that will not parse, rather than reporting nothing to replay', () => {+ // The worker blocks on a record it cannot rebuild. Returning null here would read as+ // "nothing to do" and commit the offset past an event that was never replayed.+ expect(() => readParkedEvent(message({ dlq_step: 'parse' }, '{"broken'))).toThrow()+ })++ it('rebuilds an event from parked bytes', () => {+ expect(readParkedEvent(message({ dlq_step: 'inputs' }, '{"team_id":2,"uuid":"abc"}'))).toMatchObject({+ team_id: 2,+ uuid: 'abc',+ })+ })+})++describe('partitionReplayFailures', () => {+ const failure = (overrides: Partial<InvocationBuildFailure>): InvocationBuildFailure => ({+ sourceId: 'fn-1',+ sourceKind: 'hog_function',+ step: 'inputs',+ error: 'boom',+ ...overrides,+ })++ it('blocks on a failure that is ours, so the offset is not committed past a lost delivery', () => {+ const { blocking, unreplayable } = partitionReplayFailures([+ failure({ errorClass: 'drift' }),+ failure({ errorClass: 'bug' }),+ failure({ errorClass: 'platform' }),+ failure({}),+ ])++ expect(blocking).toHaveLength(4)+ expect(unreplayable).toBe(0)+ })++ it('passes over a failure no replay can clear, so one record cannot wedge the worker', () => {+ const { blocking, unreplayable } = partitionReplayFailures([+ failure({ errorClass: 'data' }),+ failure({ errorClass: 'limit' }),+ failure({ errorClass: 'legacy' }),+ ])++ expect(blocking).toHaveLength(0)+ expect(unreplayable).toBe(3)+ })++ it('still blocks when only one of a mixed batch is ours', () => {+ const { blocking, unreplayable } = partitionReplayFailures([+ failure({ errorClass: 'data' }),+ failure({ sourceId: 'fn-2', errorClass: 'drift' }),+ ])++ expect(blocking).toEqual([expect.objectContaining({ sourceId: 'fn-2' })])+ expect(unreplayable).toBe(1)+ })+})diff --git a/nodejs/src/cdp/services/dead-letter/replay-policy.ts b/nodejs/src/cdp/services/dead-letter/replay-policy.tsnew file mode 100644index 000000000000..a57f6c210cae--- /dev/null+++ b/nodejs/src/cdp/services/dead-letter/replay-policy.ts@@ -0,0 +1,103 @@+import { Message } from 'node-rdkafka'++import { parseJSON } from '~/common/utils/json-parse'++import type { RawClickHouseEvent } from '../../../types'+import type { InvocationBuildFailure } from '../../types'+import { isOurFailure } from './cdp-dead-letter.service'++/**+ * A dead-letter record, read from its headers alone.+ *+ * Only the two id lists are here. The producer writes the step, reason, team and source position+ * too, but those exist for a person reading the topic, and reading them into this type would+ * suggest the worker branches on them.+ */+export interface DeadLetterRecord {+ hogFunctionIds: string[]+ hogFlowIds: string[]+ /** Which kinds this record's replay may rebuild. Empty means nothing was built, so both. */+ kinds: SourceKind[]+}++export type SourceKind = 'hog_function' | 'hog_flow'++function headerValues(message: Message): Record<string, string> {+ const values: Record<string, string> = {}+ for (const header of message.headers ?? []) {+ for (const [key, value] of Object.entries(header)) {+ if (value === undefined) {+ continue+ }+ values[key] = Buffer.isBuffer(value) ? value.toString() : String(value)+ }+ }+ return values+}++function idList(value: string | undefined): string[] {+ return (value ?? '')+ .split(',')+ .map((id) => id.trim())+ .filter(Boolean)+}++/** Reads a record's headers without touching its payload. `dlq_step` marks it as one of ours. */+export function readDeadLetterRecord(message: Message): DeadLetterRecord | null {+ const headers = headerValues(message)+ if (!headers.dlq_step || !message.value) {+ return null+ }++ return {+ hogFunctionIds: idList(headers.dlq_hog_function_ids),+ hogFlowIds: idList(headers.dlq_hog_flow_ids),+ kinds: idList(headers.dlq_kinds).filter(+ (kind): kind is SourceKind => kind === 'hog_function' || kind === 'hog_flow'+ ),+ }+}++/**+ * Restricts a rebuild to the sources the record names.+ *+ * This is what stops a replay double-delivering. An event that failed for one function out of five+ * was already delivered to the other four, and rebuilding all five would send those again. An empty+ * list means nothing was built the first time, so everything is in scope.+ */+export function replayTargetIds(record: DeadLetterRecord): Set<string> | null {+ const named = [...record.hogFunctionIds, ...record.hogFlowIds]+ return named.length ? new Set(named) : null+}++/**+ * Which pipelines may rebuild for this record.+ *+ * Null is every kind, and only right when nothing was built the first time. A `process` failure+ * names its kind but no id, because the two pipelines run against the same event: one can queue its+ * invocations while the other throws, and rebuilding both would re-deliver what already went out.+ */+export function replayTargetKinds(record: DeadLetterRecord): Set<SourceKind> | null {+ return record.kinds.length ? new Set(record.kinds) : null+}++/** Reads a parked payload. Null when the bytes are not an event this worker can rebuild. */+export function readParkedEvent(message: Message): RawClickHouseEvent | null {+ if (!message.value) {+ return null+ }+ const event = parseJSON(message.value.toString()) as RawClickHouseEvent+ return event.team_id ? event : null+}++/**+ * A rebuild that fails on the owner's data or budget fails the same way on every attempt, so+ * holding the offset for it wedges the worker on a record no retry can clear.+ */+export function partitionReplayFailures(failures: InvocationBuildFailure[]): {+ blocking: InvocationBuildFailure[]+ unreplayable: number+} {+ const blocking = failures.filter(isOurFailure)+ return { blocking, unreplayable: failures.length - blocking.length }+}diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.tsindex 36cadc47a980..d838ea19834b 100644--- a/nodejs/src/common/config.ts+++ b/nodejs/src/common/config.ts@@ -63,6 +63,7 @@ export enum PluginServerMode {cdp_cyclotron_worker_batch_resolve = 'cdp-cyclotron-worker-batch-resolve',cdp_cyclotron_v2_janitor = 'cdp-cyclotron-v2-janitor',cdp_rerun_worker = 'cdp-rerun-worker',+ cdp_dlq_replay = 'cdp-dlq-replay',recording_api = 'recording-api',ingestion_v2_combined = 'ingestion-v2-combined',ingestion_traces = 'ingestion-traces',diff --git a/nodejs/src/server.ts b/nodejs/src/server.tsindex 362409c07065..2ba7bbdf73e2 100644--- a/nodejs/src/server.ts+++ b/nodejs/src/server.ts@@ -30,6 +30,7 @@ import { CdpCyclotronWorkerEmail } from './cdp/consumers/cdp-cyclotron-worker-emimport { CdpCyclotronWorkerHogFlow } from './cdp/consumers/cdp-cyclotron-worker-hogflow.consumer'import { CdpCyclotronWorker } from './cdp/consumers/cdp-cyclotron-worker.consumer'import { CdpDatawarehouseEventsConsumer } from './cdp/consumers/cdp-data-warehouse-events.consumer'+import { CdpDlqReplayConsumer } from './cdp/consumers/cdp-dlq-replay.consumer'import { CdpEventsConsumer } from './cdp/consumers/cdp-events.consumer'import { CdpHogflowSubscriptionMatcherConsumer } from './cdp/consumers/cdp-hogflow-subscription-matcher.consumer'import { CdpInternalEventsConsumer } from './cdp/consumers/cdp-internal-event.consumer'@@ -103,7 +104,8 @@ export class PluginServer implements NodeServer {capabilities.cdpCohortMembership ||capabilities.cdpCyclotronWorkerBatchResolve ||capabilities.cdpHogflowSubscriptionMatcher ||- capabilities.cdpRerunWorker+ capabilities.cdpRerunWorker ||+ capabilities.cdpDlqReplay)// The janitor records poison-pill give-ups as failed invocation results,// so it needs the Kafka producer registry — but NOT createCdpSharedServices@@ -319,6 +321,17 @@ export class PluginServer implements NodeServer {})}+ if (capabilities.cdpDlqReplay) {+ serviceLoaders.push(async () => {+ const worker = new CdpDlqReplayConsumer(this.config, cdpDeps!, {+ hogQueue: kafkaQueue,+ hogflowQueue: postgresV2Queue,+ })+ await worker.start()+ return worker.service+ })+ }+// Boot-time guard: an email-sending deployment must carry a signing key, otherwise every send// would either mint an unsigned tracking link or (now that generate() fails closed) fail. Refuse// to start instead of degrading silently. The email worker below signs tracking codes.diff --git a/nodejs/src/types.ts b/nodejs/src/types.tsindex 53b929eb7928..bd5b9624fc97 100644--- a/nodejs/src/types.ts+++ b/nodejs/src/types.ts@@ -150,6 +150,7 @@ export interface PluginServerCapabilities {evaluationScheduler?: booleancdpCyclotronV2Janitor?: booleancdpRerunWorker?: boolean+ cdpDlqReplay?: booleancdpHogflowScheduler?: booleancdpHogflowSubscriptionMatcher?: booleanrecordingApi?: boolean