: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
fix(cdp): Queue invocations synchronously to prevent silent kafka offset advances (#58033)
Daniel Marchuk9f0af4f581fb
diff --git a/nodejs/src/kafka/consumer/consumer-v2.test.ts b/nodejs/src/kafka/consumer/consumer-v2.test.tsindex 0655ae0d3760..a101ae1b29fe 100644--- a/nodejs/src/kafka/consumer/consumer-v2.test.ts+++ b/nodejs/src/kafka/consumer/consumer-v2.test.ts@@ -604,6 +604,60 @@ describe('KafkaConsumerV2', () => {expect(mockRdKafka.offsetsStore).not.toHaveBeenCalled()})+ it('backgroundTask rejection: latches fatalError and skips offset store', async () => {+ // Loop-exit propagation is covered by the existing "eachBatch throwing" test plus+ // the runLoop fatalError guard. Here we pin the new behavior: the rejection is+ // latched onto fatalError and offsets for the failed batch are not stored.+ const eachBatch = jest.fn(() => Promise.resolve({}))+ await startConsuming(eachBatch)+ // Suppress unhandled-rejection warning in case the loop ticks (and throws fatalError)+ // during afterEach teardown before disconnect attaches its catch handler.+ ;((consumer as any).loopDone as Promise<void>).catch(() => {})++ const failure = new Error('column "X" does not exist')+ const failing = triggerablePromise<void>()+ eachBatch.mockImplementationOnce(() => Promise.resolve({ backgroundTask: failing.promise }))++ consumeCallback!(null, [createMessage({ offset: 1, partition: 0 })])+ await delay(2)+ failing.reject(failure)+ await delay(10)++ expect(captureException).toHaveBeenCalledWith(failure)+ expect((consumer as any).fatalError).toBe(failure)+ expect(mockRdKafka.offsetsStore).not.toHaveBeenCalled()+ })++ it('backgroundTask rejection: a later successful batch must NOT advance the bookmark past the failed one', async () => {+ // The cross-batch ordering bug: batch N's task fails, batch N+1's succeeds, and+ // without the fatalError gate batch N+1 would store its (higher) offset, silently+ // committing past the lost events.+ ;(consumer as any).maxBackgroundTasks = 4+ const eachBatch = jest.fn(() => Promise.resolve({}))+ await startConsuming(eachBatch)+ ;((consumer as any).loopDone as Promise<void>).catch(() => {})++ const failure = new Error('column "X" does not exist')+ const slowFailure = triggerablePromise<void>()+ eachBatch.mockImplementationOnce(() => Promise.resolve({ backgroundTask: slowFailure.promise }))+ consumeCallback!(null, [createMessage({ offset: 100, partition: 0 })])+ await delay(2)++ // Second batch on the same partition with a successful, fast task.+ eachBatch.mockImplementationOnce(() => Promise.resolve({ backgroundTask: Promise.resolve() }))+ consumeCallback!(null, [createMessage({ offset: 200, partition: 0 })])+ await delay(10)++ // Resolve the first batch's task with a failure AFTER batch N+1 finished its own work.+ slowFailure.reject(failure)+ await delay(20)++ const partition0Stores = (mockRdKafka.offsetsStore as jest.Mock).mock.calls.filter(([offsets]) =>+ offsets.some((o: any) => o.partition === 0)+ )+ expect(partition0Stores).toEqual([])+ })+it('Health: not connected → error', () => {;(mockRdKafka.isConnected as jest.Mock).mockReturnValue(false)const result = consumer.isHealthy()diff --git a/nodejs/src/kafka/consumer/consumer-v2.ts b/nodejs/src/kafka/consumer/consumer-v2.tsindex ef22037a6f7e..fb2515669de1 100644--- a/nodejs/src/kafka/consumer/consumer-v2.ts+++ b/nodejs/src/kafka/consumer/consumer-v2.ts@@ -86,6 +86,10 @@ export class KafkaConsumerV2 {private inFlight: TaskEntry[] = []private loopDone: Promise<void> | undefined+ // Latched on the first backgroundTask failure: blocks further offset stores and+ // makes the loop exit on the next tick so the pod replays from the last good commit.+ private fatalError: unknown | undefined+// Tunables (resolved at construction)private fetchBatchSize: numberprivate batchTimeoutMs: number@@ -241,6 +245,12 @@ export class KafkaConsumerV2 {while (this.running) {this.lastLoopTickAt = Date.now()+ // Check before fetching another batch — any further offset commit after a+ // task failure is the silent-drop bug.+ if (this.fatalError) {+ throw this.fatalError+ }+// 1. Drain rebalance events. handleRebalanceEvent on REVOKE awaits drainAll// and calls incrementalUnassign before returning.while (this.rebalanceQueue.length > 0) {@@ -306,6 +316,11 @@ export class KafkaConsumerV2 {}): undefined+ // Serialize store decisions in batch order: without this a faster later batch+ // could store its (higher) offset before an earlier failed batch latches fatalError.+ const predecessorSettled =+ this.inFlight.length > 0 ? this.inFlight[this.inFlight.length - 1].settled : undefined+const settled: Promise<void> = (async () => {try {const { timedOut } = await raceWithTimeout(Promise.resolve(raw), this.backgroundTaskTimeoutMs)@@ -315,12 +330,19 @@ export class KafkaConsumerV2 {} catch (error) {logger.error('🔥', 'kafka_consumer_v2_background_task_failed', { error: String(error) })captureException(error)- // Do not store offsets when the task failed.- return+ this.fatalError ??= error} finally {stopBackgroundTimer?.()}+ if (predecessorSettled) {+ await predecessorSettled+ }++ if (this.fatalError) {+ return+ }+if (this.config.autoCommit && this.config.autoOffsetStore) {if (gen !== this.generation) {// The partitions backing these offsets were revoked between dispatch and now.