: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
perf(ai-research): write image shards behind the next batch's scrub (#103693)
Robbied443424ae3b0
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.mdindex 1e003ee473ad..bc40adcb1744 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md@@ -22,7 +22,8 @@ Lag grows while that happens, which is correct and is what the drain-time panelsBecause the batch has no time limit, its duration is set by how many images it holds, so this lane runs a small `CONSUMER_BATCH_SIZE` (50, against a default of 500).A batch that outlives `max.poll.interval.ms` (300s) gets the pod evicted mid-batch, and that is not a clean retry: the evicted pod loses the offsets for work it already did, and the partition lands on a pod whose sidecar is equally busy and redoes the same images, so offered load rises while throughput falls.Keeping batches far inside the interval is what stops ordinary saturation reaching that point.-If a revoke does land mid-batch, the batch stops as soon as a flush finds it no longer owns the partitions, rather than scrubbing on and writing a second shard for a span the new owner is already writing.+If a revoke does land mid-batch, the batch stops as soon as a write finds it no longer owns the partitions, rather than scrubbing on and writing a second shard for a span the new owner is already writing.+The S3 writes of a batch run behind the scrub of the next batch, so the batch duration the consumer reports covers the scrub only; `ml_mirror_image_scrub_consumer_write_duration_seconds` covers the writes.A wedged sidecar still blocks its partitions rather than draining them, and no batch size prevents that.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.tsindex 058412cd3966..20bd78e58a8c 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts@@ -7,7 +7,7 @@ import { INGESTION_VERSION_HEADER } from '~/ingestion/pipelines/sessionreplay/mlimport { MlKafkaTransport } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport'import { hashImageBytes, imageRef, urlRef } from './content-ref'-import { ImageBatcher, OffsetStore } from './image-batcher'+import { ImageBatcher, OffsetStore, WRITE_CONCURRENCY } from './image-batcher'import { ImageShardStore, ScrubbedImage, ScrubbedUrlImage, UrlImageWriteOutcome } from './image-shard-store'import { CAPTURE_TIMESTAMP_HEADER } from './image-transport'import { ImageScrubConsumerMetrics } from './metrics'@@ -75,13 +75,18 @@ const scrubClient = {} as unknown as ScrubClientconst options = {- flushIntervalMs: 0,maxImages: 1000,maxBytes: 1e9,scrubConcurrency: 4,dedupMaxRefs: 1000,}+/** Runs a batch and waits for its writes, for tests that assert on what reached the store. */+async function handleAndWrite(batcher: ImageBatcher, messages: Message[]): Promise<void> {+ await batcher.handleBatch(messages)+ await batcher.drain()+}+describe('ImageBatcher', () => {afterEach(() => jest.restoreAllMocks())@@ -104,14 +109,13 @@ describe('ImageBatcher', () => {offsets,scrubClient,options,- 0,{ park },keyManager)const invalid = msg(0, 0, pt(1), Buffer.from('invalid envelope'), undefined, [{ [INGESTION_VERSION_HEADER]: Buffer.from('2') },])- const batch = batcher.handleBatch([invalid], 1)+ const batch = batcher.handleBatch([invalid])await jest.advanceTimersByTimeAsync(0)expect(park).toHaveBeenCalledTimes(1)expect(offsets.received).toEqual([])@@ -121,7 +125,7 @@ describe('ImageBatcher', () => {['1', 0],])if (stop) {- batcher.stop()+ await batcher.stop()} else {await jest.advanceTimersByTimeAsync(500)}@@ -152,16 +156,13 @@ describe('ImageBatcher', () => {const store = new FakeStore()const offsets = new FakeOffsets()const observeCaptureToS3 = jest.spyOn(ImageScrubConsumerMetrics, 'observeCaptureToS3').mockImplementation()- const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, scrubClient, options, 0)+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, scrubClient, options)const captureHeader = [{ [CAPTURE_TIMESTAMP_HEADER]: Buffer.from(String(CAPTURED_AT)) }]- await batcher.handleBatch(- [- msg(0, 0, pt(1), Buffer.from('a'), undefined, captureHeader),- msg(0, 1, mixed ? '42' : pt(2), Buffer.from('b'), undefined, captureHeader),- ],- 1- )+ await handleAndWrite(batcher, [+ msg(0, 0, pt(1), Buffer.from('a'), undefined, captureHeader),+ msg(0, 1, mixed ? '42' : pt(2), Buffer.from('b'), undefined, captureHeader),+ ])expect(store.writes).toHaveLength(mixed ? 2 : 1)expect(@@ -184,16 +185,10 @@ describe('ImageBatcher', () => {// The hash is a producer-side per-team HMAC; this consumer has no key and must not try to// validate — it indexes the scrubbed bytes under whatever hash the ref carries.const store = new FakeStore()- const batcher = new ImageBatcher(- store as unknown as ImageShardStore,- new FakeOffsets(),- scrubClient,- options,- 0- )+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, new FakeOffsets(), scrubClient, options)const ref = imageRef(pt(1), hashImageBytes('some-opaque-producer-key', Buffer.from('a')))- await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'), ref)], 1)+ await handleAndWrite(batcher, [msg(0, 0, pt(1), Buffer.from('a'), ref)])expect(store.writes).toHaveLength(1)expect(store.writes[0][0].hash).toBe(ref.split(':')[2])@@ -205,11 +200,10 @@ describe('ImageBatcher', () => {new FakeStore() as unknown as ImageShardStore,new FakeOffsets(),scrubClient,- options,- 0+ options)- await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))], 1)+ await handleAndWrite(batcher, [msg(0, 0, pt(1), Buffer.from('a'))])expect(incrementVersion.mock.calls).toEqual([['2', 0],@@ -232,21 +226,17 @@ describe('ImageBatcher', () => {store as unknown as ImageShardStore,new FakeOffsets(),capturingClient,- options,- 0+ options)const ref = urlRef(hashImageBytes(CONTENT_KEY, Buffer.from('https://example.com/image.png')))- await batcher.handleBatch(- [- msg(0, 0, pt(1), gzipSync(png), ref, [- { 'content-type': Buffer.from('image/png') },- { 'content-encoding': Buffer.from('gzip') },- { [CAPTURE_TIMESTAMP_HEADER]: Buffer.from(String(CAPTURED_AT)) },- ]),- ],- 1- )+ await handleAndWrite(batcher, [+ msg(0, 0, pt(1), gzipSync(png), ref, [+ { 'content-type': Buffer.from('image/png') },+ { 'content-encoding': Buffer.from('gzip') },+ { [CAPTURE_TIMESTAMP_HEADER]: Buffer.from(String(CAPTURED_AT)) },+ ]),+ ])expect(received).toEqual([png])expect(store.urlWrites).toEqual([@@ -270,20 +260,16 @@ describe('ImageBatcher', () => {store as unknown as ImageShardStore,new FakeOffsets(),{ scrub: (bytes: Buffer) => Promise.resolve(bytes) } as unknown as ScrubClient,- options,- 0+ options)const ref = urlRef(hashImageBytes(CONTENT_KEY, Buffer.from('https://example.com/image.png')))- await batcher.handleBatch(- [- msg(0, 0, pt(1), png, ref, [- { 'content-type': Buffer.from('image/png') },- { [CAPTURE_TIMESTAMP_HEADER]: Buffer.from(String(CAPTURED_AT)) },- ]),- ],- 1- )+ await handleAndWrite(batcher, [+ msg(0, 0, pt(1), png, ref, [+ { 'content-type': Buffer.from('image/png') },+ { [CAPTURE_TIMESTAMP_HEADER]: Buffer.from(String(CAPTURED_AT)) },+ ]),+ ])expect(store.urlWrites).toHaveLength(1)expect(observeCaptureToS3).not.toHaveBeenCalled()@@ -298,18 +284,14 @@ describe('ImageBatcher', () => {store as unknown as ImageShardStore,new FakeOffsets(),{ scrub: (bytes: Buffer) => Promise.resolve(bytes) } as unknown as ScrubClient,- options,- 0+ options)const ref = urlRef(hashImageBytes(CONTENT_KEY, Buffer.from('https://example.com/image.png')))- await batcher.handleBatch(- [- msg(0, 12, pt(1), newer, ref, [{ 'content-type': Buffer.from('image/png') }]),- msg(0, 10, pt(1), older, ref, [{ 'content-type': Buffer.from('image/png') }]),- ],- 1- )+ await handleAndWrite(batcher, [+ msg(0, 12, pt(1), newer, ref, [{ 'content-type': Buffer.from('image/png') }]),+ msg(0, 10, pt(1), older, ref, [{ 'content-type': Buffer.from('image/png') }]),+ ])expect(store.urlWrites).toEqual([{@@ -334,18 +316,14 @@ describe('ImageBatcher', () => {store as unknown as ImageShardStore,new FakeOffsets(),{ scrub: (bytes: Buffer) => Promise.resolve(bytes) } as unknown as ScrubClient,- options,- 0+ options)const ref = urlRef(hashImageBytes(CONTENT_KEY, Buffer.from('https://example.com/image.png')))- await batcher.handleBatch(- [- msg(0, 10, pt(1), Buffer.from('not a png'), ref, [{ 'content-type': Buffer.from('image/png') }]),- msg(0, 11, pt(1), png, ref, [{ 'content-type': Buffer.from('image/png') }]),- ],- 1- )+ await handleAndWrite(batcher, [+ msg(0, 10, pt(1), Buffer.from('not a png'), ref, [{ 'content-type': Buffer.from('image/png') }]),+ msg(0, 11, pt(1), png, ref, [{ 'content-type': Buffer.from('image/png') }]),+ ])expect(store.urlWrites).toEqual([{@@ -366,13 +344,12 @@ describe('ImageBatcher', () => {store as unknown as ImageShardStore,new FakeOffsets(),{ scrub: (bytes: Buffer) => Promise.resolve(bytes) } as unknown as ScrubClient,- options,- 0+ options)const ref = urlRef(hashImageBytes(CONTENT_KEY, Buffer.from('https://example.com/image.png')))- await batcher.handleBatch([msg(0, 10, pt(1), first, ref, [{ 'content-type': Buffer.from('image/png') }])], 1)- await batcher.handleBatch([msg(0, 11, pt(1), second, ref, [{ 'content-type': Buffer.from('image/png') }])], 2)+ await handleAndWrite(batcher, [msg(0, 10, pt(1), first, ref, [{ 'content-type': Buffer.from('image/png') }])])+ await handleAndWrite(batcher, [msg(0, 11, pt(1), second, ref, [{ 'content-type': Buffer.from('image/png') }])])expect(store.urlWrites.map((image) => [image.sourceOffset, image.bytes])).toEqual([[10, first],@@ -380,7 +357,9 @@ describe('ImageBatcher', () => {])})- it('bounds concurrent URL-image writes by the scrub worker limit', async () => {+ it('bounds concurrent URL-image writes by the write concurrency, not the scrub slots', async () => {+ // The writes run behind the next batch's scrub, so sharing the scrub slots would let a write+ // burst take the sidecar's work away from it. The bound is the write lane's own.const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])let activeWrites = 0let maximumActiveWrites = 0@@ -397,17 +376,16 @@ describe('ImageBatcher', () => {store,new FakeOffsets(),{ scrub: () => Promise.resolve(png) } as unknown as ScrubClient,- { ...options, scrubConcurrency: 2 },- 0+ { ...options, scrubConcurrency: 2 })- const messages = Array.from({ length: 6 }, (_, index) => {+ const messages = Array.from({ length: WRITE_CONCURRENCY + 2 }, (_, index) => {const ref = urlRef(hashImageBytes(CONTENT_KEY, Buffer.from(`https://example.com/${index}.png`)))return msg(0, index, pt(1), png, ref, [{ 'content-type': Buffer.from('image/png') }])})- await batcher.handleBatch(messages, 1)+ await handleAndWrite(batcher, messages)- expect(maximumActiveWrites).toBe(2)+ expect(maximumActiveWrites).toBe(WRITE_CONCURRENCY)})it('drops a URL image whose bytes do not match its Kafka content-type', async () => {@@ -422,37 +400,42 @@ describe('ImageBatcher', () => {return Promise.resolve(Buffer.from('scrubbed'))},} as unknown as ScrubClient,- options,- 0+ options)const ref = urlRef(hashImageBytes(CONTENT_KEY, Buffer.from('https://example.com/image.png')))- await batcher.handleBatch(- [msg(0, 0, pt(1), Buffer.from([0xff, 0xd8, 0xff]), ref, [{ 'content-type': Buffer.from('image/png') }])],- 1- )+ await handleAndWrite(batcher, [+ msg(0, 0, pt(1), Buffer.from([0xff, 0xd8, 0xff]), ref, [{ 'content-type': Buffer.from('image/png') }]),+ ])expect(scrubCalls).toBe(0)expect(incSkipped).toHaveBeenCalledWith('content_type_mismatch')})- it('does not store offsets when the shard write fails (at-least-once replay)', async () => {+ it('does not store offsets when the shard write fails, and fails the next batch so the pod replays', async () => {+ // The write runs behind the next batch, so the batch that scrubbed the image has already+ // returned when S3 refuses it. The lane is poisoned instead: nothing behind the failed write+ // stores an offset, and the next batch raises the failure, which is what exits the process.const store = new FakeStore()store.failNext = trueconst offsets = new FakeOffsets()const observeCaptureToS3 = jest.spyOn(ImageScrubConsumerMetrics, 'observeCaptureToS3').mockImplementation()- const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, scrubClient, options, 0)+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, scrubClient, options)- await expect(- batcher.handleBatch(- [- msg(0, 0, pt(1), Buffer.from('a'), undefined, [- { [CAPTURE_TIMESTAMP_HEADER]: Buffer.from(String(CAPTURED_AT)) },- ]),- ],- 1- )- ).rejects.toThrow('s3 down')+ await batcher.handleBatch([+ msg(0, 0, pt(1), Buffer.from('a'), undefined, [+ { [CAPTURE_TIMESTAMP_HEADER]: Buffer.from(String(CAPTURED_AT)) },+ ]),+ ])+ // The failed write has settled and left the in-flight list before anyone drains.+ for (let tick = 0; tick < 20; tick++) {+ await new Promise((resolve) => setImmediate(resolve))+ }+ await expect(batcher.drain()).rejects.toThrow('s3 down')++ store.failNext = false+ await expect(batcher.handleBatch([msg(0, 1, pt(1), Buffer.from('b'))])).rejects.toThrow('s3 down')+ expect(store.writes).toHaveLength(0)expect(offsets.stored).toBe(0)expect(observeCaptureToS3).not.toHaveBeenCalled()})@@ -461,27 +444,23 @@ describe('ImageBatcher', () => {const store = new FakeStore()store.failNextUrl = trueconst offsets = new FakeOffsets()- const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, scrubClient, options, 0)+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, scrubClient, options)const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])const ref = urlRef(hashImageBytes(CONTENT_KEY, Buffer.from('https://example.com/image.png')))- await expect(- batcher.handleBatch(- [- msg(0, 0, pt(1), Buffer.from('inline')),- msg(0, 1, pt(1), png, ref, [{ 'content-type': Buffer.from('image/png') }]),- ],- 1- )- ).rejects.toThrow('url s3 down')+ await batcher.handleBatch([+ msg(0, 0, pt(1), Buffer.from('inline')),+ msg(0, 1, pt(1), png, ref, [{ 'content-type': Buffer.from('image/png') }]),+ ])+ await expect(batcher.drain()).rejects.toThrow('url s3 down')expect(store.writes).toHaveLength(0)expect(offsets.stored).toBe(0)})- it('stores offsets with each mid-batch flush, so a later failure replays only from the flush', async () => {- // A flush persists a randomly named shard; if the batch then fails (e.g. the scrub deadline)- // without having stored the flushed messages' offsets, Kafka replays them and every replay+ it('stores offsets with each mid-batch hand-off, so a later failure replays only from there', async () => {+ // A hand-off persists a randomly named shard; if the batch then fails (e.g. the scrub deadline)+ // without having stored those messages' offsets, Kafka replays them and every replay// writes another duplicate shard — unbounded write amplification an attacker can induce.const store = new FakeStore()const offsets = new FakeOffsets()@@ -492,48 +471,45 @@ describe('ImageBatcher', () => {return scrubs <= 2 ? Promise.resolve(Buffer.alloc(16)) : Promise.reject(new Error('sidecar down'))},} as unknown as ScrubClient- const batcher = new ImageBatcher(- store as unknown as ImageShardStore,- offsets,- failsAfterFirstChunk,- { ...options, maxBytes: 32, scrubConcurrency: 2 },- 0- )+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, failsAfterFirstChunk, {+ ...options,+ maxBytes: 32,+ scrubConcurrency: 2,+ })const messages = Array.from({ length: 4 }, (_, i) => msg(0, i, pt(1), Buffer.from(`img-${i}`)))- await expect(batcher.handleBatch(messages, 1)).rejects.toThrow('sidecar down')+ await expect(batcher.handleBatch(messages)).rejects.toThrow('sidecar down')+ await batcher.drain()expect(store.writes).toHaveLength(1)- // The flushed chunk's messages (offsets 0-1) are recorded, so only 2-3 replay.+ // The handed-off chunk's messages (offsets 0-1) are recorded, so only 2-3 replay.expect(offsets.received).toEqual([[{ topic: 'session_replay_image_scrub', partition: 0, offset: 2 }]])})- it('flushes mid-batch when scrubbed bytes cross the byte bound instead of holding the whole batch', async () => {+ it('hands off mid-batch when scrubbed bytes cross the byte bound instead of holding the whole batch', async () => {// Scrubbed outputs can be far larger than their inputs (full-resolution PNG re-encode), so// the byte bound must apply while a poll batch is still scrubbing — a reverted batcher that- // accumulates all outputs first can hold gigabytes before its first flush.+ // accumulates all outputs first can hold gigabytes before its first hand-off.const store = new FakeStore()const offsets = new FakeOffsets()const bigOutputClient = { scrub: () => Promise.resolve(Buffer.alloc(16)) } as unknown as ScrubClient- const batcher = new ImageBatcher(- store as unknown as ImageShardStore,- offsets,- bigOutputClient,- { ...options, maxBytes: 32, scrubConcurrency: 2 },- 0- )+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, bigOutputClient, {+ ...options,+ maxBytes: 32,+ scrubConcurrency: 2,+ })const messages = Array.from({ length: 6 }, (_, i) => msg(0, i, pt(1), Buffer.from(`img-${i}`)))- await batcher.handleBatch(messages, 1)+ await handleAndWrite(batcher, messages)expect(store.writes.length).toBeGreaterThan(1)expect(store.writes.flat()).toHaveLength(6)expect(offsets.stored).toBe(store.writes.length)})- it('does not count mid-batch flush time against the scrub deadline', async () => {+ it('does not count write time against the scrub deadline', async () => {// Slow-but-succeeding S3 writes must not exhaust the scrub budget: a reverted deadline that- // spans flushes turns degraded storage into an abort/replay loop blamed on the sidecar.+ // spans the writes turns degraded storage into an abort/replay loop blamed on the sidecar.const slowStore = new FakeStore()const writeShard = slowStore.writeShard.bind(slowStore)slowStore.writeShard = async (images) => {@@ -545,12 +521,11 @@ describe('ImageBatcher', () => {slowStore as unknown as ImageShardStore,offsets,{ scrub: () => Promise.resolve(Buffer.alloc(16)) } as unknown as ScrubClient,- { ...options, maxBytes: 32, scrubConcurrency: 2 },- 0+ { ...options, maxBytes: 32, scrubConcurrency: 2 })const messages = Array.from({ length: 6 }, (_, i) => msg(0, i, pt(1), Buffer.from(`img-${i}`)))- await batcher.handleBatch(messages, 1)+ await handleAndWrite(batcher, messages)expect(slowStore.writes.flat()).toHaveLength(6)expect(offsets.stored).toBe(slowStore.writes.length)@@ -569,11 +544,11 @@ describe('ImageBatcher', () => {return Promise.resolve(b)},} as unknown as ScrubClient- const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, countingClient, options, 0)+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, countingClient, options)const sprite = Buffer.from('sprite')- await batcher.handleBatch([msg(0, 0, pt(1), sprite), msg(0, 1, pt(1), sprite)], 1)- await batcher.handleBatch([msg(0, 2, pt(1), sprite)], 2)+ await handleAndWrite(batcher, [msg(0, 0, pt(1), sprite), msg(0, 1, pt(1), sprite)])+ await handleAndWrite(batcher, [msg(0, 2, pt(1), sprite)])expect(scrubs).toBe(1)expect(store.writes.flat()).toHaveLength(1)@@ -603,13 +578,10 @@ describe('ImageBatcher', () => {return b},} as unknown as ScrubClient- const batcher = new ImageBatcher(- store as unknown as ImageShardStore,- new FakeOffsets(),- trackingClient,- { ...options, dedupMaxRefs },- 0- )+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, new FakeOffsets(), trackingClient, {+ ...options,+ dedupMaxRefs,+ })const batch: Message[] = []for (let sprite = 0; sprite < 4; sprite++) {@@ -617,7 +589,7 @@ describe('ImageBatcher', () => {batch.push(msg(0, batch.length, pt(1), Buffer.from(`sprite-${sprite}`)))}}- await batcher.handleBatch(batch, 1)+ await handleAndWrite(batcher, batch)expect(scrubs).toBe(4)expect(maxInFlight).toBe(4)@@ -641,19 +613,13 @@ describe('ImageBatcher', () => {return b.toString() === 'slow' ? slow.then(() => b) : Promise.resolve(b)},} as unknown as ScrubClient- const batcher = new ImageBatcher(- store as unknown as ImageShardStore,- new FakeOffsets(),- gatedClient,- options,- 0- )+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, new FakeOffsets(), gatedClient, options)const batch: Message[] = [msg(0, 0, pt(1), Buffer.from('slow'))]for (let i = 1; i < 8; i++) {batch.push(msg(0, i, pt(1), Buffer.from(`img-${i}`)))}- const running = batcher.handleBatch(batch, 1)+ const running = batcher.handleBatch(batch)for (let tick = 0; tick < 20; tick++) {await new Promise((resolve) => setImmediate(resolve))}@@ -679,19 +645,17 @@ describe('ImageBatcher', () => {const gatedClient = {scrub: (b: Buffer) => (b.toString() === 'slow' ? slow.then(() => b) : Promise.resolve(b)),} as unknown as ScrubClient- const batcher = new ImageBatcher(- store as unknown as ImageShardStore,- offsets,- gatedClient,- { ...options, maxImages: 2, scrubConcurrency: 4 },- 0- )+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, gatedClient, {+ ...options,+ maxImages: 2,+ scrubConcurrency: 4,+ })const batch: Message[] = [msg(0, 0, pt(1), Buffer.from('slow'))]for (let i = 1; i < 5; i++) {batch.push(msg(0, i, pt(1), Buffer.from(`img-${i}`)))}- const running = batcher.handleBatch(batch, 1)+ const running = batcher.handleBatch(batch)for (let tick = 0; tick < 20; tick++) {await new Promise((resolve) => setImmediate(resolve))}@@ -702,6 +666,7 @@ describe('ImageBatcher', () => {releaseSlow()await running+ await batcher.drain()expect(store.writes.flat()).toHaveLength(5)expect(offsets.received.at(-1)).toEqual([{ topic: 'session_replay_image_scrub', partition: 0, offset: 5 }])@@ -720,17 +685,11 @@ describe('ImageBatcher', () => {},} as unknown as ScrubClientconst store = new FakeStore()- const batcher = new ImageBatcher(- store as unknown as ImageShardStore,- new FakeOffsets(),- flakyClient,- options,- 0- )+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, new FakeOffsets(), flakyClient, options)const sprite = Buffer.from('sprite')- await expect(batcher.handleBatch([msg(0, 0, pt(1), sprite)], 1)).rejects.toThrow('sidecar down')- await batcher.handleBatch([msg(0, 0, pt(1), sprite)], 2)+ await expect(batcher.handleBatch([msg(0, 0, pt(1), sprite)])).rejects.toThrow('sidecar down')+ await handleAndWrite(batcher, [msg(0, 0, pt(1), sprite)])expect(store.writes.flat()).toHaveLength(1)})@@ -740,20 +699,16 @@ describe('ImageBatcher', () => {// and that failure is silent permanent loss. Both partitions here end on a duplicate, so the// trailing skips are only covered if the final recordOffsets spans the whole batch.const offsets = new FakeOffsets()- const batcher = new ImageBatcher(- new FakeStore() as unknown as ImageShardStore,- offsets,- scrubClient,- options,- 0- )+ const batcher = new ImageBatcher(new FakeStore() as unknown as ImageShardStore, offsets, scrubClient, options)const a = Buffer.from('a')const b = Buffer.from('b')- await batcher.handleBatch(- [msg(0, 100, pt(1), a), msg(1, 200, pt(1), b), msg(0, 101, pt(1), a), msg(1, 201, pt(1), b)],- 1- )+ await handleAndWrite(batcher, [+ msg(0, 100, pt(1), a),+ msg(1, 200, pt(1), b),+ msg(0, 101, pt(1), a),+ msg(1, 201, pt(1), b),+ ])expect(offsets.received.at(-1)).toEqual(expect.arrayContaining([@@ -763,8 +718,8 @@ describe('ImageBatcher', () => {)})- it('leaves both partitions replayable when a chunk fails after a mid-batch flush', async () => {- // A mid-batch flush commits offsets for the prefix it persisted, and everything after it has+ it('leaves both partitions replayable when a chunk fails after a mid-batch hand-off', async () => {+ // A mid-batch hand-off commits offsets for the prefix it persisted, and everything after it has// to stay replayable. Multi-partition is where that can quietly go wrong, because each// partition carries its own maximum and only one of them appears in a given chunk's span.const store = new FakeStore()@@ -776,25 +731,21 @@ describe('ImageBatcher', () => {return scrubs > 2 ? Promise.reject(new Error('sidecar down')) : Promise.resolve(b)},} as unknown as ScrubClient- const batcher = new ImageBatcher(- store as unknown as ImageShardStore,- offsets,- failLateClient,- { ...options, maxImages: 2, scrubConcurrency: 2 },- 0- )+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, failLateClient, {+ ...options,+ maxImages: 2,+ scrubConcurrency: 2,+ })await expect(- batcher.handleBatch(- [- msg(0, 10, pt(1), Buffer.from('a')),- msg(1, 20, pt(1), Buffer.from('b')),- msg(0, 11, pt(1), Buffer.from('c')),- msg(1, 21, pt(1), Buffer.from('d')),- ],- 1- )+ batcher.handleBatch([+ msg(0, 10, pt(1), Buffer.from('a')),+ msg(1, 20, pt(1), Buffer.from('b')),+ msg(0, 11, pt(1), Buffer.from('c')),+ msg(1, 21, pt(1), Buffer.from('d')),+ ])).rejects.toThrow('sidecar down')+ await batcher.drain()expect(offsets.received).toHaveLength(1)expect(offsets.received[0]).toHaveLength(2)@@ -820,14 +771,13 @@ describe('ImageBatcher', () => {new FakeStore() as unknown as ImageShardStore,new FakeOffsets(),rejectingClient,- options,- 0+ options)const broken = Buffer.from('broken')const incSkipped = jest.spyOn(ImageScrubConsumerMetrics, 'incSkipped')- await batcher.handleBatch([msg(0, 0, pt(1), broken)], 1)- await batcher.handleBatch([msg(0, 1, pt(1), broken)], 2)+ await handleAndWrite(batcher, [msg(0, 0, pt(1), broken)])+ await handleAndWrite(batcher, [msg(0, 1, pt(1), broken)])expect(calls).toBe(1)expect(incSkipped).toHaveBeenCalledWith('sidecar_rejected')@@ -835,21 +785,18 @@ describe('ImageBatcher', () => {it('dedupMaxRefs 0 disables the cross-batch cache but never intra-batch dedup', async () => {const store = new FakeStore()- const batcher = new ImageBatcher(- store as unknown as ImageShardStore,- new FakeOffsets(),- scrubClient,- { ...options, dedupMaxRefs: 0 },- 0- )+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, new FakeOffsets(), scrubClient, {+ ...options,+ dedupMaxRefs: 0,+ })const sprite = Buffer.from('sprite')- await batcher.handleBatch([msg(0, 0, pt(1), sprite)], 1)- await batcher.handleBatch([msg(0, 1, pt(1), sprite)], 2)+ await handleAndWrite(batcher, [msg(0, 0, pt(1), sprite)])+ await handleAndWrite(batcher, [msg(0, 1, pt(1), sprite)])expect(store.writes.flat()).toHaveLength(2)// Intra-batch dedup keeps no state between batches, so turning the cache off cannot reach it.- await batcher.handleBatch([msg(0, 2, pt(1), sprite), msg(0, 3, pt(1), sprite)], 3)+ await handleAndWrite(batcher, [msg(0, 2, pt(1), sprite), msg(0, 3, pt(1), sprite)])expect(store.writes.flat()).toHaveLength(3)})@@ -858,13 +805,10 @@ describe('ImageBatcher', () => {// silently dropping the whole batch — both must fail loudly at boot instead.expect(() =>- new ImageBatcher(- new FakeStore() as unknown as ImageShardStore,- new FakeOffsets(),- scrubClient,- { ...options, scrubConcurrency },- 0- )+ new ImageBatcher(new FakeStore() as unknown as ImageShardStore, new FakeOffsets(), scrubClient, {+ ...options,+ scrubConcurrency,+ })).toThrow('scrubConcurrency')})@@ -887,11 +831,11 @@ describe('ImageBatcher', () => {): Promise.resolve(b),} as unknown as ScrubClient- const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, poisonClient, options, 0, {+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, poisonClient, options, {park: (image) => Promise.resolve(void parked.push(image.ref)),})- await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('poison')), msg(0, 1, pt(1), Buffer.from('ok'))], 1)+ await handleAndWrite(batcher, [msg(0, 0, pt(1), Buffer.from('poison')), msg(0, 1, pt(1), Buffer.from('ok'))])expect(parked).toHaveLength(1)// The healthy image behind it still gets written, and the offset advances over both.@@ -922,13 +866,12 @@ describe('ImageBatcher', () => {new FakeOffsets(),poisonClient,options,- 0,{ park: (image) => Promise.resolve(void parked.push(image.detail)) })const replayed = msg(0, 0, pt(1), Buffer.from('poison'));(replayed as unknown as { headers: unknown[] }).headers = [{ replayCount: Buffer.from('1') }]- await batcher.handleBatch([replayed], 1)+ await handleAndWrite(batcher, [replayed])expect(parked[0].replayCount).toBe(1)})@@ -953,7 +896,6 @@ describe('ImageBatcher', () => {new FakeOffsets(),poisonClient,options,- 0,{park: (image) => Promise.resolve(void parked.push({ headers: image.headers, bytes: image.bytes })),}@@ -962,16 +904,13 @@ describe('ImageBatcher', () => {const compressed = gzipSync(png)const ref = urlRef(hashImageBytes(CONTENT_KEY, Buffer.from('https://example.com/poison.png')))- await batcher.handleBatch(- [- msg(0, 0, pt(1), compressed, ref, [- { 'content-type': Buffer.from('image/png') },- { 'content-encoding': Buffer.from('gzip') },- { [CAPTURE_TIMESTAMP_HEADER]: Buffer.from(String(CAPTURED_AT)) },- ]),- ],- 1- )+ await handleAndWrite(batcher, [+ msg(0, 0, pt(1), compressed, ref, [+ { 'content-type': Buffer.from('image/png') },+ { 'content-encoding': Buffer.from('gzip') },+ { [CAPTURE_TIMESTAMP_HEADER]: Buffer.from(String(CAPTURED_AT)) },+ ]),+ ])expect(parked).toEqual([{@@ -998,7 +937,6 @@ describe('ImageBatcher', () => {new FakeOffsets(),scrubClient,{ ...options, scrubConcurrency: 2 },- 0,{ park: () => Promise.resolve() })).toThrow('scrubConcurrency must exceed')@@ -1029,14 +967,14 @@ describe('ImageBatcher', () => {),} as unknown as ScrubClientlet parkAttempts = 0- const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, poisonClient, options, 0, {+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, poisonClient, options, {park: () => {parkAttempts += 1return parkAttempts < 3 ? Promise.reject(new Error('dlq produce failed')) : Promise.resolve()},})- await expect(batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('poison'))], 1)).resolves.toBeUndefined()+ await expect(batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('poison'))])).resolves.toBeUndefined()expect(parkAttempts).toBe(3)// The offset only moves once the bytes are somewhere, never while parking is still failing.@@ -1055,14 +993,14 @@ describe('ImageBatcher', () => {signal.addEventListener('abort', () => reject(new Error('scrub batch aborted')), { once: true })),} as unknown as ScrubClient- const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, hangingClient, options, 0)+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, hangingClient, options)const startBatch = jest.spyOn(ImageScrubConsumerMetrics, 'startBatch')const finishBatch = jest.spyOn(ImageScrubConsumerMetrics, 'finishBatch')- const running = batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))], 1)+ const running = batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))])expect(startBatch).toHaveBeenCalledTimes(1)expect(finishBatch).not.toHaveBeenCalled()- batcher.stop()+ await batcher.stop()await expect(running).resolves.toBeUndefined()expect(finishBatch).toHaveBeenCalledTimes(1)@@ -1080,20 +1018,197 @@ describe('ImageBatcher', () => {revoked.offsetsStore = () => {throw Object.assign(new Error('Local: Erroneous state'), { code: -172 })}- const batcher = new ImageBatcher(store as unknown as ImageShardStore, revoked, scrubClient, options, 0)+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, revoked, scrubClient, options)- await expect(batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))], 1)).resolves.toBeUndefined()+ await expect(batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))])).resolves.toBeUndefined()+ await batcher.drain()expect(store.writes).toHaveLength(1)})- it('still fails the batch when storing offsets fails for any other reason', async () => {+ it('still fails when storing offsets fails for any other reason', async () => {const store = new FakeStore()const broken = new FakeOffsets()broken.offsetsStore = () => {throw Object.assign(new Error('Broker: Not coordinator'), { code: 16 })}- const batcher = new ImageBatcher(store as unknown as ImageShardStore, broken, scrubClient, options, 0)+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, broken, scrubClient, options)++ await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))])+ await expect(batcher.drain()).rejects.toThrow('Not coordinator')+ await expect(batcher.handleBatch([msg(0, 1, pt(1), Buffer.from('b'))])).rejects.toThrow('Not coordinator')+ })++ it('writes the shards of one batch while it scrubs the next batch', async () => {+ // A batch's images spread over as many shard groups as team-months, and each group costs S3+ // round trips. A write that blocks its batch leaves the sidecar idle for the sum of them.+ const store = new FakeStore()+ let releaseWrite = (): void => {}+ const writeGate = new Promise<void>((resolve) => (releaseWrite = resolve))+ const writeShard = store.writeShard.bind(store)+ store.writeShard = async (images) => {+ await writeGate+ return writeShard(images)+ }+ const offsets = new FakeOffsets()+ const scrubbed: string[] = []+ const recordingClient = {+ scrub: (b: Buffer) => {+ scrubbed.push(b.toString())+ return Promise.resolve(b)+ },+ } as unknown as ScrubClient+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, recordingClient, options)++ await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('first'))])+ await batcher.handleBatch([msg(0, 1, pt(1), Buffer.from('second'))])++ // Both batches scrubbed while the first write is still held open, and nothing is stored yet.+ expect(scrubbed).toEqual(['first', 'second'])+ expect(store.writes).toHaveLength(0)+ expect(offsets.received).toEqual([])++ releaseWrite()+ await batcher.drain()++ expect(store.writes.flat()).toHaveLength(2)+ expect(offsets.received.flat().map((offset) => offset.offset)).toEqual([1, 2])+ })++ it('writes the shard groups of one hand-off concurrently', async () => {+ const store = new FakeStore()+ let active = 0+ let maximumActive = 0+ const writeShard = store.writeShard.bind(store)+ store.writeShard = async (images) => {+ active += 1+ maximumActive = Math.max(maximumActive, active)+ await new Promise((resolve) => setImmediate(resolve))+ active -= 1+ return writeShard(images)+ }+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, new FakeOffsets(), scrubClient, options)++ await handleAndWrite(batcher, [msg(0, 0, pt(1), Buffer.from('a')), msg(0, 1, '42', Buffer.from('b'))])++ expect(store.writes).toHaveLength(2)+ expect(maximumActive).toBe(2)+ })++ it('waits on the oldest hand-off once two are in flight, so a stalled S3 bounds what a pod holds', async () => {+ const store = new FakeStore()+ let releaseWrite = (): void => {}+ const writeGate = new Promise<void>((resolve) => (releaseWrite = resolve))+ const writeShard = store.writeShard.bind(store)+ store.writeShard = async (images) => {+ await writeGate+ return writeShard(images)+ }+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, new FakeOffsets(), scrubClient, options)++ await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))])+ await batcher.handleBatch([msg(0, 1, pt(1), Buffer.from('b'))])+ let thirdSettled = false+ const third = batcher.handleBatch([msg(0, 2, pt(1), Buffer.from('c'))]).then(() => {+ thirdSettled = true+ })+ for (let tick = 0; tick < 20; tick++) {+ await new Promise((resolve) => setImmediate(resolve))+ }+ expect(thirdSettled).toBe(false)++ releaseWrite()+ await third+ await batcher.drain()+ expect(store.writes.flat()).toHaveLength(3)+ })++ it('stop() waits for the write lane, so finished images reach S3 and their offsets are stored', async () => {+ // disconnect() commits whatever offsets are stored when it runs, so a stop that returned+ // before the lane finished would leave the last written images to be scrubbed again.+ const store = new FakeStore()+ let releaseWrite = (): void => {}+ const writeGate = new Promise<void>((resolve) => (releaseWrite = resolve))+ const writeShard = store.writeShard.bind(store)+ store.writeShard = async (images) => {+ await writeGate+ return writeShard(images)+ }+ const offsets = new FakeOffsets()+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, scrubClient, options)+ await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))])++ let stopped = false+ const stopping = batcher.stop().then(() => {+ stopped = true+ })+ for (let tick = 0; tick < 20; tick++) {+ await new Promise((resolve) => setImmediate(resolve))+ }+ expect(stopped).toBe(false)++ releaseWrite()+ await stopping+ expect(store.writes.flat()).toHaveLength(1)+ expect(offsets.received.flat().map((offset) => offset.offset)).toEqual([1])+ })++ it('discards a hand-off queued behind one that found its partitions revoked', async () => {+ // The new owner rescrubs that span, so writing it here leaves a second shard under a random+ // key. The discarded refs are unmarked, or a replay on this pod would dedup them away unwritten.+ const store = new FakeStore()+ let releaseWrite = (): void => {}+ const writeGate = new Promise<void>((resolve) => (releaseWrite = resolve))+ const writeShard = store.writeShard.bind(store)+ store.writeShard = async (images) => {+ await writeGate+ return writeShard(images)+ }+ const revoked = new FakeOffsets()+ revoked.offsetsStore = () => {+ throw Object.assign(new Error('Local: Erroneous state'), { code: -172 })+ }+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, revoked, scrubClient, options)++ await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))])+ await batcher.handleBatch([msg(0, 1, pt(1), Buffer.from('b'))])+ releaseWrite()+ await batcher.drain()+ expect(store.writes.flat()).toHaveLength(1)++ await handleAndWrite(batcher, [msg(0, 1, pt(1), Buffer.from('b'))])+ expect(store.writes.flat()).toHaveLength(2)+ })++ it('lets sibling object writes settle before a hand-off reports the first failure', async () => {+ // The lane's failure ends the process, and a write still in flight at that point leaves a+ // partial shard behind that nothing indexes.+ const store = new FakeStore()+ let releaseWrite = (): void => {}+ const writeGate = new Promise<void>((resolve) => (releaseWrite = resolve))+ let settledWrites = 0+ store.writeShard = async (images) => {+ if (images[0].teamId === '42') {+ throw new Error('s3 down')+ }+ await writeGate+ settledWrites += 1+ return { shard: 'shard', bytes: 0 }+ }+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, new FakeOffsets(), scrubClient, options)+ await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a')), msg(0, 1, '42', Buffer.from('b'))])++ let failed = false+ const drain = batcher.drain().catch(() => {+ failed = true+ })+ for (let tick = 0; tick < 20; tick++) {+ await new Promise((resolve) => setImmediate(resolve))+ }+ expect(failed).toBe(false)- await expect(batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))], 1)).rejects.toThrow('Not coordinator')+ releaseWrite()+ await drain+ expect(failed).toBe(true)+ expect(settledWrites).toBe(1)})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.tsindex e60b1275142d..18f62438da2f 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts@@ -1,5 +1,6 @@import { LibrdKafkaError, Message, TopicPartitionOffset } from 'node-rdkafka'import { setTimeout as waitForRetry } from 'node:timers/promises'+import pLimit from 'p-limit'import { findOffsetsToCommit, parseKafkaHeaders } from '~/common/kafka/consumer/consumer-v1'import { ConcurrencyController } from '~/common/utils/concurrencyController'@@ -113,18 +114,71 @@ interface SettledScrub {}export interface ImageBatcherOptions {- flushIntervalMs: numbermaxImages: numbermaxBytes: numberscrubConcurrency: numberdedupMaxRefs: number}+/**+ * S3 objects in flight per hand-off: shard groups and URL images alike.+ *+ * A batch's images spread over as many shard groups as it has team-months, which is most of them,+ * so written one after another the groups cost a round trip each and the sidecar idles for the sum.+ * Written together they cost about one. Bounded so a burst cannot exhaust the S3 client's socket+ * pool, and separate from the scrub concurrency so a write never takes a slot from the next batch.+ */+export const WRITE_CONCURRENCY = 8++/**+ * Hand-offs the write lane may hold before the scrub waits on it: one writing, one queued.+ *+ * Writes run behind the scrub of the next batch, so an S3 slowdown would otherwise queue hand-offs+ * without limit and hold their images in memory. Waiting on the oldest hand-off bounds that at+ * two batches of scrubbed output plus the batch in flight.+ */+const MAX_WRITES_IN_FLIGHT = 2++/**+ * What a batch hands to the write lane: images whose offsets retired in order, and those offsets.+ * The offsets are stored only once every image here is durable, so they travel together.+ */+interface WriteHandoff {+ images: ScrubbedRef[]+ offsets: TopicPartitionOffset[]+}++/**+ * Waits for every write, then raises the first failure. A lane failure exits the process, and a+ * sibling write still in flight at that point leaves a partial shard behind that nothing indexes.+ */+async function settleAll(writes: Promise<void>[]): Promise<void> {+ const failed = (await Promise.allSettled(writes)).find(+ (result): result is PromiseRejectedResult => result.status === 'rejected'+ )+ if (failed) {+ throw failed.reason+ }+}+export class ImageBatcher {- private buffer: ScrubbedRef[] = []- private bufferBytes = 0- private pendingOffsets = new Map<string, TopicPartitionOffset>()- private lastFlushMs: number+ /** Retired images of the running batch that no hand-off has taken yet. */+ private outgoing: ScrubbedRef[] = []+ private outgoingBytes = 0+ private outgoingOffsets = new Map<string, TopicPartitionOffset>()+ /**+ * Writes hand-offs one at a time, in the order the batches retired them.+ *+ * The order is what makes a failure safe: a hand-off stores its offsets only after its own+ * images are durable, and the first failure poisons the lane so nothing behind it can store an+ * offset past the images that were never written. The process then exits on the next batch and+ * replays from the last stored offset.+ */+ private readonly writeLane = pLimit(1)+ private readonly writeLimiter = pLimit(WRITE_CONCURRENCY)+ private writesInFlight: Promise<void>[] = []+ private writeFailure: unknown+ private activeBatchSettled: Promise<void> = Promise.resolve()private readonly maxInFlight: numberprivate readonly scrubConcurrency: ConcurrencyController/**@@ -133,9 +187,9 @@ export class ImageBatcher {* between recrawls. A best-effort stand-in for asking S3 "are these bytes already in the bucket",* which shards cannot answer: they pack many images per object, so no per-hash key exists. The* topic is keyed by ref, so every copy of an inline image reaches this same pod and within capacity- * the answer is exact; past it we simply rescrub. Marking a scrubbed ref only after its buffer push- * is what stops a rebalance without a restart from skipping a ref it never persisted, since a batch- * that throws keeps its buffer. Sizing is a throughput question, not a correctness one.+ * the answer is exact; past it we simply rescrub. Marking a scrubbed ref only once it is staged for a+ * hand-off is what stops a rebalance without a restart from skipping a ref it never persisted, since+ * a batch that throws discards what it staged. Sizing is a throughput question, not a correctness one.*/private readonly seenRefs: RefDedupCache/**@@ -149,7 +203,7 @@ export class ImageBatcher {private activeBatch: AbortController | null = nullprivate stopping = false/**- * Set when a flush finds this pod no longer owns the partitions it is committing.+ * Set when a write finds this pod no longer owns the partitions it is committing.** Whatever is left of the batch belongs to another pod now, and scrubbing it anyway spends the* same saturated sidecar twice on one image and writes a second shard for a span the new owner@@ -165,7 +219,6 @@ export class ImageBatcher {private readonly offsetStore: OffsetStore,private readonly scrubClient: ScrubClient,private readonly options: ImageBatcherOptions,- nowMs: number,private readonly deadLetters: DeadLetterSink | null = null,private readonly keyManager?: MlKeyManager) {@@ -184,26 +237,55 @@ export class ImageBatcher {`scrubConcurrency must exceed ${POISON_MIN_OTHER_SUCCESSES} for dead-lettering to be reachable, got ${this.maxInFlight}`)}- this.lastFlushMs = nowMsthis.scrubConcurrency = new ConcurrencyController(this.maxInFlight)this.seenRefs = new RefDedupCache('image_scrub_consumer', options.dedupMaxRefs)}- /** Interrupts the running batch so a graceful shutdown does not wait on an unresponsive sidecar. */- public stop(): void {+ /**+ * Interrupts the running batch so a graceful shutdown does not wait on an unresponsive sidecar,+ * then waits for the write lane, so the images that did finish reach S3 and their offsets are+ * stored while the consumer is still connected to commit them. Resolves either way: a write+ * that failed was already logged by the lane, and there is no batch left to raise it through.+ */+ public async stop(): Promise<void> {this.stopping = truethis.activeBatch?.abort()+ await this.activeBatchSettled+ try {+ await this.drain()+ } catch (error) {+ logger.error('🔥', 'image_scrub_write_failed_during_shutdown', { error: String(error) })+ }}- public async handleBatch(messages: Message[], nowMs: number): Promise<void> {+ /** Resolves once every hand-off taken so far is written and its offsets stored; rejects with the lane's failure. */+ public async drain(): Promise<void> {+ await Promise.all(this.writesInFlight)+ // A hand-off that failed before this call has already left the list, so the list alone cannot report it.+ if (this.writeFailure !== undefined) {+ throw this.writeFailure+ }+ }++ public async handleBatch(messages: Message[]): Promise<void> {if (this.stopping) {return}+ // Raised here rather than swallowed by the lane, because the Kafka loop exits the process on+ // a batch error and that exit is what replays the unwritten images from the last stored offset.+ if (this.writeFailure !== undefined) {+ throw this.writeFailure+ }const controller = new AbortController()this.activeBatch = controllerthis.partitionsRevoked = false+ const running = this.handleActiveBatch(messages, controller)+ this.activeBatchSettled = running.then(+ () => undefined,+ () => undefined+ )try {- await this.handleActiveBatch(messages, nowMs, controller)+ await running} catch (error) {if (!(this.stopping && error instanceof ScrubAborted)) {throw error@@ -215,7 +297,7 @@ export class ImageBatcher {}}- private async handleActiveBatch(messages: Message[], nowMs: number, controller: AbortController): Promise<void> {+ private async handleActiveBatch(messages: Message[], controller: AbortController): Promise<void> {// Skips resolve up front so the window only ever holds real work: a duplicate admitted into a// slot would occupy it and complete instantly, spending the pod's concurrency on no-ops.if (messages.length) {@@ -281,7 +363,7 @@ export class ImageBatcher {ImageScrubConsumerMetrics.startBatch()}try {- await this.scrubAndStage(messages, planned, controller, nowMs)+ await this.scrubAndStage(messages, planned, controller)} finally {// Empty polls arrive on a timer under callEachBatchWhenEmpty and would otherwise bury// the real distribution of both histograms in a zero bucket.@@ -299,8 +381,7 @@ export class ImageBatcher {private async scrubAndStage(messages: Message[],planned: PlannedScrub[],- controller: AbortController,- nowMs: number+ controller: AbortController): Promise<void> {let spanStart = 0let nextToSubmit = 0@@ -309,7 +390,7 @@ export class ImageBatcher {const settled = new Array<boolean>(planned.length).fill(false)const inFlight = new Map<number, Promise<SettledScrub>>()// Results wait here until their slot retires, so the buffer only ever holds images whose- // offsets have been recorded. Without it a flush could persist an image while a still-running+ // offsets have been recorded. Without it a write could persist an image while a still-running// predecessor kept its offset unrecorded, and a later batch failure would rewrite it under a// fresh shard key. Staged bytes count towards capacity, which is what bounds this.const staged = new Array<ScrubbedRef | null>(planned.length).fill(null)@@ -325,9 +406,9 @@ export class ImageBatcher {inFlight.set(nextToSubmit, this.submitScrub(nextToSubmit, planned[nextToSubmit], controller))nextToSubmit++}- // Only reachable over capacity with work left: flush to make room rather than spin.+ // Only reachable over capacity with work left: hand off to make room rather than spin.if (inFlight.size === 0) {- await this.flushOrThrow(nowMs)+ await this.handOff()if (this.partitionsRevoked) {break}@@ -337,7 +418,7 @@ export class ImageBatcher {const done = await Promise.race(inFlight.values())inFlight.delete(done.slot)if (done.error !== undefined) {- // Shutdown is not a failure. Everything retired so far is flushed below and its+ // Shutdown is not a failure. Everything retired so far is handed off below and its// offsets are already recorded; the rest was never finished, so its offsets stay// unrecorded and it replays wherever the partition lands next.if (this.stopping) {@@ -347,6 +428,12 @@ export class ImageBatcher {ImageScrubConsumerMetrics.incBatchFailed('scrub')throw done.error}+ // A hand-off that failed behind this batch: nothing this batch retires can be stored past+ // the images it never wrote, so stop scrubbing now rather than at the end of the batch.+ if (this.writeFailure !== undefined) {+ controller.abort()+ throw this.writeFailure+ }if (done.scrubbed) {staged[done.slot] = done.scrubbedstagedCount += 1@@ -356,14 +443,14 @@ export class ImageBatcher {// Completions arrive out of order, so only the contiguous run from the front is safe to// commit: anything past a still-running image would commit an offset for work that has// not happened. The span also covers the skipped messages between retired entries, which- // are done too and would otherwise replay forever. Offsets are only ever *stored* by a- // flush, after the buffer holding these images is durably written.+ // are done too and would otherwise replay forever. Offsets are only ever *stored* by the+ // write lane, after the hand-off holding these images is durably written.settled[done.slot] = trueconst retiredBefore = retiredwhile (retired < planned.length && settled[retired]) {const ready = staged[retired]if (ready) {- this.bufferScrubbedRef(ready)+ this.stageOutgoing(ready)// Marked here rather than on completion: a staged image is a local that a thrown// batch discards, so a ref marked before retirement could be skipped on replay// without ever having been persisted.@@ -383,7 +470,7 @@ export class ImageBatcher {spanStart = spanEnd}if (this.overCapacity(stagedCount, stagedBytes)) {- await this.flushOrThrow(nowMs)+ await this.handOff()}if (this.partitionsRevoked) {controller.abort()@@ -394,21 +481,71 @@ export class ImageBatcher {// Neither the offsets nor the shard belong to this pod any more. Writing it would only// duplicate what the partition's new owner is already producing, under a fresh key that// nothing later reconciles.- this.buffer = []- this.bufferBytes = 0- this.pendingOffsets.clear()+ this.forgetUnwritten(this.outgoing)+ this.outgoing = []+ this.outgoingBytes = 0+ this.outgoingOffsets.clear()return}if (this.stopping) {// Deliberately no tail recordOffsets: past the last retired image nothing was finished,// and moving offsets over it here would lose exactly what the wait exists to protect.- await this.flushOrThrow(nowMs)+ await this.handOff()return}// A batch whose tail is all skips, or which is nothing but skips, still has to move offsets.this.recordOffsets(messages.slice(spanStart))- if (this.shouldFlush(nowMs)) {- await this.flushOrThrow(nowMs)+ await this.handOff()+ }++ /**+ * Moves everything retired so far to the write lane and returns as soon as the lane has room,+ * so the scrub of the next batch overlaps the S3 round trips of this one. The wait on the+ * oldest hand-off is the only place a slow S3 reaches the scrub, and it is what bounds memory.+ */+ private async handOff(): Promise<void> {+ if (this.outgoing.length === 0 && this.outgoingOffsets.size === 0) {+ return+ }+ const handoff: WriteHandoff = { images: this.outgoing, offsets: [...this.outgoingOffsets.values()] }+ this.outgoing = []+ this.outgoingBytes = 0+ this.outgoingOffsets = new Map()+ const write = this.writeLane(() => this.writeOrPoison(handoff))+ this.writesInFlight.push(write)+ const forget = (): void => {+ const index = this.writesInFlight.indexOf(write)+ if (index >= 0) {+ void this.writesInFlight.splice(index, 1)+ }+ }+ void write.then(forget, forget)+ if (this.writesInFlight.length > MAX_WRITES_IN_FLIGHT) {+ await this.writesInFlight[0]+ }+ }++ private async writeOrPoison(handoff: WriteHandoff): Promise<void> {+ if (this.writeFailure !== undefined) {+ throw this.writeFailure+ }+ // Found by the hand-off ahead of this one, whose offsets could not be stored: the span belongs+ // to another pod now, and writing it here would leave a second shard under a random key.+ if (this.partitionsRevoked) {+ this.forgetUnwritten(handoff.images)+ return+ }+ const startedAt = performance.now()+ try {+ await this.write(handoff)+ } catch (error) {+ if (this.writeFailure === undefined) {+ this.writeFailure = error ?? new Error('image shard write failed')+ }+ ImageScrubConsumerMetrics.incBatchFailed('write')+ throw error+ } finally {+ ImageScrubConsumerMetrics.observeWrite((performance.now() - startedAt) / 1000)}}@@ -482,14 +619,23 @@ export class ImageBatcher {return planned}- private bufferScrubbedRef(ready: ScrubbedRef): void {- this.buffer.push(ready)- this.bufferBytes += ready.image.bytes.length+ /** A ref that was marked seen but never persisted would be deduped away unwritten if its partition came back here. */+ private forgetUnwritten(images: ScrubbedRef[]): void {+ for (const { ref, source } of images) {+ if (source === 'bytes') {+ this.seenRefs.delete(ref)+ }+ }+ }++ private stageOutgoing(ready: ScrubbedRef): void {+ this.outgoing.push(ready)+ this.outgoingBytes += ready.image.bytes.length}private recordOffsets(messages: Message[]): void {for (const offset of findOffsetsToCommit(messages)) {- this.pendingOffsets.set(`${offset.topic}:${offset.partition}`, offset)+ this.outgoingOffsets.set(`${offset.topic}:${offset.partition}`, offset)}}@@ -512,15 +658,6 @@ export class ImageBatcher {)}- private async flushOrThrow(nowMs: number): Promise<void> {- try {- await this.flush(nowMs)- } catch (e) {- ImageScrubConsumerMetrics.incBatchFailed('write')- throw e- }- }-private async scrubOne(planned: PlannedScrub,signal: AbortSignal@@ -662,62 +799,51 @@ export class ImageBatcher {/** Staged results are counted so a slow slot holding back retirement still applies backpressure. */private overCapacity(stagedCount = 0, stagedBytes = 0): boolean {return (- this.buffer.length + stagedCount >= this.options.maxImages ||- this.bufferBytes + stagedBytes >= this.options.maxBytes+ this.outgoing.length + stagedCount >= this.options.maxImages ||+ this.outgoingBytes + stagedBytes >= this.options.maxBytes)}- private shouldFlush(nowMs: number): boolean {- if (this.overCapacity()) {- return true- }- const hasPending = this.buffer.length > 0 || this.pendingOffsets.size > 0- return hasPending && nowMs - this.lastFlushMs >= this.options.flushIntervalMs- }-- public async flush(nowMs: number): Promise<void> {- this.lastFlushMs = nowMs- if (this.buffer.length > 0) {+ private async write(handoff: WriteHandoff): Promise<void> {+ if (handoff.images.length > 0) {const imageKeys = this.keyManager? await this.keyManager.reader.read(- this.buffer.flatMap(({ image }) =>+ handoff.images.flatMap(({ image }) =>image.sessionMonth === undefined? []: [imageKeyId(Number(image.teamId), image.sessionMonth!)])): new Map()- this.buffer = this.buffer.filter(+ const keyed = handoff.images.filter(({ image }) =>image.sessionMonth === undefined ||imageKeys.has(tableKeyString(imageKeyId(Number(image.teamId), image.sessionMonth!))))- const inlineItems = this.buffer.filter(+ const inlineItems = keyed.filter((item): item is ScrubbedRef & { image: ScrubbedImage } => item.source === 'bytes')- const urlItems = this.buffer.filter(+ const urlItems = keyed.filter((item): item is ScrubbedRef & { image: ScrubbedUrlImage } => item.source === 'url')- await Promise.all(- urlItems.map(async (item) => {- const outcome = await this.scrubConcurrency.run({- debugTag: item.image.hash,- fn: () =>- this.store.writeUrlImage(- item.image,- item.image.sessionMonth === undefined- ? undefined- : imageKeys.get(- tableKeyString(- imageKeyId(Number(item.image.teamId), item.image.sessionMonth!)- )- )- ),+ // URL images first: their keys are deterministic, so a failure here leaves nothing behind,+ // while a shard is written under a fresh key that a replay would duplicate.+ await settleAll(+ urlItems.map((item) =>+ this.writeLimiter(async () => {+ const outcome = await this.store.writeUrlImage(+ item.image,+ item.image.sessionMonth === undefined+ ? undefined+ : imageKeys.get(+ tableKeyString(imageKeyId(Number(item.image.teamId), item.image.sessionMonth!))+ )+ )+ if (outcome === 'created' && item.capturedAtMs !== undefined) {+ ImageScrubConsumerMetrics.observeCaptureToS3('url', item.capturedAtMs, Date.now())+ }})- if (outcome === 'created' && item.capturedAtMs !== undefined) {- ImageScrubConsumerMetrics.observeCaptureToS3('url', item.capturedAtMs, Date.now())- }- })+ ))const groups = new Map<string, typeof inlineItems>()for (const item of inlineItems) {@@ -729,32 +855,32 @@ export class ImageBatcher {group.push(item)groups.set(groupId, group)}- for (const items of groups.values()) {- if (items.length === 0) {- continue- }- const { bytes } = await this.store.writeShard(- items.map((item) => item.image),- items[0].image.sessionMonth === undefined- ? undefined- : imageKeys.get(- tableKeyString(imageKeyId(Number(items[0].image.teamId), items[0].image.sessionMonth!))- )+ await settleAll(+ [...groups.values()].map((items) =>+ this.writeLimiter(async () => {+ const { bytes } = await this.store.writeShard(+ items.map((item) => item.image),+ items[0].image.sessionMonth === undefined+ ? undefined+ : imageKeys.get(+ tableKeyString(+ imageKeyId(Number(items[0].image.teamId), items[0].image.sessionMonth!)+ )+ )+ )+ const storedAtMs = Date.now()+ for (const item of items) {+ if (item.capturedAtMs !== undefined) {+ ImageScrubConsumerMetrics.observeCaptureToS3('inline', item.capturedAtMs, storedAtMs)+ }+ }+ ImageScrubConsumerMetrics.observeShard(items.length, bytes)+ }))- const storedAtMs = Date.now()- for (const item of items) {- if (item.capturedAtMs !== undefined) {- ImageScrubConsumerMetrics.observeCaptureToS3('inline', item.capturedAtMs, storedAtMs)- }- }- ImageScrubConsumerMetrics.observeShard(items.length, bytes)- }- this.buffer = []- this.bufferBytes = 0+ )}- if (this.pendingOffsets.size > 0) {- this.storeOffsetsUnlessRevoked([...this.pendingOffsets.values()])- this.pendingOffsets.clear()+ if (handoff.offsets.length > 0) {+ this.storeOffsetsUnlessRevoked(handoff.offsets)}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.tsindex 3a4b7f767326..ac937c3b8f2e 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts@@ -106,9 +106,14 @@ export class ImageScrubConsumerMetrics {})private static readonly batchDuration = new Histogram({name: 'ml_mirror_image_scrub_consumer_batch_duration_seconds',- help: 'Wall time per poll batch. Read against Kafka max.poll.interval.ms (300s): batches approaching it get the pod evicted mid-batch, and the partition is redone by whoever picks it up',+ help: 'Wall time per poll batch, from its first scrub until its images are handed to the write lane; the S3 writes run behind the next batch and are timed by write_duration_seconds. Read against Kafka max.poll.interval.ms (300s): batches approaching it get the pod evicted mid-batch, and the partition is redone by whoever picks it up',buckets: [1, 5, 15, 30, 60, 120, 240, 300, 600],})+ private static readonly writeDuration = new Histogram({+ name: 'ml_mirror_image_scrub_consumer_write_duration_seconds',+ help: 'Wall time one hand-off spends writing its shards, URL images and offsets, excluding the wait behind the previous hand-off. It overlaps the next batch, so it only costs throughput once it exceeds batch_duration_seconds',+ buckets: [0.1, 0.5, 1, 2, 5, 15, 30, 60, 120],+ })private static activeBatchStartedAtMs: number | undefinedprivate static readonly activeBatchElapsed = new Gauge({name: 'ml_mirror_image_scrub_consumer_active_batch_elapsed_seconds',@@ -189,6 +194,9 @@ export class ImageScrubConsumerMetrics {}this.batchDuration.observe(durationSeconds)}+ public static observeWrite(durationSeconds: number): void {+ this.writeDuration.observe(durationSeconds)+ }public static startBatch(nowMs = performance.now()): void {this.activeBatchStartedAtMs = nowMs}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.tsindex f29faa209b8f..16f6c7ffed19 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts@@ -166,7 +166,6 @@ export type MlMirrorConfig = {SESSION_RECORDING_ML_IMAGE_SCRUB_GROUP_ID: stringSESSION_RECORDING_ML_IMAGE_SCRUB_PREFIX: stringSESSION_RECORDING_ML_IMAGE_SCRUB_SIDECAR_URL: string- SESSION_RECORDING_ML_IMAGE_SCRUB_FLUSH_INTERVAL_MS: numberSESSION_RECORDING_ML_IMAGE_SCRUB_MAX_IMAGES: number// Real peak memory is ~2x this: the flush does a Buffer.concat copy.SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_BYTES: number@@ -269,7 +268,6 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {SESSION_RECORDING_ML_IMAGE_SCRUB_PREFIX: 'scrubbed-images',// 127.0.0.1, not localhost: the sidecar binds IPv4 loopback, and localhost can resolve to ::1 first.SESSION_RECORDING_ML_IMAGE_SCRUB_SIDECAR_URL: 'http://127.0.0.1:9010',- SESSION_RECORDING_ML_IMAGE_SCRUB_FLUSH_INTERVAL_MS: 30 * 1000,SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_IMAGES: 1000,SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_BYTES: 128 * 1024 * 1024,SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_CONCURRENCY: 8,diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.tsindex 67bb926b9584..def16b1c5cc7 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.ts@@ -102,32 +102,29 @@ export class IngestionSessionReplayMlImageScrubServer extends MlMirrorConsumerSeconsumer,scrubClient,{- flushIntervalMs: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_FLUSH_INTERVAL_MS,maxImages: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_IMAGES,maxBytes: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_BYTES,scrubConcurrency: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_CONCURRENCY,dedupMaxRefs: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_DEDUP_MAX_REFS,},- Date.now(),deadLetters,this.keyManager)await scrubClient.waitUntilReachable()await consumer.connect((messages) => {const heartbeat = setInterval(() => consumer.heartbeat(), BATCH_HEARTBEAT_INTERVAL_MS)- return batcher.handleBatch(messages, Date.now()).finally(() => clearInterval(heartbeat))+ return batcher.handleBatch(messages).finally(() => clearInterval(heartbeat))})this.lifecycle.services.push({id: 'session-replay-ml-image-scrub',// batcher.stop() first: disconnect() waits on the running batch, and a batch waiting on an// unresponsive sidecar never returns, so without the interrupt a graceful stop runs to the- // termination grace period and ends in a SIGKILL. Then disconnect() stops the poll loop and- // commits stored offsets. The un-flushed buffer's offsets were never stored, so those- // messages just replay on restart — a final flush here would only race the still-running- // loop over the shared buffer.+ // termination grace period and ends in a SIGKILL. stop() also waits for the write lane, so+ // the offsets of every written image are stored before disconnect() stops the poll loop+ // and commits them. Whatever was still scrubbing was never stored and replays on restart.onShutdown: async () => {- batcher.stop()+ await batcher.stop()await consumer.disconnect()},healthcheck: () => consumer.isHealthy(),diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.mdindex e337d60c4a8b..8b4938388181 100644--- a/products/ai_training/docs/replay-data.md+++ b/products/ai_training/docs/replay-data.md@@ -200,6 +200,8 @@ Consumers reject malformed UUIDv7 session identifiers before reading DynamoDB.Oversized identifiers cannot fail a whole bulk key lookup.Inline images have an encrypted lookup for each reference, published after the shard and its index.Readers fetch that lookup directly; a missing image does not require a scan of the team's image history.+The image scrubber writes the shards of one poll batch while it scrubs the next batch, and writes the shard groups of a batch concurrently.+The offsets of a batch are stored after its writes complete, in batch order, so a failed write stops every later store and the pod replays from the last stored offset.Source deduplication includes the session, so deleting one source session cannot suppress another session's copy.The v2 image-fetch frontier uses a separate, initially empty DynamoDB history table.Its URL history expires eight days after the end of the session's UTC month.