: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(session-replay): join image fetch batches across consumers (#89982)
Robbie616c4f0c097c
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.mdindex 784fa64b48cc..f7f0c15bfdfd 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@@ -38,6 +38,8 @@ The queue tracks the remaining request slots from active and waiting jobs. It apThe 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, so each ready member adds a different partition. 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 the existing Kafka prefetch memory budget across its group members. 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 four for worker-count experiments.+Retry jobs use 1-minute, 10-minute, and 1-hour Kafka topics. The topics use broker append timestamps.Each delay consumer waits once for the latest record in its batch. It then republishes the complete batch to the frontier.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.mdindex 3effb040febf..5a10d9ff6803 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md@@ -299,6 +299,8 @@ Removing an eligible entry cannot permit an earlier request.This rule lets later Kafka records add domain and origin diversity when the current pass cannot use enough pod capacity. A job can receive this zero-wait diversity deferral once. A previously deferred job proceeds normally, subject to the pass deadline. This bound prevents a persistent dominant origin or one long run from creating a fast republish cycle without progress.+**5.20** Each worker creates one Kafka group member for each configured target partition. Group assignments do not overlap, so ready group members supply batches from different partitions. The worker joins their batches into one fetch pass. The target must be from one to four and defaults to two. The worker starts the fetch pass when all target batches arrive or the join window ends. If fewer batches arrive, the worker processes the available batches. A later group can run concurrently instead of waiting behind a full pass. Shared request limits still bound total network concurrency. The worker divides the existing Kafka prefetch memory budget across its group members.+### 6. Smokescreen**6.1** Smokescreen is the authoritative network boundary for outbound requests in production. It must refuse a connection to an IP address that is not globally routable.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.tsnew file mode 100644index 000000000000..0c21aec6c1f1--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.test.ts@@ -0,0 +1,89 @@+import { Message } from 'node-rdkafka'++import { IMAGE_FETCH_BATCH_JOIN_TIMEOUT_MS, ImageFetchBatchJoiner } from './image-fetch-batch-joiner'++function message(partition: number): Message {+ return {+ topic: 'session_replay_image_fetch',+ partition,+ offset: 1,+ value: Buffer.from(`partition-${partition}`),+ size: 11,+ }+}++function deferred(): { promise: Promise<void>; resolve: () => void; reject: (error: unknown) => void } {+ let resolve!: () => void+ let reject!: (error: unknown) => void+ const promise = new Promise<void>((done, fail) => {+ resolve = done+ reject = fail+ })+ return { promise, resolve, reject }+}++describe('ImageFetchBatchJoiner', () => {+ beforeEach(() => jest.useFakeTimers())+ afterEach(() => jest.useRealTimers())++ it('joins batches from two consumers before processing', async () => {+ const processBatch = jest.fn(() => Promise.resolve())+ const joiner = new ImageFetchBatchJoiner(2, processBatch)++ const first = joiner.handleBatch([message(0)])+ expect(processBatch).not.toHaveBeenCalled()+ const second = joiner.handleBatch([message(1)])++ await Promise.all([first, second])+ expect(processBatch).toHaveBeenCalledWith([message(0), message(1)])+ })++ it('processes one available batch when the join window ends', async () => {+ const processBatch = jest.fn(() => Promise.resolve())+ const joiner = new ImageFetchBatchJoiner(2, processBatch)++ const pending = joiner.handleBatch([message(0)])+ await jest.advanceTimersByTimeAsync(IMAGE_FETCH_BATCH_JOIN_TIMEOUT_MS - 1)+ expect(processBatch).not.toHaveBeenCalled()+ await jest.advanceTimersByTimeAsync(1)++ await pending+ expect(processBatch).toHaveBeenCalledWith([message(0)])+ })++ it('rejects active and pending consumers when processing fails', async () => {+ const error = new Error('fetch pass failed')+ const pass = deferred()+ const joiner = new ImageFetchBatchJoiner(2, () => pass.promise)++ const first = joiner.handleBatch([message(0)])+ await jest.advanceTimersByTimeAsync(IMAGE_FETCH_BATCH_JOIN_TIMEOUT_MS)+ const second = joiner.handleBatch([message(1)])+ pass.reject(error)++ await expect(first).rejects.toBe(error)+ await expect(second).rejects.toBe(error)+ })++ it('does not hold a later partial batch behind active 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 first = joiner.handleBatch([message(0)])+ await jest.advanceTimersByTimeAsync(IMAGE_FETCH_BATCH_JOIN_TIMEOUT_MS)+ const second = joiner.handleBatch([message(1)])+ await jest.advanceTimersByTimeAsync(IMAGE_FETCH_BATCH_JOIN_TIMEOUT_MS)+ expect(processBatch).toHaveBeenCalledTimes(2)++ secondPass.resolve()+ await second+ firstPass.resolve()+ await first+ expect(processBatch).toHaveBeenLastCalledWith([message(1)])+ })+})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.tsnew file mode 100644index 000000000000..8e8250619d1d--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.ts@@ -0,0 +1,110 @@+import { Message } from 'node-rdkafka'++export const IMAGE_FETCH_BATCH_JOIN_TIMEOUT_MS = 500+export const MAX_IMAGE_FETCH_BATCHES_PER_PASS = 4++type BatchProcessor = (messages: Message[]) => Promise<void>++type BatchWaiter = {+ resolve: () => void+ reject: (error: unknown) => void+}++type PendingBatchGroup = {+ batches: Message[][]+ waiters: BatchWaiter[]+ timeout?: NodeJS.Timeout+}++export function assertImageFetchBatchTarget(targetBatchCount: number): void {+ if (+ !Number.isSafeInteger(targetBatchCount) ||+ targetBatchCount < 1 ||+ targetBatchCount > MAX_IMAGE_FETCH_BATCHES_PER_PASS+ ) {+ throw new Error(`image fetch batch target must be an integer between 1 and ${MAX_IMAGE_FETCH_BATCHES_PER_PASS}`)+ }+}++export class ImageFetchBatchJoiner {+ private pendingGroup?: PendingBatchGroup+ private failed = false+ private failure: unknown++ constructor(+ private readonly targetBatchCount: number,+ private readonly processBatch: BatchProcessor+ ) {+ assertImageFetchBatchTarget(targetBatchCount)+ }++ public handleBatch(messages: Message[]): Promise<void> {+ if (messages.length === 0) {+ return Promise.resolve()+ }+ if (this.failed) {+ return Promise.reject(this.failure)+ }++ return new Promise<void>((resolve, reject) => {+ const group = this.pendingGroup ?? this.createPendingGroup()+ group.batches.push(messages)+ group.waiters.push({ resolve, reject })+ if (group.batches.length >= this.targetBatchCount) {+ this.dispatch(group)+ }+ })+ }++ private createPendingGroup(): PendingBatchGroup {+ const group: PendingBatchGroup = { batches: [], waiters: [] }+ group.timeout = setTimeout(() => this.dispatch(group), IMAGE_FETCH_BATCH_JOIN_TIMEOUT_MS)+ this.pendingGroup = group+ return group+ }++ private dispatch(group: PendingBatchGroup): void {+ if (this.pendingGroup !== group) {+ return+ }+ this.pendingGroup = undefined+ if (group.timeout) {+ clearTimeout(group.timeout)+ }++ const processing = (async () => {+ if (this.failed) {+ throw this.failure+ }+ try {+ await this.processBatch(group.batches.flat())+ } catch (error) {+ this.fail(error)+ throw error+ }+ })()+ void processing.then(+ () => group.waiters.forEach(({ resolve }) => resolve()),+ (error) => group.waiters.forEach(({ reject }) => reject(error))+ )+ }++ private fail(error: unknown): void {+ if (!this.failed) {+ this.failed = true+ this.failure = error+ }++ const pendingGroup = this.pendingGroup+ if (!pendingGroup) {+ return+ }+ this.pendingGroup = undefined+ if (pendingGroup.timeout) {+ clearTimeout(pendingGroup.timeout)+ }+ for (const { reject } of pendingGroup.waiters) {+ reject(this.failure)+ }+ }+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.test.tsindex 93f625f58c03..29d3142a6294 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.test.ts@@ -4,6 +4,7 @@ import { ImageFetchConsumerMetrics, ImageFetchRequestMetrics } from './metrics'describe('image fetch metrics', () => {beforeEach(() => register.resetMetrics())+ afterEach(() => jest.restoreAllMocks())test.each([[undefined, 'network_error'],@@ -76,4 +77,22 @@ describe('image fetch metrics', () => {expect.objectContaining({ metricName: expect.stringMatching(/_sum$/), value: 0.7 }))})++ it('keeps the oldest active batch age when another batch finishes', async () => {+ jest.spyOn(performance, 'now').mockReturnValue(3_000)+ const firstBatchId = ImageFetchConsumerMetrics.startBatch(1_000)+ const secondBatchId = ImageFetchConsumerMetrics.startBatch(2_000)++ ImageFetchConsumerMetrics.finishBatch(secondBatchId)+ const activeMetric = (await register.getMetricsAsJSON()).find(+ (metric) => metric.name === 'ml_image_fetch_consumer_active_batch_elapsed_seconds'+ )+ expect(activeMetric?.values[0].value).toBe(2)++ ImageFetchConsumerMetrics.finishBatch(firstBatchId)+ const idleMetric = (await register.getMetricsAsJSON()).find(+ (metric) => metric.name === 'ml_image_fetch_consumer_active_batch_elapsed_seconds'+ )+ expect(idleMetric?.values[0].value).toBe(0)+ })})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.tsindex d1abd6f6083e..b59d6cc9ef88 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts@@ -110,12 +110,15 @@ export class ImageFetchConsumerMetrics {help: 'Wall time per completed poll batch. Read against Kafka max.poll.interval.ms (300s)',buckets: [0.01, 0.05, 0.1, 0.5, 1, 5, 15, 30, 60, 120, 240, 300, 600],})- private static activeBatchStartedAtMs: number | undefined+ private static readonly activeBatchStartedAtMs = new Map<symbol, number>()private static readonly activeBatchElapsed = new Gauge({name: 'ml_image_fetch_consumer_active_batch_elapsed_seconds',help: 'Elapsed wall time of the active non-empty poll batch, or zero between batches. This exposes a stuck batch before Kafka max.poll.interval.ms revokes it',collect() {- const startedAtMs = ImageFetchConsumerMetrics.activeBatchStartedAtMs+ const startedAtMs =+ ImageFetchConsumerMetrics.activeBatchStartedAtMs.size > 0+ ? Math.min(...ImageFetchConsumerMetrics.activeBatchStartedAtMs.values())+ : undefinedthis.set(startedAtMs === undefined ? 0 : Math.max(0, performance.now() - startedAtMs) / 1000)},})@@ -167,11 +170,13 @@ export class ImageFetchConsumerMetrics {this.observeBatchDistribution('origin', originCounts)this.observeBatchDistribution('registrable_domain', registrableDomainCounts)}- public static startBatch(nowMs = performance.now()): void {- this.activeBatchStartedAtMs = nowMs+ public static startBatch(nowMs = performance.now()): symbol {+ const batchId = Symbol()+ this.activeBatchStartedAtMs.set(batchId, nowMs)+ return batchId}- public static finishBatch(): void {- this.activeBatchStartedAtMs = undefined+ public static finishBatch(batchId: symbol): void {+ this.activeBatchStartedAtMs.delete(batchId)}public static observeRecord(urls: number): void {this.urlsPerRecord.observe(urls)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.tsindex 849bfe4ccead..cc2da24aeba6 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts@@ -61,7 +61,7 @@ export class UrlFetchConsumer {let registrableDomainCount = 0let originCandidateCounts: number[] = []let registrableDomainCandidateCounts: number[] = []- ImageFetchConsumerMetrics.startBatch()+ const activeBatchId = ImageFetchConsumerMetrics.startBatch()try {for (const message of messages) {@@ -163,7 +163,7 @@ export class UrlFetchConsumer {}await this.parkRejectedRecords(rejectedRecords, drops)} finally {- ImageFetchConsumerMetrics.finishBatch()+ ImageFetchConsumerMetrics.finishBatch(activeBatchId)this.recordMetrics(drops,dedupedInBatch,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.tsindex f9f0ca134a4c..76ccab15744d 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts@@ -85,6 +85,8 @@ export type MlMirrorConfig = {SESSION_RECORDING_ML_IMAGE_FETCH_DLQ_TOPIC: stringSESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID: stringSESSION_RECORDING_ML_IMAGE_FETCH_BATCH_SIZE: number+ /** Kafka group members per image-fetch worker. Their batches join into one fetch pass. */+ SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: numberAI_RESEARCH_IMAGE_FETCH_DYNAMODB_TABLE: string/** Bounds one DynamoDB request so an unavailable store cannot hold the poll loop. */AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TIMEOUT_MS: number@@ -234,6 +236,7 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {SESSION_RECORDING_ML_IMAGE_FETCH_DLQ_TOPIC: '',SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID: 'session-replay-ml-image-fetch',SESSION_RECORDING_ML_IMAGE_FETCH_BATCH_SIZE: 500,+ SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 2,AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TABLE: '',AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TIMEOUT_MS: 5_000,AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS: 30 * 24 * 60 * 60,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.tsnew file mode 100644index 000000000000..1a083a870a19--- /dev/null+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.test.ts@@ -0,0 +1,41 @@+import {+ buildImageFetchConsumerConfigs,+ buildImageFetchConsumerOverrides,+} from './ingestion-session-replay-ml-image-fetch-server'+import { buildMlMirrorServerConfig } from './ingestion-session-replay-ml-mirror-server'++describe('image fetch consumer wiring', () => {+ it.each([+ ['the default', {}, 2],+ ['an explicit override', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 4 }, 4],+ ])('creates %s number of Kafka group members', (_name, overrides, expectedConsumers) => {+ const serverConfig = buildMlMirrorServerConfig(overrides)+ const consumerConfigs = buildImageFetchConsumerConfigs(serverConfig)+ const consumerOverrides = buildImageFetchConsumerOverrides(serverConfig, consumerConfigs.length)++ expect(consumerConfigs).toHaveLength(expectedConsumers)+ expect(consumerConfigs.map((config) => config.groupId)).toEqual(+ Array(expectedConsumers).fill(serverConfig.SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID)+ )+ expect(Number(consumerOverrides['queued.max.messages.kbytes']) * expectedConsumers).toBeLessThanOrEqual(102_400)+ expect(Number(consumerOverrides['queued.max.messages.kbytes']) * expectedConsumers).toBeGreaterThanOrEqual(+ 102_400 - expectedConsumers+ )+ expect(Number(consumerOverrides['queued.max.messages.kbytes']) * 1024).toBeGreaterThanOrEqual(+ serverConfig.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES + 64 * 1024+ )+ })++ it.each([0, -1, 1.5, 5, Number.NaN, Number.MAX_SAFE_INTEGER + 1])(+ 'refuses invalid target partition count %p',+ (targetPartitionsPerBatch) => {+ const serverConfig = buildMlMirrorServerConfig({+ SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: targetPartitionsPerBatch,+ })++ expect(() => buildImageFetchConsumerConfigs(serverConfig)).toThrow(+ 'image fetch batch target must be an integer between 1 and 4'+ )+ }+ )+})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.tsindex 5af7568fd420..c41fb2e91760 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@@ -9,7 +9,7 @@ import {KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_10M,KAFKA_SESSION_REPLAY_IMAGE_SCRUB,} from '~/common/config/kafka-topics'-import { KafkaConsumerV2, KafkaConsumerV2Config } from '~/common/kafka/consumer/consumer-v2'+import { KafkaConsumerV2, KafkaConsumerV2Config, RdKafkaConsumerOverrides } from '~/common/kafka/consumer/consumer-v2'import { KafkaProducerWrapper } from '~/common/kafka/producer'import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'import { logger } from '~/common/utils/logger'@@ -23,6 +23,10 @@ import { FetchRunner } from '~/ingestion/pipelines/sessionreplay/ml-mirror-imageimport { KafkaFrontierDeadLetterSink } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-dead-letter-sink'import { FrontierPublisher } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher'import { HostBudget } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget'+import {+ ImageFetchBatchJoiner,+ assertImageFetchBatchTarget,+} from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner'import { HttpImageFetcher } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher'import { OriginRequestScheduler } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/origin-request-scheduler'import { assertUrlPolicyLoaded } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key'@@ -30,6 +34,7 @@ import { UrlFetchConsumer } from '~/ingestion/pipelines/sessionreplay/ml-mirror-import { createWebBotAuthRequestSigner } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/web-bot-auth'import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'import { INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER } from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'+import { HealthCheckResultOk } from '~/types'import { CleanupResources, NodeServer, ServerLifecycle } from './base-server'import {@@ -45,6 +50,7 @@ import {* mid-batch to a pod that will be just as slow, so the lane sheds the rest of the batch instead.*/const STORE_BATCH_BUDGET_MS = 50_000+const IMAGE_FETCH_KAFKA_QUEUE_BUDGET_KBYTES = 102_400/** Matches MAX_URL_LEN in the crate, which is what the collector applied to the first candidate. */const MAX_REDIRECT_URL_LENGTH = 2048@@ -141,15 +147,30 @@ export function buildFetchRunner()}-export function buildImageFetchConsumerConfig(+export function buildImageFetchConsumerConfigs(config: IngestionSessionReplayMlMirrorServerConfig-): KafkaConsumerV2Config {- return {+): KafkaConsumerV2Config[] {+ const targetBatchCount = config.SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH+ assertImageFetchBatchTarget(targetBatchCount)+ return Array.from({ length: targetBatchCount }, () => ({topic: KAFKA_SESSION_REPLAY_IMAGE_FETCH,groupId: config.SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID,autoCommit: true,autoOffsetStore: true,fetchBatchSize: config.SESSION_RECORDING_ML_IMAGE_FETCH_BATCH_SIZE,+ }))+}++export function buildImageFetchConsumerOverrides(+ config: IngestionSessionReplayMlMirrorServerConfig,+ consumerCount: number+): RdKafkaConsumerOverrides {+ assertImageFetchBatchTarget(consumerCount)+ const maximumRecordBytes = config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES + 64 * 1024+ return {+ 'fetch.message.max.bytes': maximumRecordBytes,+ 'max.partition.fetch.bytes': maximumRecordBytes,+ 'queued.max.messages.kbytes': Math.floor(IMAGE_FETCH_KAFKA_QUEUE_BUDGET_KBYTES / consumerCount),}}@@ -239,18 +260,33 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {)logger.info('🌐', 'ml_image_fetch_started', { dryRun })- const maximumRecordBytes = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES + 64 * 1024- const consumer = new KafkaConsumerV2(buildImageFetchConsumerConfig(this.config), {- 'fetch.message.max.bytes': maximumRecordBytes,- 'max.partition.fetch.bytes': maximumRecordBytes,- })- await consumer.connect((messages) => fetchConsumer.handleBatch(messages, Date.now()))+ const consumerConfigs = buildImageFetchConsumerConfigs(this.config)+ const batchJoiner = new ImageFetchBatchJoiner(consumerConfigs.length, (messages) =>+ fetchConsumer.handleBatch(messages, Date.now())+ )+ const consumerOverrides = buildImageFetchConsumerOverrides(this.config, consumerConfigs.length)+ const consumers = consumerConfigs.map(+ (consumerConfig) => new KafkaConsumerV2(consumerConfig, consumerOverrides)+ )this.lifecycle.services.push({id: 'session-replay-ml-image-fetch',- onShutdown: () => consumer.disconnect(),- healthcheck: () => consumer.isHealthy(),+ onShutdown: async () => {+ await Promise.all(consumers.map((consumer) => consumer.disconnect()))+ },+ healthcheck: () => {+ for (const consumer of consumers) {+ const health = consumer.isHealthy()+ if (health.isError()) {+ return health+ }+ }+ return new HealthCheckResultOk()+ },})+ await Promise.all(+ consumers.map((consumer) => consumer.connect((messages) => batchJoiner.handleBatch(messages)))+ )}private getCleanupResources(): CleanupResources {