: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(ingestion): drop latest_processed_timestamp_ms series on partition revoke (#105133)
Paweł Ledwońa67cc3978faf
diff --git a/nodejs/src/common/kafka/consumer/consumer-v1.test.ts b/nodejs/src/common/kafka/consumer/consumer-v1.test.tsindex 2eb8985fa5b6..59b5626f4053 100644--- a/nodejs/src/common/kafka/consumer/consumer-v1.test.ts+++ b/nodejs/src/common/kafka/consumer/consumer-v1.test.ts@@ -379,9 +379,11 @@ describe('consumer', () => {expect(consumer['rebalanceCoordination'].isRebalancing).toBe(false)})- it('should unassign and resume consuming when no background tasks exist', async () => {+ it('should unassign, call the revoke hook and resume consuming when no background tasks exist', async () => {consumer['backgroundTask'] = []mockRdKafkaConsumer.assignments.mockReturnValue([{ topic: 'test-topic', partition: 2 }])+ const onPartitionsRevoked = jest.fn().mockResolvedValue(undefined)+ consumer['onPartitionsRevoked'] = onPartitionsRevokedconsumer.rebalanceCallback({ code: CODES.ERRORS.ERR__REVOKE_PARTITIONS } as any, [{ topic: 'test-topic', partition: 1 },@@ -392,6 +394,7 @@ describe('consumer', () => {{ topic: 'test-topic', partition: 1 },])expect(consumer['rebalanceCoordination'].isRebalancing).toBe(false)+ expect(onPartitionsRevoked).toHaveBeenCalledWith([{ topic: 'test-topic', partition: 1 }])})it('should resume consuming when unassigning revoked partitions throws', () => {diff --git a/nodejs/src/common/kafka/consumer/consumer-v1.ts b/nodejs/src/common/kafka/consumer/consumer-v1.tsindex d07d7930b531..6842ca666d22 100644--- a/nodejs/src/common/kafka/consumer/consumer-v1.ts+++ b/nodejs/src/common/kafka/consumer/consumer-v1.ts@@ -155,6 +155,7 @@ export class KafkaConsumer {rebalanceStartTime: 0,}private consumerLogStatsLevel: LogLevel+ private onPartitionsRevoked?: (assignments: Assignment[]) => Promise<void>constructor(private config: KafkaConsumerConfig,@@ -467,6 +468,11 @@ export class KafkaConsumer {} finally {this.resetRebalanceCoordination()}+ Promise.resolve()+ .then(() => this.onPartitionsRevoked?.(assignments))+ .catch((error) => {+ logger.error('🔁', 'partition_revoked_handler_failed', { error: String(error) })+ })}private updateMetricsAfterRevocation(assignments: Assignment[]): void {@@ -599,9 +605,11 @@ export class KafkaConsumer {}public async connect(- eachBatch: (messages: Message[]) => Promise<{ backgroundTask?: Promise<any> } | void>+ eachBatch: (messages: Message[]) => Promise<{ backgroundTask?: Promise<any> } | void>,+ onPartitionsRevoked?: (assignments: Assignment[]) => Promise<void>): Promise<void> {const { topic, groupId, callEachBatchWhenEmpty = false } = this.config+ this.onPartitionsRevoked = onPartitionsRevokedtry {await promisifyCallback<Metadata>((cb) => this.rdKafkaConsumer.connect({}, cb))diff --git a/nodejs/src/common/kafka/consumer/index.ts b/nodejs/src/common/kafka/consumer/index.tsindex 134bd14e3d60..c39bc6523c73 100644--- a/nodejs/src/common/kafka/consumer/index.ts+++ b/nodejs/src/common/kafka/consumer/index.ts@@ -1,4 +1,4 @@-import { Message, PartitionMetadata, TopicPartitionOffset } from 'node-rdkafka'+import { Assignment, Message, PartitionMetadata, TopicPartitionOffset } from 'node-rdkafka'import { HealthCheckResult } from '~/types'@@ -26,7 +26,10 @@ export const START_AT_LATEST = { ['auto.offset.reset' as keyof RdKafkaConsumerCo* implementations to support it.*/export interface KafkaConsumerInterface {- connect(eachBatch: (messages: Message[]) => Promise<{ backgroundTask?: Promise<unknown> } | void>): Promise<void>+ connect(+ eachBatch: (messages: Message[]) => Promise<{ backgroundTask?: Promise<unknown> } | void>,+ onPartitionsRevoked?: (revokedPartitions: Assignment[]) => Promise<void>+ ): Promise<void>disconnect(): Promise<void>isHealthy(): HealthCheckResultoffsetsStore(offsets: TopicPartitionOffset[]): voiddiff --git a/nodejs/src/ingestion/ingestion-consumer.serial.test.ts b/nodejs/src/ingestion/ingestion-consumer.serial.test.tsindex 0059f4f9b0f6..9c1a683c6626 100644--- a/nodejs/src/ingestion/ingestion-consumer.serial.test.ts+++ b/nodejs/src/ingestion/ingestion-consumer.serial.test.ts@@ -29,7 +29,7 @@ import { forSnapshot } from '~/tests/helpers/snapshots'import { createTeam, fetchPostgresPersons, getFirstTeam, getTeam, resetTestDatabase } from '~/tests/helpers/sql'import { CookielessServerHashMode, PipelineEvent, Team } from '~/types'-import { IngestionConsumer } from './ingestion-consumer'+import { IngestionConsumer, latestOffsetTimestampGauge } from './ingestion-consumer'const DEFAULT_TEST_TIMEOUT = 5000jest.setTimeout(DEFAULT_TEST_TIMEOUT)@@ -224,6 +224,21 @@ describe('IngestionConsumer', () => {expect(forSnapshot(mockProducerObserver.getProducedKafkaMessages())).toMatchSnapshot()})+ it('should stop exporting the processed timestamp of revoked partitions', async () => {+ latestOffsetTimestampGauge.reset()+ const messages = createKafkaMessages([createEvent(), createEvent()])+ messages[1].partition = 2+ await ingester.handleKafkaBatch(messages)++ const onPartitionsRevoked = jest.mocked(ingester['kafkaConsumer'].connect).mock.calls[0][1]!+ await onPartitionsRevoked([{ topic: 'test', partition: 1 }])++ const { values } = await latestOffsetTimestampGauge.get()+ expect(values.filter((v) => v.labels.groupId === ingester['groupId'])).toEqual([+ expect.objectContaining({ labels: expect.objectContaining({ topic: 'test', partition: 2 }) }),+ ])+ })+it('should process a cookieless event', async () => {await ingester.handleKafkaBatch(createKafkaMessages([createCookielessEvent()]))diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.tsindex 407b0fc56519..05e5c1364dda 100644--- a/nodejs/src/ingestion/ingestion-consumer.ts+++ b/nodejs/src/ingestion/ingestion-consumer.ts@@ -1,4 +1,4 @@-import { Message } from 'node-rdkafka'+import { Assignment, Message } from 'node-rdkafka'import { Gauge, Histogram } from 'prom-client'import { CommonConfig } from '~/common/config'@@ -341,15 +341,18 @@ export class IngestionConsumer {}this.joinedPipeline = createJoinedIngestionPipeline(joinedPipelineConfig, joinedPipelineDeps)- await this.kafkaConsumer.connect(async (messages) => {- return await instrumentFn(- {- key: `ingestionConsumer.handleEachBatch`,- sendException: false,- },- async () => await this.handleKafkaBatch(messages)- )- })+ await this.kafkaConsumer.connect(+ async (messages) => {+ return await instrumentFn(+ {+ key: `ingestionConsumer.handleEachBatch`,+ sendException: false,+ },+ async () => await this.handleKafkaBatch(messages)+ )+ },+ (revokedPartitions) => this.onPartitionsRevoked(revokedPartitions)+ )}public async stop(): Promise<void> {@@ -463,6 +466,13 @@ export class IngestionConsumer {}}+ private onPartitionsRevoked(revokedPartitions: Assignment[]): Promise<void> {+ for (const { topic, partition } of revokedPartitions) {+ latestOffsetTimestampGauge.remove({ topic, partition, groupId: this.groupId })+ }+ return Promise.resolve()+ }+private async runIngestionPipeline(messages: Message[]): Promise<void> {const batch = messages.map((message) =>createOkContext({ message }, { message, debugContext: createKafkaDebugContext(message) })