:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(replay): unblock image-scrub concurrency with per-batch ref dedup (#73589)
Robbie2afaaef0edc8
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 da86c3b8dd5c..170277517e09 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@@ -50,6 +50,7 @@ const options = {maxBytes: 1e9,scrubConcurrency: 4,maxBatchScrubMs: 30_000,+ dedupMaxRefs: 1000,}describe('ImageBatcher', () => {@@ -171,6 +172,219 @@ describe('ImageBatcher', () => {expect(offsets.stored).toBe(slowStore.writes.length)})+ it('scrubs each ref once: duplicates in and across batches skip the sidecar but still advance offsets', async () => {+ // The topic is keyed by ref, so duplicate produces (per-mirror-pod producer dedup misses+ // cross-pod repeats) are partition-affine; losing this dedup silently re-burns sidecar CPU+ // per duplicate and writes duplicate shard entries.+ const store = new FakeStore()+ const offsets = new FakeOffsets()+ let scrubs = 0+ const countingClient = {+ scrub: (b: Buffer) => {+ scrubs += 1+ return Promise.resolve(b)+ },+ } as unknown as ScrubClient+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, countingClient, options, 0)++ 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)++ expect(scrubs).toBe(1)+ expect(store.writes.flat()).toHaveLength(1)+ // The all-duplicate second batch still advances offsets, or the duplicates replay forever.+ expect(offsets.received.at(-1)).toEqual([{ topic: 'session_replay_image_scrub', partition: 0, offset: 3 }])+ })++ it.each([0, 1000])(+ 'scrubs the distinct images of a duplicate-heavy batch at full concurrency (dedupMaxRefs %p)',+ async (dedupMaxRefs) => {+ // Duplicates have to collapse before the batch is chunked. Left in, they occupy+ // concurrency slots, so a chunk finishes as soon as its one distinct image does and the+ // batch serializes behind the chunk barriers — the lane then runs one image in flight+ // instead of scrubConcurrency, regardless of how many pods it has. Consecutive repeats+ // are the realistic shape: one sprite recurs across a session's snapshots.+ const store = new FakeStore()+ let inFlight = 0+ let maxInFlight = 0+ let scrubs = 0+ const trackingClient = {+ scrub: async (b: Buffer) => {+ scrubs += 1+ inFlight += 1+ maxInFlight = Math.max(maxInFlight, inFlight)+ await new Promise((resolve) => setImmediate(resolve))+ inFlight -= 1+ return b+ },+ } as unknown as ScrubClient+ const batcher = new ImageBatcher(+ store as unknown as ImageShardStore,+ new FakeOffsets(),+ trackingClient,+ { ...options, dedupMaxRefs },+ 0+ )++ const batch: Message[] = []+ for (let sprite = 0; sprite < 4; sprite++) {+ for (let repeat = 0; repeat < 8; repeat++) {+ batch.push(msg(0, batch.length, pt(1), Buffer.from(`sprite-${sprite}`)))+ }+ }+ await batcher.handleBatch(batch, 1)++ expect(scrubs).toBe(4)+ expect(maxInFlight).toBe(4)+ expect(store.writes.flat()).toHaveLength(4)+ }+ )++ it('rescrubs an image whose batch failed rather than pod-deduping the replay away', async () => {+ // A ref is marked seen only once its image is buffered. Marking it at plan time, or inside+ // scrubOne, reads as a harmless simplification and silently drops the image instead: the+ // replay is pod-deduped, its offset advances, and nothing ever writes it. No error, no+ // counter, and every other test still green.+ let attempts = 0+ const flakyClient = {+ scrub: (b: Buffer) => {+ attempts += 1+ return attempts === 1 ? Promise.reject(new Error('sidecar down')) : Promise.resolve(b)+ },+ } as unknown as ScrubClient+ const store = new FakeStore()+ const batcher = new ImageBatcher(+ store as unknown as ImageShardStore,+ new FakeOffsets(),+ flakyClient,+ options,+ 0+ )+ 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)++ expect(store.writes.flat()).toHaveLength(1)+ })++ it('advances every partition past the duplicates it skipped, not just the one it scrubbed on', async () => {+ // The span walk is the one place that can commit an offset for a message it never processed,+ // 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 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+ )++ expect(offsets.received.at(-1)).toEqual(+ expect.arrayContaining([+ { topic: 'session_replay_image_scrub', partition: 0, offset: 102 },+ { topic: 'session_replay_image_scrub', partition: 1, offset: 202 },+ ])+ )+ })++ 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+ // 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()+ const offsets = new FakeOffsets()+ let scrubs = 0+ const failLateClient = {+ scrub: (b: Buffer) => {+ scrubs += 1+ 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+ )++ 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+ )+ ).rejects.toThrow('sidecar down')++ expect(offsets.received).toHaveLength(1)+ expect(offsets.received[0]).toHaveLength(2)+ expect(offsets.received[0]).toEqual(+ expect.arrayContaining([+ { topic: 'session_replay_image_scrub', partition: 0, offset: 11 },+ { topic: 'session_replay_image_scrub', partition: 1, offset: 21 },+ ])+ )+ })++ it('stops re-sending an image the sidecar permanently rejected', async () => {+ // A 422/413 is a verdict on the content, so every later copy would earn the same rejection.+ // Without marking it, the most broken images are the ones that keep costing sidecar calls.+ let calls = 0+ const rejectingClient = {+ scrub: () => {+ calls += 1+ return Promise.resolve(null)+ },+ } as unknown as ScrubClient+ const batcher = new ImageBatcher(+ new FakeStore() as unknown as ImageShardStore,+ new FakeOffsets(),+ rejectingClient,+ options,+ 0+ )+ const broken = Buffer.from('broken')++ await batcher.handleBatch([msg(0, 0, pt(1), broken)], 1)+ await batcher.handleBatch([msg(0, 1, pt(1), broken)], 2)++ expect(calls).toBe(1)+ })++ 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 sprite = Buffer.from('sprite')+ await batcher.handleBatch([msg(0, 0, pt(1), sprite)], 1)+ await batcher.handleBatch([msg(0, 1, pt(1), sprite)], 2)+ 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)+ expect(store.writes.flat()).toHaveLength(3)+ })+test.each([[0], [NaN], [-1]])('rejects scrubConcurrency %p at construction', (scrubConcurrency) => {// 0 spins the chunk loop forever; NaN skips it entirely yet still commits offsets,// silently dropping the whole batch — both must fail loudly at boot instead.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 5931dcd98fe3..dbd0c637627b 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@@ -2,8 +2,9 @@ import { Message, TopicPartitionOffset } from 'node-rdkafka'import { findOffsetsToCommit } from '~/common/kafka/consumer/consumer-v1'import { ConcurrencyController } from '~/common/utils/concurrencyController'+import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'-import { isImageRef, parseImageRef } from './content-ref'+import { parseImageRef } from './content-ref'import { ImageShardStore, ScrubbedImage } from './image-shard-store'import { ImageScrubConsumerMetrics } from './metrics'import { ScrubClient } from './scrub-client'@@ -12,12 +13,27 @@ export interface OffsetStore {offsetsStore(offsets: TopicPartitionOffset[]): void}+/** The batch index is what lets offsets advance across the messages planning skipped. */+interface PlannedScrub {+ index: number+ ref: string+ pseudoTeam: string+ hash: string+ value: Buffer+}++interface ScrubbedRef {+ ref: string+ image: ScrubbedImage+}+export interface ImageBatcherOptions {flushIntervalMs: numbermaxImages: numbermaxBytes: numberscrubConcurrency: numbermaxBatchScrubMs: number+ dedupMaxRefs: number}export class ImageBatcher {@@ -27,6 +43,17 @@ export class ImageBatcher {private lastFlushMs: numberprivate readonly chunkSize: numberprivate readonly scrubConcurrency: ConcurrencyController+ /**+ * Refs this pod has resolved, either by buffering the scrubbed bytes or by having the sidecar+ * permanently reject them. 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 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.+ */+ private readonly seenRefs: RefDedupCacheconstructor(private readonly store: ImageShardStore,@@ -43,9 +70,18 @@ export class ImageBatcher {}this.lastFlushMs = nowMsthis.scrubConcurrency = new ConcurrencyController(this.chunkSize)+ this.seenRefs = new RefDedupCache('image_scrub_consumer', options.dedupMaxRefs)}public async handleBatch(messages: Message[], nowMs: number): Promise<void> {+ // Skips must resolve before chunking: a duplicate left in a chunk still holds a concurrency+ // slot and completes instantly, so the chunk ends with its one distinct image and the batch+ // serializes behind the barriers, running one scrub at a time whatever scrubConcurrency says.+ if (messages.length) {+ ImageScrubConsumerMetrics.observeBatchMessages(messages.length)+ }+ const planned = this.planBatch(messages)+// Scrub in concurrency-sized chunks with the capacity bounds applied between chunks: scrubbed// outputs can dwarf their inputs (a sub-MB input can come back as a multi-MB full-resolution// PNG), so retaining a whole poll batch of them before the first bound check can hold@@ -57,11 +93,12 @@ export class ImageBatcher {// loop misattributed to the sidecar.const controller = new AbortController()let scrubBudgetMs = this.options.maxBatchScrubMs- for (let i = 0; i < messages.length; i += this.chunkSize) {- const chunk = messages.slice(i, i + this.chunkSize)+ let spanStart = 0+ for (let i = 0; i < planned.length; i += this.chunkSize) {+ const chunk = planned.slice(i, i + this.chunkSize)const chunkStartMs = performance.now()const timer = setTimeout(() => controller.abort(), scrubBudgetMs)- let scrubbed: ScrubbedImage[]+ let scrubbed: ScrubbedRef[]try {scrubbed = await this.scrubChunk(chunk, controller)} catch (e) {@@ -71,38 +108,74 @@ export class ImageBatcher {clearTimeout(timer)}scrubBudgetMs -= performance.now() - chunkStartMs- for (const image of scrubbed) {+ for (const { ref, image } of scrubbed) {this.buffer.push(image)this.bufferBytes += image.bytes.length+ this.seenRefs.add(ref)}- // Advance offsets per completed chunk (even all-skipped ones, or skipped messages- // replay forever). They are only ever *stored* by a flush, after the buffer — which- // holds exactly these chunks' images — is durably written. A mid-batch flush thereby- // records the progress it persisted: a later failure in this batch replays only from- // the flush, instead of re-writing another copy of the flushed shard per replay.- for (const offset of findOffsetsToCommit(chunk)) {- this.pendingOffsets.set(`${offset.topic}:${offset.partition}`, offset)- }+ // The span also covers the skipped messages between this chunk's 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, so a mid-batch flush records+ // exactly the progress it persisted and a later failure replays only from there.+ const spanEnd = chunk[chunk.length - 1].index + 1+ this.recordOffsets(messages.slice(spanStart, spanEnd))+ spanStart = spanEndif (this.overCapacity()) {await this.flushOrThrow(nowMs)}}+ // 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)}}- private async scrubChunk(messages: Message[], controller: AbortController): Promise<ScrubbedImage[]> {+ /** Retains nothing between batches, so unlike [[seenRefs]] this dedup cannot be sized wrong or disabled. */+ private planBatch(messages: Message[]): PlannedScrub[] {+ const planned: PlannedScrub[] = []+ const batchRefs = new Set<string>()+ for (const [index, m] of messages.entries()) {+ const ref = m.key?.toString('utf8')+ // The ref's hash is a producer-side per-team HMAC; this consumer doesn't hold the key and+ // trusts the producer (the topic's only writer) that the key names these bytes.+ const parsed = ref ? parseImageRef(ref) : null+ if (!ref || !parsed || !m.value) {+ ImageScrubConsumerMetrics.incInvalidKey()+ continue+ }+ if (batchRefs.has(ref)) {+ ImageScrubConsumerMetrics.incDeduped('batch')+ continue+ }+ batchRefs.add(ref)+ if (this.seenRefs.has(ref)) {+ ImageScrubConsumerMetrics.incDeduped('pod')+ continue+ }+ planned.push({ index, ref, pseudoTeam: parsed.pseudoTeam, hash: parsed.hash, value: m.value })+ }+ return planned+ }++ private recordOffsets(messages: Message[]): void {+ for (const offset of findOffsetsToCommit(messages)) {+ this.pendingOffsets.set(`${offset.topic}:${offset.partition}`, offset)+ }+ }++ private async scrubChunk(planned: PlannedScrub[], controller: AbortController): Promise<ScrubbedRef[]> {try {const scrubbed = await Promise.all(- messages.map((m) =>+ planned.map((p) =>this.scrubConcurrency.run({- fn: () => this.scrubOne(m, controller.signal),+ fn: () =>+ this.scrubOne(p, controller.signal).then((image) => (image ? { ref: p.ref, image } : null)),abortController: controller,})))- return scrubbed.filter((image): image is ScrubbedImage => image !== null)+ return scrubbed.filter((entry): entry is ScrubbedRef => entry !== null)} catch (e) {controller.abort() // one failure dooms the batch, so cancel the siblings still in flightthrow e@@ -118,26 +191,18 @@ export class ImageBatcher {}}- private async scrubOne(m: Message, signal: AbortSignal): Promise<ScrubbedImage | null> {- const ref = m.key?.toString('utf8')- if (!ref || !isImageRef(ref) || !m.value) {- ImageScrubConsumerMetrics.incInvalidKey()- return null- }- // The ref's hash is a producer-side per-team HMAC; this consumer doesn't hold the key and- // trusts the producer (the topic's only writer) that the key names these bytes.- const parsed = parseImageRef(ref)- if (!parsed) {- ImageScrubConsumerMetrics.incInvalidKey()- return null- }- const bytes = await this.scrubClient.scrub(m.value, signal)+ private async scrubOne(planned: PlannedScrub, signal: AbortSignal): Promise<ScrubbedImage | null> {+ const bytes = await this.scrubClient.scrub(planned.value, signal)if (bytes === null) {+ // Null is only ever a 422/413, a verdict on the content itself, so no retry can succeed.+ // Marking it stops every later copy from re-earning the same rejection, and there is+ // nothing pending to persist, so this needs none of the care the success path does.+ this.seenRefs.add(planned.ref)ImageScrubConsumerMetrics.incSkipped()return null}ImageScrubConsumerMetrics.incScrubbed()- return { pseudoTeam: parsed.pseudoTeam, hash: parsed.hash, bytes }+ return { pseudoTeam: planned.pseudoTeam, hash: planned.hash, bytes }}private overCapacity(): boolean {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 b397db563f76..9664cfa02464 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@@ -1,4 +1,4 @@-import { Counter } from 'prom-client'+import { Counter, Histogram } from 'prom-client'export class ImageScrubConsumerMetrics {private static readonly scrubbed = new Counter({@@ -9,6 +9,25 @@ export class ImageScrubConsumerMetrics {name: 'ml_mirror_image_scrub_consumer_skipped_total',help: 'Images skipped because the sidecar rejected them as undecodable (resolve to nothing)',})+ private static readonly deduped = new Counter({+ name: 'ml_mirror_image_scrub_consumer_deduped_total',+ help: 'Messages skipped as duplicate produces of a ref, by scope: "batch" (another copy in the same poll batch) or "pod" (this pod scrubbed it earlier). Dedup hit rate = deduped / (deduped + scrubbed + skipped); the batch/pod split says how much the retained seen-ref cache is earning over free intra-batch dedup',+ labelNames: ['scope'],+ })+ /**+ * Intra-batch dedup can only collapse copies that arrive in the same poll batch, so its ceiling is+ * set by how many messages a batch holds. Small batches are the one way it can be "undersized",+ * and unlike the seen-ref cache the fix is poll configuration rather than memory. Buckets stop at+ * the CONSUMER_BATCH_SIZE fetch cap, past which they could never be populated. This deliberately+ * excludes empty polls, which is what makes it readable where consumer-v1's own batch-size+ * histogram is not: that one samples before the empty check, and this lane runs with+ * callEachBatchWhenEmpty, so idle polls bury the real distribution in the lowest bucket.+ */+ private static readonly batchMessages = new Histogram({+ name: 'ml_mirror_image_scrub_consumer_batch_messages',+ help: 'Messages per non-empty poll batch. Read alongside deduped{scope="batch"}: consistently small batches cap how much intra-batch dedup can collapse, whatever the duplicate rate is',+ buckets: [1, 10, 50, 100, 200, 300, 400, 500],+ })private static readonly invalidKey = new Counter({name: 'ml_mirror_image_scrub_consumer_invalid_key_total',help: 'Messages dropped because the key is missing, not an image ref, or the value is empty — a sustained rate means producer/consumer ref-format drift is zeroing the lane',@@ -40,9 +59,15 @@ export class ImageScrubConsumerMetrics {public static incSkipped(): void {this.skipped.inc()}+ public static incDeduped(scope: 'batch' | 'pod'): void {+ this.deduped.labels(scope).inc()+ }public static incInvalidKey(): void {this.invalidKey.inc()}+ public static observeBatchMessages(count: number): void {+ this.batchMessages.observe(count)+ }public static observeShard(images: number, bytes: number): void {this.shardsWritten.inc()this.shardImages.inc(images)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.tsindex f849a56e100b..65002cb7ca4d 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts@@ -37,6 +37,24 @@ export type MlMirrorConfig = {// Real peak memory is ~2x this: the flush does a Buffer.concat copy.SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_BYTES: numberSESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_CONCURRENCY: number+ /**+ * Capacity of the consumer's per-pod seen-ref LRU. The topic is keyed by ref, so duplicates are+ * partition-affine and a per-pod cache dedupes them exactly up to this many refs. Budget ~200 B+ * per entry, of which lru-cache commits about an eighth up front by preallocating its backing+ * arrays. Sized against the 2000M consumer container in+ * https://github.com/PostHog/charts/blob/main/apps/ingestion-sessionreplay-ml-image-scrub/values.yaml,+ * which also has to hold MAX_BYTES of scrubbed images at ~2x during a flush. Start low and raise+ * it off ml_mirror_ref_cache_capacity_probe_total rather than guessing.+ *+ * 0 disables only this cross-batch cache; duplicates within a poll batch always collapse.+ */+ SESSION_RECORDING_ML_IMAGE_SCRUB_DEDUP_MAX_REFS: number+ /**+ * The mirror-side twin of the knob above, bounding re-produces onto the scrub topic. Tunable for+ * the same reason: it is a pure memory-for-throughput trade, and shedding it during a mirror+ * memory incident should not need a code deploy of the shared replay ingester.+ */+ SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCED_REF_CACHE_MAX: numberSESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_TIMEOUT_MS: numberSESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_RETRIES: number// Per-write timeout (the S3 client has no built-in one). A flush does two writes, so it bounds at 2x this.@@ -76,6 +94,8 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {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,+ SESSION_RECORDING_ML_IMAGE_SCRUB_DEDUP_MAX_REFS: 250_000,+ SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCED_REF_CACHE_MAX: 500_000,SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_TIMEOUT_MS: 10 * 1000,SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_RETRIES: 3,SESSION_RECORDING_ML_IMAGE_SCRUB_S3_WRITE_TIMEOUT_MS: 30 * 1000,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.tsindex 8ace48738e79..45d819ae14e3 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts@@ -35,6 +35,7 @@ export interface MlMirrorImageScrubProducer {outputs: IngestionOutputs<MlImageScrubOutput>/** The ML pseudonym HMAC key (also used by the block-metadata sink), for the per-team ref prefix. */pseudonymSecret: string | Buffer+ producedRefCacheMax: number}export function createMlMirrorReplayPipeline(@@ -153,7 +154,10 @@ export function createMlMirrorReplayPipeline()const withImagesProduced = imageScrub? parsed.pipe(- createProduceCollectedImagesStep(imageScrub.outputs)+ createProduceCollectedImagesStep(+ imageScrub.outputs,+ imageScrub.producedRefCacheMax+ )): parsedreturn withImagesProduced.pipe(diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.test.tsindex df02a0a68787..b656886fd08d 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.test.ts@@ -66,6 +66,20 @@ describe('produceCollectedImagesStep', () => {])})+ it('evicts oldest refs at capacity instead of forgetting the whole working set', async () => {+ const step = createProduceCollectedImagesStep(outputs, 2)+ await run(step, { collectedImages: [image('image:aa:h1'), image('image:aa:h2')] })+ await run(step, { collectedImages: [image('image:aa:h3')] })+ // Only h1 (the oldest) made room for h3; h2 must still dedup — a wholesale clear-on-full+ // would re-produce the entire hot working set every time the cap is hit.+ await run(step, { collectedImages: [image('image:aa:h2'), image('image:aa:h1')] })+ expect(queued.map((batch) => batch.map((m) => m.key))).toEqual([+ ['image:aa:h1', 'image:aa:h2'],+ ['image:aa:h3'],+ ['image:aa:h1'],+ ])+ })+it('swallows produce failures (a dangling ref reads as a placeholder downstream)', async () => {queueMessages.mockRejectedValueOnce(new Error('broker down'))const step = createProduceCollectedImagesStep(outputs)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.tsindex 9343bd97a876..e8ae939cd52f 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts@@ -5,14 +5,18 @@ import { ProcessingStep } from '~/ingestion/framework/steps'import { SessionRecordingIngesterMetrics } from '~/ingestion/pipelines/sessionreplay/metrics'import { CollectedImage } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'import { ML_IMAGE_SCRUB_OUTPUT, MlImageScrubOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'+import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'/**- * The Rust collector dedupes within one message; this bounds cross-message re-produces (the same- * sprite recurring in every snapshot of a session). Refs are ~60 bytes, so the ceiling is ~6 MB.- * Duplicates that slip past it are only wasted topic bytes — the consumer's S3 layout is keyed by- * hash, so re-produces are idempotent.+ * The Rust collector only dedupes within one message, leaving this as the sole thing between a hot+ * sprite and one produce per recurrence, so capacity translates directly into scrub-topic volume: a+ * ref evicted before its next sighting is re-produced and re-scrubbed. Budget ~200 B per entry (the+ * LRU's bookkeeping dominates the ~60 B ref), so this is ~100 MB against the 8000M mirror container+ * in https://github.com/PostHog/charts/blob/main/apps/ingestion-sessionreplay-ml-mirror/values.yaml,+ * which also holds the anonymizer's packed image buffers. Overflowing it costs topic bytes rather+ * than correctness, since the consumer dedupes by ref too.*/-const PRODUCED_REF_CACHE_MAX = 100_000+const PRODUCED_REF_CACHE_MAX = 500_000/*** Produce collected original images to the scrub topic as a fire-and-forget side effect, keyed by@@ -21,9 +25,10 @@ const PRODUCED_REF_CACHE_MAX = 100_000* is defined as equivalent to a placeholder for training joins.*/export function createProduceCollectedImagesStep<T extends { collectedImages?: CollectedImage[] }>(- outputs: IngestionOutputs<MlImageScrubOutput>+ outputs: IngestionOutputs<MlImageScrubOutput>,+ producedRefCacheMax: number = PRODUCED_REF_CACHE_MAX): ProcessingStep<T, T> {- const producedRefs = new Set<string>()+ const producedRefs = new RefDedupCache('image_scrub_producer', producedRefCacheMax)return function produceCollectedImagesStep(input) {const images = input.collectedImages@@ -37,9 +42,6 @@ export function createProduceCollectedImagesStep<T extends { collectedImages?: Creturn Promise.resolve(ok({ ...input, collectedImages: undefined }))}- if (producedRefs.size + fresh.length > PRODUCED_REF_CACHE_MAX) {- producedRefs.clear()- }let bytes = 0for (const image of fresh) {producedRefs.add(image.ref)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache.test.tsnew file mode 100644index 000000000000..e15b3135ffcc--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache.test.ts@@ -0,0 +1,72 @@+import { Counter, register } from 'prom-client'++import { RefDedupCache } from './ref-dedup-cache'++describe('RefDedupCache', () => {+ async function probe(cache: string, verdict: 'would_hit' | 'would_miss'): Promise<number> {+ const metric = register.getSingleMetric('ml_mirror_ref_cache_capacity_probe_total') as Counter | undefined+ const data = await metric?.get()+ const sample = data?.values.find((v) => v.labels.cache === cache && v.labels.verdict === verdict)+ return sample?.value ?? 0+ }++ it('separates misses a bigger cache would have caught from ones it would not', async () => {+ // The whole point of the probe is to tell "the working set does not fit" apart from "these+ // duplicates were always too far apart to cache". Both verdicts have to move: a probe stuck+ // on would_miss reads as a correctly sized cache and we stop looking, and one stuck on+ // would_hit sends us buying memory that buys nothing. Sample every ref so it is deterministic.+ const name = 'test_capacity_probe'+ const cache = new RefDedupCache(name, 2, 1)+ cache.add('a')+ cache.add('b')+ cache.add('c') // evicts 'a'++ expect(cache.has('a')).toBe(false)+ expect(await probe(name, 'would_hit')).toBe(1)++ expect(cache.has('never-seen')).toBe(false)+ expect(await probe(name, 'would_miss')).toBe(1)+ expect(await probe(name, 'would_hit')).toBe(1)+ })++ it('credits one eviction with one verdict, however often the evicted ref is probed', async () => {+ // Reading the ghost through `get` renews its recency, so a ref that is probed but never+ // re-added (the sidecar rejected it, or its produce failed) pins itself and scores would_hit+ // on every later batch. That inflates the ratio in the "buy more memory" direction, on the+ // one metric whose whole job is deciding whether to spend memory.+ const name = 'test_repeat_probe'+ const cache = new RefDedupCache(name, 2, 1)+ cache.add('a')+ cache.add('b')+ cache.add('c') // evicts 'a'++ for (let i = 0; i < 5; i++) {+ expect(cache.has('a')).toBe(false)+ }++ expect(await probe(name, 'would_hit')).toBe(1)+ expect(await probe(name, 'would_miss')).toBe(4)+ })++ it.each([+ ['a typo parsed to NaN', NaN],+ ['the source default copied verbatim, which parseFloat truncates', 1.5],+ ['a negative that would otherwise silently disable dedup', -1],+ ])('rejects %s at construction rather than at first use', (_case, max) => {+ // lru-cache throws on these too, but names neither the cache nor the knob, so the lane+ // crash-loops on a message an operator cannot act on.+ expect(() => new RefDedupCache('test_validation', max)).toThrow(/test_validation ref cache max/)+ })++ it('does not probe while the cache still has room, so an unfilled cache reads as sized correctly', async () => {+ // Evictions are the only thing that can put a ref in the ghost list, so a cache that never+ // fills must report no would_hit at all rather than blaming capacity for ordinary misses.+ const name = 'test_unfilled'+ const cache = new RefDedupCache(name, 100, 1)+ cache.add('a')++ expect(cache.has('b')).toBe(false)+ expect(await probe(name, 'would_hit')).toBe(0)+ expect(await probe(name, 'would_miss')).toBe(1)+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache.tsnew file mode 100644index 000000000000..8bc7e79a4f00--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache.ts@@ -0,0 +1,134 @@+import { LRUCache } from 'lru-cache'+import { Counter, Gauge } from 'prom-client'++/**+ * In sampled space the ghost list spans as many evictions as the cache holds entries, so a ghost hit+ * means a cache of twice the capacity would still have held that ref. Sampling keeps the diagnostic+ * near 6% of the cache's own memory, which is what makes it affordable to leave on across the fleet.+ */+const GHOST_SAMPLE_RATE = 16++const evictionsTotal = new Counter({+ name: 'ml_mirror_ref_cache_evictions_total',+ help: 'Refs dropped from a dedup cache to make room for newer ones',+ labelNames: ['cache'],+})++const capacityProbeTotal = new Counter({+ name: 'ml_mirror_ref_cache_capacity_probe_total',+ help: 'Sampled cache misses split by whether the ref was evicted recently enough that twice the capacity would still hold it. would_hit / (would_hit + would_miss) is the share of misses that doubling the cache would recover, so a value near zero means the cache is big enough and a high value means it is undersized',+ labelNames: ['cache', 'verdict'],+})++/** Read at scrape time by the entries gauge, which keeps the hot path free of a gauge write per ref. */+const liveCaches = new Map<string, RefDedupCache>()++// Never referenced again: constructing it registers it, and it pulls its own values at scrape time.+new Gauge({+ name: 'ml_mirror_ref_cache_entries',+ help: 'Refs currently held in a dedup cache. Below the capacity gauge means the cache has never filled, so it cannot be undersized',+ labelNames: ['cache'],+ collect() {+ for (const [name, cache] of liveCaches) {+ this.labels(name).set(cache.size)+ }+ },+})++const capacityGauge = new Gauge({+ name: 'ml_mirror_ref_cache_capacity',+ help: 'Configured maximum for a dedup cache, so utilization reads off the metrics instead of the deployed config',+ labelNames: ['cache'],+})++/** Independent of the ref format, so a change to how refs are built cannot skew which ones are sampled. */+function sampleBucket(ref: string): number {+ let hash = 0x811c9dc5+ for (let i = 0; i < ref.length; i++) {+ hash ^= ref.charCodeAt(i)+ hash = Math.imul(hash, 0x01000193)+ }+ return hash >>> 0+}++/**+ * An LRU of refs that reports whether its capacity is the thing limiting its hit rate.+ *+ * Hit rate alone cannot answer that: a low rate looks identical whether the duplicates are genuinely+ * far apart or merely further apart than the cache can reach. The ghost list separates the two, which+ * is the difference between buying hit rate with memory and wasting memory on a working set that was+ * never going to fit.+ */+export class RefDedupCache {+ private readonly cache: LRUCache<string, true> | null+ private readonly ghost: LRUCache<string, true> | null++ constructor(+ private readonly name: string,+ max: number,+ private readonly ghostSampleRate: number = GHOST_SAMPLE_RATE+ ) {+ // These arrive from env, where `overrideConfigWithEnv` parseFloats whatever it is given: the+ // source default is written `1_000_000`, which parses to 1, and a typo parses to NaN. Both+ // reach lru-cache as a `max` it rejects with an error naming neither the knob nor the cache.+ if (!Number.isInteger(max) || max < 0) {+ throw new Error(`${name} ref cache max must be 0 or a positive integer, got ${max}`)+ }+ liveCaches.set(name, this)+ capacityGauge.labels(name).set(max)+ if (max === 0) {+ this.cache = null+ this.ghost = null+ return+ }+ this.ghost = new LRUCache({ max: Math.max(1, Math.floor(max / ghostSampleRate)) })+ this.cache = new LRUCache({+ max,+ dispose: (_value, key, reason) => {+ if (reason !== 'evict') {+ return+ }+ evictionsTotal.labels(name).inc()+ if (this.isSampled(key)) {+ this.ghost?.set(key, true)+ }+ },+ })+ }++ public has(ref: string): boolean {+ if (!this.cache) {+ return false+ }+ if (this.cache.get(ref)) {+ return true+ }+ if (this.isSampled(ref)) {+ // peek, not get: reading through `get` would renew the ghost entry's own recency, letting+ // a ref that is probed but never re-added pin itself and score would_hit indefinitely.+ // Dropping it on a hit keeps one eviction worth exactly one verdict.+ const wouldHit = this.ghost?.peek(ref) === true+ if (wouldHit) {+ this.ghost?.delete(ref)+ }+ capacityProbeTotal.labels(this.name, wouldHit ? 'would_hit' : 'would_miss').inc()+ }+ return false+ }++ public add(ref: string): void {+ this.cache?.set(ref, true)+ }++ public delete(ref: string): void {+ this.cache?.delete(ref)+ }++ public get size(): number {+ return this.cache?.size ?? 0+ }++ private isSampled(ref: string): boolean {+ return sampleBucket(ref) % this.ghostSampleRate === 0+ }+}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 dc23177dded0..92ff276b0343 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@@ -82,6 +82,7 @@ export class IngestionSessionReplayMlImageScrubServer implements NodeServer {maxBytes: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_BYTES,scrubConcurrency: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_CONCURRENCY,maxBatchScrubMs: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_BATCH_SCRUB_MS,+ dedupMaxRefs: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_DEDUP_MAX_REFS,},Date.now())diff --git a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.tsindex 8b5ecef972d2..08a11f7942d9 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts@@ -166,7 +166,11 @@ export class IngestionSessionReplayMlMirrorServer implements NodeServer {),},this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED- ? { outputs, pseudonymSecret }+ ? {+ outputs,+ pseudonymSecret,+ producedRefCacheMax: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCED_REF_CACHE_MAX,+ }: undefined),// Isolate the mirror's session tracker/filter keys from the main lane. Sharing them would let