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.

chore(ai-research): allow bounded image fetch batch overlap (#99971)

Robbie3836acdfb283
diff --git a/nodejs/src/common/kafka/consumer/consumer-v2.test.ts b/nodejs/src/common/kafka/consumer/consumer-v2.test.ts
index 48088713f320..1ea91bedbffe 100644
--- a/nodejs/src/common/kafka/consumer/consumer-v2.test.ts
+++ b/nodejs/src/common/kafka/consumer/consumer-v2.test.ts
@@ -1,5 +1,6 @@
import { CODES, Message, KafkaConsumer as RdKafkaConsumer } from 'node-rdkafka'
+import { ImageFetchBatchJoiner } from '../../../ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner'
import { captureException } from '../../utils/posthog'
import { delay } from '../../utils/utils'
import { KafkaConsumerV2 } from './consumer-v2'
@@ -208,26 +209,44 @@ describe('KafkaConsumerV2', () => {
expect(mockRdKafka.offsetsStore).toHaveBeenCalledWith([{ topic: 'test-topic', partition: 0, offset: 2 }])
})
- it('Backpressure: pushing > maxBackgroundTasks blocks until oldest settles', async () => {
- ;(consumer as any).maxBackgroundTasks = 2
- const eachBatch = jest.fn(() => Promise.resolve({}))
- await startConsuming(eachBatch)
-
- const p1 = triggerablePromise()
- const p2 = triggerablePromise()
- const p3 = triggerablePromise()
+ it.each(['direct', 'image fetch joiner'])(
+ 'bounds %s background work and holds later offsets until the oldest batch settles',
+ async (mode) => {
+ consumer = new KafkaConsumerV2({ groupId: 'test-group', topic: 'test-topic', maxBackgroundTasks: 2 })
+ const p1 = triggerablePromise<void>()
+ const p2 = triggerablePromise<void>()
+ const processBatch = jest.fn().mockReturnValueOnce(p1.promise).mockReturnValueOnce(p2.promise)
+ const joiner = new ImageFetchBatchJoiner(1, processBatch)
+ const eachBatch = jest.fn((messages: Message[]) =>
+ mode === 'direct'
+ ? Promise.resolve({ backgroundTask: processBatch(messages) })
+ : joiner.handleBatch(messages)
+ )
+ await startConsuming(eachBatch)
+
+ consumeCallback!(null, [createMessage({ offset: 1, partition: 0 })])
+ await delay(5)
+ const pollsAfterFirstBatch = mockRdKafka.consume.mock.calls.length
+ consumeCallback!(null, [createMessage({ offset: 2, partition: 0 })])
+ await delay(5)
+ expect(processBatch).toHaveBeenCalledTimes(2)
+ expect(mockRdKafka.consume).toHaveBeenCalledTimes(pollsAfterFirstBatch)
+ expect(mockRdKafka.offsetsStore).not.toHaveBeenCalled()
- await dispatchBatch(eachBatch, [createMessage({ offset: 1, partition: 0 })], p1.promise)
- await dispatchBatch(eachBatch, [createMessage({ offset: 2, partition: 0 })], p2.promise)
- await dispatchBatch(eachBatch, [createMessage({ offset: 3, partition: 0 })], p3.promise)
- await delay(2)
+ p2.resolve()
+ await delay(5)
+ expect(mockRdKafka.consume).toHaveBeenCalledTimes(pollsAfterFirstBatch)
+ expect(mockRdKafka.offsetsStore).not.toHaveBeenCalled()
- // Loop is blocked on backpressure; consume() should NOT have been called for batch 4.
- const callsBefore = mockRdKafka.consume.mock.calls.length
- p1.resolve()
- await delay(5)
- expect(mockRdKafka.consume.mock.calls.length).toBeGreaterThan(callsBefore)
- })
+ p1.resolve()
+ await delay(5)
+ expect(mockRdKafka.consume.mock.calls.length).toBeGreaterThan(pollsAfterFirstBatch)
+ expect(mockRdKafka.offsetsStore.mock.calls).toEqual([
+ [[{ topic: 'test-topic', partition: 0, offset: 2 }]],
+ [[{ topic: 'test-topic', partition: 0, offset: 3 }]],
+ ])
+ }
+ )
it('REVOKE drain: incrementalUnassign called only after every settled completes', async () => {
;(consumer as any).maxBackgroundTasks = 5
@@ -807,6 +826,37 @@ describe('KafkaConsumerV2', () => {
expect(partition0Stores).toEqual([])
})
+ it('fails unfinished background work at the configured timeout without advancing offsets', async () => {
+ jest.useFakeTimers()
+ try {
+ consumer = new KafkaConsumerV2({
+ groupId: 'test-group',
+ topic: 'test-topic',
+ backgroundTaskTimeoutMs: 100,
+ })
+ const task = triggerablePromise<void>()
+ const eachBatch = jest.fn(() => Promise.resolve({ backgroundTask: task.promise }))
+ const starting = startConsuming(eachBatch)
+ await jest.advanceTimersByTimeAsync(5)
+ await starting
+ const loopFailure = (consumer as unknown as { loopDone: Promise<void> }).loopDone.catch(
+ (error: unknown) => error
+ )
+ consumeCallback!(null, [createMessage({ offset: 1, partition: 0 })])
+ await jest.advanceTimersByTimeAsync(99)
+ expect(captureException).not.toHaveBeenCalled()
+ expect(mockRdKafka.offsetsStore).not.toHaveBeenCalled()
+
+ await jest.advanceTimersByTimeAsync(1)
+ expect(captureException).toHaveBeenCalledWith(new Error('background_task_timeout_after_100ms'))
+ expect(mockRdKafka.offsetsStore).not.toHaveBeenCalled()
+ await expect(loopFailure).resolves.toEqual(new Error('background_task_timeout_after_100ms'))
+ task.resolve()
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
it('Health: not connected → error', () => {
;(mockRdKafka.isConnected as jest.Mock).mockReturnValue(false)
const result = consumer.isHealthy()
diff --git a/nodejs/src/common/kafka/consumer/consumer-v2.ts b/nodejs/src/common/kafka/consumer/consumer-v2.ts
index 7feaff1cf707..d1fc272a6a4a 100644
--- a/nodejs/src/common/kafka/consumer/consumer-v2.ts
+++ b/nodejs/src/common/kafka/consumer/consumer-v2.ts
@@ -56,6 +56,7 @@ export type KafkaConsumerV2Config = {
enablePartitionEof?: boolean
fetchBatchSize?: number
maxBackgroundTasks?: number
+ backgroundTaskTimeoutMs?: number
rebalanceTimeoutMs?: number
}
@@ -142,7 +143,8 @@ export class KafkaConsumerV2 {
this.fetchBatchSize = config.fetchBatchSize ?? defaultConfig.CONSUMER_BATCH_SIZE
this.batchTimeoutMs = this.config.batchTimeoutMs ?? DEFAULT_BATCH_TIMEOUT_MS
this.maxBackgroundTasks = config.maxBackgroundTasks ?? defaultConfig.CONSUMER_MAX_BACKGROUND_TASKS
- this.backgroundTaskTimeoutMs = defaultConfig.CONSUMER_BACKGROUND_TASK_TIMEOUT_MS
+ this.backgroundTaskTimeoutMs =
+ config.backgroundTaskTimeoutMs ?? defaultConfig.CONSUMER_BACKGROUND_TASK_TIMEOUT_MS
this.drainTimeoutMs = config.rebalanceTimeoutMs ?? defaultConfig.CONSUMER_REBALANCE_TIMEOUT_MS
this.loopStallThresholdMs = defaultConfig.CONSUMER_LOOP_STALL_THRESHOLD_MS || LOOP_STALL_THRESHOLD_MS_DEFAULT
this.logStatsLevel = defaultConfig.CONSUMER_LOG_STATS_LEVEL
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
index db7c4c3cd0ae..34f3e0870696 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
@@ -40,7 +40,7 @@ The queue tracks the remaining request slots from active and waiting jobs. It ap
The frontier consumer uses cooperative rebalancing. Its revoke path drains active work before it releases assigned partitions.
-Each image-fetch worker creates two Kafka group members by default. A local joiner combines their batches before it starts a fetch pass. Group assignments do not overlap, and each member can own multiple partitions. The joiner processes available batches when its join window ends. A later group can run concurrently instead of spending its Kafka poll interval behind a full pass. Shared request limits still bound total network concurrency. The worker divides a 100 MiB Kafka prefetch budget across its group members, with a minimum of 25 MiB per member. This preserves the queue sizes for one to four members and allows a default maximum-sized record in each queue. Sixteen members have a combined prefetch budget of 400 MiB. During a mixed-version rollout, pods with more group members can receive more partitions until the rollout finishes. `SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH` accepts targets from one to sixteen for worker-count experiments.
+Each image-fetch worker creates two Kafka group members by default. A local joiner combines their batches before it starts a fetch pass. Group assignments do not overlap, and each member can own multiple partitions. The joiner processes available batches when its join window ends. Each member waits for its group to start before it reads another batch, so a group has at most one contribution per member. The member then tracks completion through the shared Kafka consumer background-task mechanism. Each member can hold two unfinished batches. The consumer waits for the oldest batch at that limit and stores offsets in batch order. Shared request limits still bound total network concurrency. The background-task timeout is 240 seconds, leaving 60 seconds below the default Kafka poll allowance for joining and scheduling. Shutdown stops all consumer loops and waits for the actual joined processing promises before disconnecting consumers and destroying shared dependencies. This wait includes work that outlives the Kafka consumer drain or background-task timeout. The worker divides a 100 MiB Kafka prefetch budget across its group members, with a minimum of 25 MiB per member. This preserves the queue sizes for one to four members and allows a default maximum-sized record in each queue. Sixteen members have a combined prefetch budget of 400 MiB. During a mixed-version rollout, pods with more group members can receive more partitions until the rollout finishes. `SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH` accepts targets from one to sixteen for worker-count experiments.
Retry jobs use 1-minute, 10-minute, and 1-hour Kafka topics. The topics use broker append timestamps.
@@ -85,7 +85,8 @@ Batch-diversity histograms record the top 1, 5, and 10 URL shares and the invers
Republish batch metrics use the fixed topic classes `frontier`, `retry_1m`, `retry_10m`, and `retry_1h`. They expose Kafka record count, registrable-domain key count, per-topic delivery time, and total republish flush time. They do not use a configured topic name or a domain as a label.
Processing-stage metrics expose the active count, oldest active age, and elapsed time of finished operations, including failures.
-Consumer stages separate the join window from waiting for the combined batch to finish.
+Consumer stages separate the join window from waiting for the combined batch to finish. Their active counts measure outstanding consumer batches, not distinct consumers; overlap can raise the processing count to twice the member count.
+Compare p95 and p99 for image HTTP, configuration HTTP, candidate work, and batch fetch duration separately. Check the oldest active stage age too, because completed-duration histograms exclude unfinished work. Evaluate tighter request timeouts against successful fetch throughput, timeout failures, and deadline republishes.
Batch stages separate parsing, history reads, filtering, fetching, republish preparation, history writes, republish flushes, final accounting, and dead-letter delivery.
Candidate stages separate admission to the pod-wide controller, work that holds a slot, policy checks, and image fetching.
The queued-candidate gauge counts work before selection; it excludes candidates waiting for admission or already running.
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.test.ts
index a9515e429efc..577345344daf 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.test.ts
@@ -31,7 +31,8 @@ describe('ImageFetchBatchJoiner', () => {
afterEach(() => jest.useRealTimers())
it.each([2, 16])('joins batches from %i consumers before processing', async (consumerCount) => {
- const processBatch = jest.fn(() => Promise.resolve())
+ const pass = deferred()
+ const processBatch = jest.fn(() => pass.promise)
const joiner = new ImageFetchBatchJoiner(consumerCount, processBatch)
const messages = Array.from({ length: consumerCount }, (_, partition) => message(partition))
@@ -39,9 +40,18 @@ describe('ImageFetchBatchJoiner', () => {
expect(processBatch).not.toHaveBeenCalled()
pending.push(joiner.handleBatch([messages[consumerCount - 1]]))
- await Promise.all(pending)
+ const batches = await Promise.all(pending)
expect(processBatch).toHaveBeenCalledTimes(1)
expect(processBatch).toHaveBeenCalledWith(messages)
+ expect(batches.every((batch) => batch?.backgroundTask === batches[0]?.backgroundTask)).toBe(true)
+ const completed = jest.fn()
+ const completion = Promise.all(batches.map((batch) => batch?.backgroundTask ?? Promise.resolve())).then(
+ completed
+ )
+ await jest.advanceTimersByTimeAsync(0)
+ expect(completed).not.toHaveBeenCalled()
+ pass.resolve()
+ await completion
})
it.each([2, 16])(
@@ -55,7 +65,9 @@ describe('ImageFetchBatchJoiner', () => {
expect(processBatch).not.toHaveBeenCalled()
await jest.advanceTimersByTimeAsync(1)
- await pending
+ await (
+ await pending
+ )?.backgroundTask
expect(processBatch).toHaveBeenCalledWith([message(0)])
}
)
@@ -67,6 +79,7 @@ describe('ImageFetchBatchJoiner', () => {
const first = joiner.handleBatch([message(0)])
await jest.advanceTimersByTimeAsync(IMAGE_FETCH_BATCH_JOIN_TIMEOUT_MS)
+ const firstCompletion = (await first)?.backgroundTask
const second = joiner.handleBatch([message(1)])
const active = register.getSingleMetric('ml_image_fetch_stage_active')!
expect((await active.get()).values).toEqual(
@@ -75,10 +88,10 @@ describe('ImageFetchBatchJoiner', () => {
expect.objectContaining({ labels: { stage: 'consumer_process' }, value: 1 }),
])
)
+ const rejected = Promise.all([expect(firstCompletion).rejects.toBe(error), expect(second).rejects.toBe(error)])
pass.reject(error)
-
- await expect(first).rejects.toBe(error)
- await expect(second).rejects.toBe(error)
+ await rejected
+ await expect(joiner.handleBatch([message(2)])).rejects.toBe(error)
expect((await active.get()).values).toEqual(
expect.arrayContaining([
expect.objectContaining({ labels: { stage: 'consumer_join' }, value: 0 }),
@@ -103,9 +116,56 @@ describe('ImageFetchBatchJoiner', () => {
expect(processBatch).toHaveBeenCalledTimes(2)
secondPass.resolve()
- await second
+ await (
+ await second
+ )?.backgroundTask
firstPass.resolve()
- await first
+ await (
+ await first
+ )?.backgroundTask
expect(processBatch).toHaveBeenLastCalledWith([message(1)])
})
+
+ it('keeps a fast consumer out of the same group twice while overlapping processing', async () => {
+ const firstPass = deferred()
+ const secondPass = deferred()
+ const processBatch = jest
+ .fn()
+ .mockImplementationOnce(() => firstPass.promise)
+ .mockImplementationOnce(() => secondPass.promise)
+ const joiner = new ImageFetchBatchJoiner(2, processBatch)
+ const secondFromFastConsumer = jest.fn(() => joiner.handleBatch([message(0)]))
+
+ const firstFast = joiner.handleBatch([message(0)])
+ const secondFast = firstFast.then(secondFromFastConsumer)
+ await jest.advanceTimersByTimeAsync(0)
+ expect(secondFromFastConsumer).not.toHaveBeenCalled()
+
+ const firstSlow = joiner.handleBatch([message(1)])
+ await firstSlow
+ await jest.advanceTimersByTimeAsync(0)
+ expect(secondFromFastConsumer).toHaveBeenCalledTimes(1)
+ expect(processBatch).toHaveBeenCalledTimes(1)
+
+ const secondSlow = joiner.handleBatch([message(1)])
+ const secondBatches = await Promise.all([secondFast, secondSlow])
+ expect(processBatch.mock.calls).toEqual([[[message(0), message(1)]], [[message(0), message(1)]]])
+ const active = register.getSingleMetric('ml_image_fetch_stage_active')!
+ expect((await active.get()).values).toEqual(
+ expect.arrayContaining([expect.objectContaining({ labels: { stage: 'consumer_process' }, value: 4 })])
+ )
+
+ secondPass.resolve()
+ await Promise.all(secondBatches.map((batch) => batch?.backgroundTask ?? Promise.resolve()))
+ expect((await active.get()).values).toEqual(
+ expect.arrayContaining([expect.objectContaining({ labels: { stage: 'consumer_process' }, value: 2 })])
+ )
+ firstPass.resolve()
+ await (
+ await firstFast
+ )?.backgroundTask
+ expect((await active.get()).values).toEqual(
+ expect.arrayContaining([expect.objectContaining({ labels: { stage: 'consumer_process' }, value: 0 })])
+ )
+ })
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.ts
index 6b6889dc274c..7da871ec9539 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.ts
@@ -7,8 +7,10 @@ export const MAX_IMAGE_FETCH_BATCHES_PER_PASS = 16
type BatchProcessor = (messages: Message[]) => Promise<void>
+type DispatchedBatch = { backgroundTask: Promise<void> }
+
type BatchWaiter = {
- resolve: () => void
+ resolve: (batch: DispatchedBatch) => void
reject: (error: unknown) => void
timer: ProcessingStageTimer
}
@@ -31,6 +33,7 @@ export function assertImageFetchBatchTarget(targetBatchCount: number): void {
export class ImageFetchBatchJoiner {
private pendingGroup?: PendingBatchGroup
+ private readonly activeProcessing = new Set<Promise<void>>()
private failed = false
private failure: unknown
@@ -41,7 +44,7 @@ export class ImageFetchBatchJoiner {
assertImageFetchBatchTarget(targetBatchCount)
}
- public handleBatch(messages: Message[]): Promise<void> {
+ public handleBatch(messages: Message[]): Promise<DispatchedBatch | void> {
if (messages.length === 0) {
return Promise.resolve()
}
@@ -49,7 +52,7 @@ export class ImageFetchBatchJoiner {
return Promise.reject(this.failure)
}
- return new Promise<void>((resolve, reject) => {
+ return new Promise<DispatchedBatch>((resolve, reject) => {
const group = this.pendingGroup ?? this.createPendingGroup()
group.batches.push(messages)
group.waiters.push({ resolve, reject, timer: ImageFetchProcessingMetrics.start('consumer_join') })
@@ -59,6 +62,10 @@ export class ImageFetchBatchJoiner {
})
}
+ public async waitForProcessing(): Promise<void> {
+ await Promise.allSettled(this.activeProcessing)
+ }
+
private createPendingGroup(): PendingBatchGroup {
const group: PendingBatchGroup = { batches: [], waiters: [] }
group.timeout = setTimeout(() => this.dispatch(group), IMAGE_FETCH_BATCH_JOIN_TIMEOUT_MS)
@@ -89,11 +96,14 @@ export class ImageFetchBatchJoiner {
this.fail(error)
throw error
}
- })().finally(() => group.waiters.forEach(({ timer }) => timer.finish()))
- void processing.then(
- () => group.waiters.forEach(({ resolve }) => resolve()),
- (error) => group.waiters.forEach(({ reject }) => reject(error))
- )
+ })().finally(() => {
+ group.waiters.forEach(({ timer }) => timer.finish())
+ this.activeProcessing.delete(processing)
+ })
+ this.activeProcessing.add(processing)
+ for (const { resolve } of group.waiters) {
+ resolve({ backgroundTask: processing })
+ }
}
private fail(error: unknown): void {
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.test.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.test.ts
index 764316e69a24..66874609b8ea 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.test.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.test.ts
@@ -1,6 +1,10 @@
+import { Message } from 'node-rdkafka'
+
+import { ImageFetchBatchJoiner } from '../ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner'
import {
buildImageFetchConsumerConfigs,
buildImageFetchConsumerOverrides,
+ shutdownImageFetchConsumers,
} from './ingestion-session-replay-ml-image-fetch-server'
import { buildMlMirrorServerConfig } from './ingestion-session-replay-ml-mirror-server'
@@ -16,6 +20,8 @@ describe('image fetch consumer wiring', () => {
const consumerOverrides = buildImageFetchConsumerOverrides(serverConfig, consumerConfigs.length)
expect(consumerConfigs).toHaveLength(expectedConsumers)
+ expect(consumerConfigs.every((config) => config.maxBackgroundTasks === 2)).toBe(true)
+ expect(consumerConfigs.every((config) => config.backgroundTaskTimeoutMs === 240_000)).toBe(true)
expect(consumerConfigs.map((config) => config.groupId)).toEqual(
Array(expectedConsumers).fill(serverConfig.SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID)
)
@@ -30,6 +36,55 @@ describe('image fetch consumer wiring', () => {
)
})
+ it.each([false, true])('waits for joined work before disconnecting and cleaning up (failure=%s)', async (fails) => {
+ jest.useFakeTimers()
+ try {
+ const processBatch = jest.fn(
+ (messages: Message[]) =>
+ new Promise<void>((resolve, reject) => {
+ setTimeout(
+ () => {
+ if (fails && messages[0].offset === 1) {
+ reject(new Error('fetch failed'))
+ } else {
+ resolve()
+ }
+ },
+ messages[0].offset === 1 ? 30_000 : 50_000
+ )
+ })
+ )
+ const joiner = new ImageFetchBatchJoiner(1, processBatch)
+ const completions = await Promise.all(
+ [1, 2].map((offset) =>
+ joiner.handleBatch([
+ { topic: 'test-topic', partition: 0, offset, value: Buffer.from('test'), size: 4 },
+ ])
+ )
+ )
+ const work = Promise.allSettled(completions.map((batch) => batch?.backgroundTask ?? Promise.resolve()))
+ const consumers = [0, 1].map(() => ({
+ stopConsuming: jest.fn(() => new Promise<void>((resolve) => setTimeout(resolve, 20_000))),
+ disconnect: jest.fn().mockResolvedValue(undefined),
+ }))
+ const cleanup = jest.fn()
+ const shutdown = shutdownImageFetchConsumers(consumers, joiner).then(cleanup)
+
+ expect(consumers.every((consumer) => consumer.stopConsuming.mock.calls.length === 1)).toBe(true)
+ await jest.advanceTimersByTimeAsync(30_000)
+ expect(consumers.every((consumer) => consumer.disconnect.mock.calls.length === 0)).toBe(true)
+ expect(cleanup).not.toHaveBeenCalled()
+
+ await jest.advanceTimersByTimeAsync(20_000)
+ await shutdown
+ await work
+ expect(consumers.every((consumer) => consumer.disconnect.mock.calls.length === 1)).toBe(true)
+ expect(cleanup).toHaveBeenCalledTimes(1)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
it.each([0, -1, 1.5, 17, Number.NaN, Number.MAX_SAFE_INTEGER + 1])(
'refuses invalid target partition count %p',
(targetPartitionsPerBatch) => {
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
index 1359209bf175..9de300fbeb6a 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
@@ -163,6 +163,8 @@ export function buildImageFetchConsumerConfigs(
autoCommit: true,
autoOffsetStore: true,
fetchBatchSize: config.SESSION_RECORDING_ML_IMAGE_FETCH_BATCH_SIZE,
+ maxBackgroundTasks: 2,
+ backgroundTaskTimeoutMs: 240_000,
}))
}
@@ -182,6 +184,15 @@ export function buildImageFetchConsumerOverrides(
}
}
+export async function shutdownImageFetchConsumers(
+ consumers: Pick<KafkaConsumerV2, 'stopConsuming' | 'disconnect'>[],
+ batchJoiner: ImageFetchBatchJoiner
+): Promise<void> {
+ await Promise.allSettled(consumers.map((consumer) => consumer.stopConsuming()))
+ await batchJoiner.waitForProcessing()
+ await Promise.allSettled(consumers.map((consumer) => consumer.disconnect()))
+}
+
/**
* The image fetch lane.
*
@@ -288,9 +299,7 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {
this.lifecycle.services.push({
id: 'session-replay-ml-image-fetch',
- onShutdown: async () => {
- await Promise.all(consumers.map((consumer) => consumer.disconnect()))
- },
+ onShutdown: () => shutdownImageFetchConsumers(consumers, batchJoiner),
healthcheck: () => {
for (const consumer of consumers) {
const health = consumer.isHealthy()