Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(ml-image-scrub): produce original images to the scrub topic from the ml-mirror (#70308)

Robbie6a32c7451753
diff --git a/.github/workflows/ci-nodejs.yml b/.github/workflows/ci-nodejs.yml
index d7dc36e1de98..e24ed8bbc532 100644
--- a/.github/workflows/ci-nodejs.yml
+++ b/.github/workflows/ci-nodejs.yml
@@ -239,7 +239,9 @@ jobs:
name: Node.js Tests ${{matrix.shard}}/3 (depot-ubuntu-24.04-4)
needs: changes
runs-on: depot-ubuntu-24.04-4
- timeout-minutes: 30 # We know tests don't take this long
+ # Tests fit comfortably in 30, but a rust change misses the turbo cache and cold-builds the
+ # replay-anonymizer addon's whole dependency tree first (no rust caching in this job yet).
+ timeout-minutes: 45
strategy:
fail-fast: false
matrix:
diff --git a/nodejs/src/common/outputs/kafka-producer-config.ts b/nodejs/src/common/outputs/kafka-producer-config.ts
index 2ae3756f885d..33f0aa33f86c 100644
--- a/nodejs/src/common/outputs/kafka-producer-config.ts
+++ b/nodejs/src/common/outputs/kafka-producer-config.ts
@@ -31,6 +31,8 @@ const producerConfigSchema = z.object({
.default('true')
.transform((v) => v === 'true'),
'message.max.bytes': z.coerce.number().optional(),
+ // Topic-level property: librdkafka applies it to the default topic conf when set globally.
+ 'message.timeout.ms': z.coerce.number().optional(),
'batch.num.messages': z.coerce.number().optional(),
'sticky.partitioning.linger.ms': z.coerce.number().optional(),
'topic.metadata.refresh.interval.ms': z.coerce.number().optional(),
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/config.ts
index 416d709f659d..3c354ba40ee2 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/config.ts
@@ -8,12 +8,15 @@ import {
KAFKA_SESSION_RECORDING_SNAPSHOT_ITEM_DLQ,
KAFKA_SESSION_RECORDING_SNAPSHOT_ITEM_EVENTS,
KAFKA_SESSION_RECORDING_SNAPSHOT_ITEM_OVERFLOW,
+ KAFKA_SESSION_REPLAY_IMAGE_SCRUB,
KAFKA_SESSION_REPLAY_ML_BLOCK_METADATA,
} from '~/common/config/kafka-topics'
import { isDevEnv } from '~/common/utils/env-utils'
import { INGESTION_DOWNSTREAM_PRODUCER, type IngestionDownstreamProducer } from '~/ingestion/common/outputs/producers'
import {
+ INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER,
INGESTION_SESSIONREPLAY_PRODUCER,
+ type IngestionSessionreplayMlImageScrubProducer,
type IngestionSessionreplayProducer,
} from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'
@@ -24,7 +27,10 @@ import { KAFKA_CONSUMER_GROUP_ID as SESSION_RECORDING_DEFAULT_GROUP_ID } from '.
* common) for ClickHouse-bound outputs, and SESSIONREPLAY (warpstream-replay, defined in the
* session-replay folder) for replay-domain topics.
*/
-export type SessionReplayProducerName = IngestionDownstreamProducer | IngestionSessionreplayProducer
+export type SessionReplayProducerName =
+ | IngestionDownstreamProducer
+ | IngestionSessionreplayProducer
+ | IngestionSessionreplayMlImageScrubProducer
export type SessionRecordingApiConfig = {
SESSION_RECORDING_API_REDIS_HOST: string
@@ -184,6 +190,9 @@ export type SessionReplayOutputsConfig = {
INGESTION_SESSIONREPLAY_OUTPUT_ML_BLOCK_METADATA_TOPIC: string
INGESTION_SESSIONREPLAY_OUTPUT_ML_BLOCK_METADATA_PRODUCER: SessionReplayProducerName
+
+ INGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_SCRUB_TOPIC: string
+ INGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_SCRUB_PRODUCER: SessionReplayProducerName
}
export function getDefaultSessionReplayOutputsConfig(): SessionReplayOutputsConfig {
@@ -205,5 +214,7 @@ export function getDefaultSessionReplayOutputsConfig(): SessionReplayOutputsConf
INGESTION_SESSIONREPLAY_OUTPUT_SESSION_FEATURES_PRODUCER: INGESTION_SESSIONREPLAY_PRODUCER,
INGESTION_SESSIONREPLAY_OUTPUT_ML_BLOCK_METADATA_TOPIC: KAFKA_SESSION_REPLAY_ML_BLOCK_METADATA,
INGESTION_SESSIONREPLAY_OUTPUT_ML_BLOCK_METADATA_PRODUCER: INGESTION_SESSIONREPLAY_PRODUCER,
+ INGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_SCRUB_TOPIC: KAFKA_SESSION_REPLAY_IMAGE_SCRUB,
+ INGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_SCRUB_PRODUCER: INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER,
}
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
index cc89f02b1441..62e8618ac308 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
@@ -9,6 +9,8 @@ export type MlAnonymizeImpl = 'rust' | 'ts'
/** Rust engine that produced the output (tree = the parse fallback fired). `''` when not applicable. */
export type MlAnonymizeRoute = 'stream' | 'tree' | ''
+export type MlImageLaneStage = 'collected' | 'deduped' | 'queued' | 'produced' | 'produce_failed'
+
export class SessionRecordingIngesterMetrics {
private static readonly sessionsHandled = new Gauge({
name: 'recording_blob_ingestion_v2_session_manager_count',
@@ -75,6 +77,22 @@ export class SessionRecordingIngesterMetrics {
labelNames: ['impl'],
})
+ private static readonly mlImagesCollected = new Counter({
+ name: 'recording_blob_ingestion_v2_ml_images_collected',
+ help: 'Images through the out-of-band scrub lane, by stage: collected (returned by the addon), deduped (suppressed by the cross-message cache), queued (handed to the producer), produced (delivery acked), produce_failed (delivery failed; refs un-marked for natural retry)',
+ labelNames: ['outcome'],
+ })
+
+ private static readonly mlImageBytesProduced = new Counter({
+ name: 'recording_blob_ingestion_v2_ml_image_bytes_produced',
+ help: 'Bytes of collected images delivered to the scrub topic (acked)',
+ })
+
+ private static readonly mlImagePseudoTeamInvalid = new Counter({
+ name: 'recording_blob_ingestion_v2_ml_image_pseudo_team_invalid',
+ help: 'Messages whose derived team pseudonym failed the consumer ref-shape check; collection disabled for them (inline blur instead)',
+ })
+
public static incrementMessageReceived(partition: number): void {
this.messageReceived.labels(partition.toString()).inc()
}
@@ -119,4 +137,16 @@ export class SessionRecordingIngesterMetrics {
public static incrementMlAnonymizeFailed(impl: MlAnonymizeImpl): void {
this.mlAnonymizeFailed.labels(impl).inc()
}
+
+ public static incrementMlImagesCollected(outcome: MlImageLaneStage, count: number): void {
+ this.mlImagesCollected.labels(outcome).inc(count)
+ }
+
+ public static incrementMlImageBytesProduced(bytes: number): void {
+ this.mlImageBytesProduced.inc(bytes)
+ }
+
+ public static incrementMlImagePseudoTeamInvalid(): void {
+ this.mlImagePseudoTeamInvalid.inc()
+ }
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref.ts
index fa58996c3306..cdd80b2348ee 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref.ts
@@ -1,12 +1,17 @@
-// The shared key between the producer, this consumer, and training joins; pseudo_team is the non-reversible
-// HMAC team pseudonym from ml-mirror/pseudonymize.ts (keeps raw team ids out of the ML bucket).
-import { createHash } from 'node:crypto'
+// The shared ref format between the producer, this consumer, and training joins; pseudo_team is the
+// non-reversible HMAC team pseudonym from ml-mirror/pseudonymize.ts (keeps raw team ids out of the
+// ML bucket). The hash half is keyed (per-team HMAC, derived alongside the pseudonym) so the
+// unencrypted bucket carries no unkeyed content digest — a plain sha256 would let a bucket reader
+// confirm whether specific known bytes appeared in a session, and correlate identical images across
+// teams. The consumer trusts the producer's ref (it is the only writer) and never recomputes the
+// hash; the Rust producer implementation is pinned to this one by the shared image-hash.json fixture.
+import { createHmac } from 'node:crypto'
const PREFIX = 'image'
const REF_RE = /^image:([0-9a-f]{32}):([A-Za-z0-9_-]{22})$/
-export function hashImageBytes(bytes: Buffer): string {
- return createHash('sha256').update(bytes).digest('base64url').slice(0, 22)
+export function hashImageBytes(contentKey: string | Buffer, bytes: Buffer): string {
+ return createHmac('sha256', contentKey).update(bytes).digest('base64url').slice(0, 22)
}
export function imageRef(pseudoTeam: string, hash: string): string {
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.ts
index eb254e9fda17..da86c3b8dd5c 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
@@ -1,4 +1,4 @@
-import { Message } from 'node-rdkafka'
+import { Message, TopicPartitionOffset } from 'node-rdkafka'
import { hashImageBytes, imageRef } from './content-ref'
import { ImageBatcher, OffsetStore } from './image-batcher'
@@ -6,9 +6,10 @@ import { ImageShardStore, ScrubbedImage } from './image-shard-store'
import { ScrubClient } from './scrub-client'
const pt = (n: number): string => String(n).padStart(32, '0')
+const CONTENT_KEY = 'fedcba9876543210fedcba9876543210'
function msg(partition: number, offset: number, pseudoTeam: string, bytes: Buffer, keyOverride?: string): Message {
- const ref = keyOverride ?? imageRef(pseudoTeam, hashImageBytes(bytes))
+ const ref = keyOverride ?? imageRef(pseudoTeam, hashImageBytes(CONTENT_KEY, bytes))
return {
topic: 'session_replay_image_scrub',
partition,
@@ -33,8 +34,10 @@ class FakeStore {
class FakeOffsets implements OffsetStore {
public stored = 0
- offsetsStore(): void {
+ public received: TopicPartitionOffset[][] = []
+ offsetsStore(offsets: TopicPartitionOffset[]): void {
this.stored += 1
+ this.received.push(offsets)
}
}
@@ -62,7 +65,9 @@ describe('ImageBatcher', () => {
expect(offsets.stored).toBe(1)
})
- it('drops a key/content mismatch without buffering it', async () => {
+ it('trusts the producer ref: the bytes are indexed under the key hash without recomputing it', async () => {
+ // 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,
@@ -72,10 +77,11 @@ describe('ImageBatcher', () => {
0
)
- const forged = imageRef(pt(1), hashImageBytes(Buffer.from('other')))
- await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'), forged)], 1)
+ 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)
- expect(store.writes).toHaveLength(0)
+ expect(store.writes).toHaveLength(1)
+ expect(store.writes[0][0].hash).toBe(ref.split(':')[2])
})
it('does not store offsets when the shard write fails (at-least-once replay)', async () => {
@@ -88,6 +94,98 @@ describe('ImageBatcher', () => {
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
+ // writes another duplicate shard — unbounded write amplification an attacker can induce.
+ const store = new FakeStore()
+ const offsets = new FakeOffsets()
+ let scrubs = 0
+ const failsAfterFirstChunk = {
+ scrub: () => {
+ scrubs += 1
+ 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 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')
+
+ expect(store.writes).toHaveLength(1)
+ // The flushed 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 () => {
+ // 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.
+ 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 messages = Array.from({ length: 6 }, (_, i) => msg(0, i, pt(1), Buffer.from(`img-${i}`)))
+ await batcher.handleBatch(messages, 1)
+
+ 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 () => {
+ // 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.
+ const slowStore = new FakeStore()
+ const writeShard = slowStore.writeShard.bind(slowStore)
+ slowStore.writeShard = async (images) => {
+ await new Promise((resolve) => setTimeout(resolve, 80))
+ return writeShard(images)
+ }
+ const offsets = new FakeOffsets()
+ const batcher = new ImageBatcher(
+ slowStore as unknown as ImageShardStore,
+ offsets,
+ { scrub: () => Promise.resolve(Buffer.alloc(16)) } as unknown as ScrubClient,
+ { ...options, maxBytes: 32, scrubConcurrency: 2, maxBatchScrubMs: 60 },
+ 0
+ )
+
+ const messages = Array.from({ length: 6 }, (_, i) => msg(0, i, pt(1), Buffer.from(`img-${i}`)))
+ await batcher.handleBatch(messages, 1)
+
+ expect(slowStore.writes.flat()).toHaveLength(6)
+ expect(offsets.stored).toBe(slowStore.writes.length)
+ })
+
+ 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.
+ expect(
+ () =>
+ new ImageBatcher(
+ new FakeStore() as unknown as ImageShardStore,
+ new FakeOffsets(),
+ scrubClient,
+ { ...options, scrubConcurrency },
+ 0
+ )
+ ).toThrow('scrubConcurrency')
+ })
+
it('aborts the batch and replays when scrubbing exceeds the deadline', async () => {
const store = new FakeStore()
const offsets = new FakeOffsets()
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.ts
index 2a822fd3ce95..5931dcd98fe3 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
@@ -3,7 +3,7 @@ import { Message, TopicPartitionOffset } from 'node-rdkafka'
import { findOffsetsToCommit } from '~/common/kafka/consumer/consumer-v1'
import { ConcurrencyController } from '~/common/utils/concurrencyController'
-import { hashImageBytes, isImageRef, parseImageRef } from './content-ref'
+import { isImageRef, parseImageRef } from './content-ref'
import { ImageShardStore, ScrubbedImage } from './image-shard-store'
import { ImageScrubConsumerMetrics } from './metrics'
import { ScrubClient } from './scrub-client'
@@ -25,6 +25,7 @@ export class ImageBatcher {
private bufferBytes = 0
private pendingOffsets = new Map<string, TopicPartitionOffset>()
private lastFlushMs: number
+ private readonly chunkSize: number
private readonly scrubConcurrency: ConcurrencyController
constructor(
@@ -34,39 +35,64 @@ export class ImageBatcher {
private readonly options: ImageBatcherOptions,
nowMs: number
) {
+ // The concurrency doubles as the chunk stride below; 0 would spin the loop forever and NaN
+ // would skip it entirely (committing offsets for unprocessed messages), so fail at boot.
+ this.chunkSize = Math.floor(options.scrubConcurrency)
+ if (!Number.isInteger(this.chunkSize) || this.chunkSize < 1) {
+ throw new Error(`scrubConcurrency must be a positive number, got ${options.scrubConcurrency}`)
+ }
this.lastFlushMs = nowMs
- this.scrubConcurrency = new ConcurrencyController(options.scrubConcurrency)
+ this.scrubConcurrency = new ConcurrencyController(this.chunkSize)
}
public async handleBatch(messages: Message[], nowMs: number): Promise<void> {
- let scrubbed: ScrubbedImage[]
- try {
- scrubbed = await this.scrubBatch(messages)
- } catch (e) {
- ImageScrubConsumerMetrics.incBatchFailed('scrub')
- throw e
- }
- for (const image of scrubbed) {
- this.buffer.push(image)
- this.bufferBytes += image.bytes.length
- }
- // Advance offsets even for all-skipped batches, or skipped messages replay forever.
- for (const offset of findOffsetsToCommit(messages)) {
- this.pendingOffsets.set(`${offset.topic}:${offset.partition}`, offset)
- }
- if (this.shouldFlush(nowMs)) {
+ // 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
+ // gigabytes. Peak memory is now ~maxBytes plus one chunk's outputs.
+ //
+ // The deadline covers scrub time only: the timer is armed per chunk with the remaining
+ // budget and disarmed before any mid-batch flush, so slow-but-succeeding S3 writes (each
+ // bounded by their own timeout) can't burn the scrub budget and turn into an abort/replay
+ // 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)
+ const chunkStartMs = performance.now()
+ const timer = setTimeout(() => controller.abort(), scrubBudgetMs)
+ let scrubbed: ScrubbedImage[]
try {
- await this.flush(nowMs)
+ scrubbed = await this.scrubChunk(chunk, controller)
} catch (e) {
- ImageScrubConsumerMetrics.incBatchFailed('write')
+ ImageScrubConsumerMetrics.incBatchFailed('scrub')
throw e
+ } finally {
+ clearTimeout(timer)
+ }
+ scrubBudgetMs -= performance.now() - chunkStartMs
+ for (const image of scrubbed) {
+ this.buffer.push(image)
+ this.bufferBytes += image.bytes.length
+ }
+ // 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)
+ }
+ if (this.overCapacity()) {
+ await this.flushOrThrow(nowMs)
}
}
+ if (this.shouldFlush(nowMs)) {
+ await this.flushOrThrow(nowMs)
+ }
}
- private async scrubBatch(messages: Message[]): Promise<ScrubbedImage[]> {
- const controller = new AbortController()
- const timer = setTimeout(() => controller.abort(), this.options.maxBatchScrubMs)
+ private async scrubChunk(messages: Message[], controller: AbortController): Promise<ScrubbedImage[]> {
try {
const scrubbed = await Promise.all(
messages.map((m) =>
@@ -80,19 +106,29 @@ export class ImageBatcher {
} catch (e) {
controller.abort() // one failure dooms the batch, so cancel the siblings still in flight
throw e
- } finally {
- clearTimeout(timer)
+ }
+ }
+
+ private async flushOrThrow(nowMs: number): Promise<void> {
+ try {
+ await this.flush(nowMs)
+ } catch (e) {
+ ImageScrubConsumerMetrics.incBatchFailed('write')
+ throw e
}
}
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 || hashImageBytes(m.value) !== parsed.hash) {
- ImageScrubConsumerMetrics.incMismatch()
+ if (!parsed) {
+ ImageScrubConsumerMetrics.incInvalidKey()
return null
}
const bytes = await this.scrubClient.scrub(m.value, signal)
@@ -104,8 +140,12 @@ export class ImageBatcher {
return { pseudoTeam: parsed.pseudoTeam, hash: parsed.hash, bytes }
}
+ private overCapacity(): boolean {
+ return this.buffer.length >= this.options.maxImages || this.bufferBytes >= this.options.maxBytes
+ }
+
private shouldFlush(nowMs: number): boolean {
- if (this.buffer.length >= this.options.maxImages || this.bufferBytes >= this.options.maxBytes) {
+ if (this.overCapacity()) {
return true
}
const hasPending = this.buffer.length > 0 || this.pendingOffsets.size > 0
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.ts
index 88eb158922e3..b397db563f76 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
@@ -9,9 +9,9 @@ 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 mismatch = new Counter({
- name: 'ml_mirror_image_scrub_consumer_key_content_mismatch_total',
- help: 'Messages dropped because the key hash did not match the value bytes (forged/corrupt key)',
+ 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',
})
private static readonly shardsWritten = new Counter({
name: 'ml_mirror_image_scrub_consumer_shards_written_total',
@@ -40,8 +40,8 @@ export class ImageScrubConsumerMetrics {
public static incSkipped(): void {
this.skipped.inc()
}
- public static incMismatch(): void {
- this.mismatch.inc()
+ public static incInvalidKey(): void {
+ this.invalidKey.inc()
}
public static observeShard(images: number, bytes: number): void {
this.shardsWritten.inc()
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
index b95256b9a28a..f849a56e100b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
@@ -23,6 +23,12 @@ export type MlMirrorConfig = {
/** Row cap that forces a flush before the interval elapses (bounds the sink's memory). */
SESSION_RECORDING_ML_PARQUET_MAX_ROWS: number
+ /**
+ * Produce collected original images to the scrub topic. Enabling changes the mirrored JSONL
+ * shape: image fields carry `image:<pseudoTeam>:<hash>` refs instead of blurred data URIs, so
+ * both the scrub consumer lane AND ref-aware downstream readers must be live first.
+ */
+ SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED: boolean
SESSION_RECORDING_ML_IMAGE_SCRUB_GROUP_ID: string
SESSION_RECORDING_ML_IMAGE_SCRUB_PREFIX: string
SESSION_RECORDING_ML_IMAGE_SCRUB_SIDECAR_URL: string
@@ -35,8 +41,10 @@ export type MlMirrorConfig = {
SESSION_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.
SESSION_RECORDING_ML_IMAGE_SCRUB_S3_WRITE_TIMEOUT_MS: number
- // Scrub-phase budget. Sized so scrub + 2x the S3 write timeout stays under Kafka's max.poll.interval.ms
- // (300s), or a hung sidecar/S3 evicts us mid-batch and livelocks.
+ // Scrub-phase budget, covering scrub time only — mid-batch flush time is excluded (each flush is
+ // separately bounded at 2x the S3 write timeout). Sized so scrub plus the worst-case flushes for
+ // one poll batch stays under Kafka's max.poll.interval.ms (300s), or a hung sidecar/S3 evicts us
+ // mid-batch and livelocks.
SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_BATCH_SCRUB_MS: number
/**
@@ -59,6 +67,7 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {
SESSION_RECORDING_ML_PARQUET_SINK_GROUP_ID: 'session-replay-ml-parquet-sink',
SESSION_RECORDING_ML_PARQUET_FLUSH_INTERVAL_MS: 60 * 1000,
SESSION_RECORDING_ML_PARQUET_MAX_ROWS: 250_000,
+ SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED: false,
SESSION_RECORDING_ML_IMAGE_SCRUB_GROUP_ID: 'session-replay-ml-image-scrub',
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.
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.ts
index a02193d2dadf..8ace48738e79 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
@@ -1,5 +1,6 @@
/** The primary session replay pipeline plus an AI-training opt-in filter and an anonymize step. */
import { OverflowOutput } from '~/common/outputs'
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { createApplyEventRestrictionsStep, createParseHeadersStep } from '~/ingestion/common/steps/event-preprocessing'
import { newBatchingPipeline } from '~/ingestion/framework/builders'
import { createTopHogWrapper, sum, timer } from '~/ingestion/framework/extensions/tophog'
@@ -12,6 +13,7 @@ import {
SessionReplayPipelineOutput,
} from '~/ingestion/pipelines/sessionreplay'
import { createAiTrainingOptInFilterStep } from '~/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step'
+import { createProduceCollectedImagesStep } from '~/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step'
import { createParseAndAnonymizeMessageStep } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'
import { MessageContext } from '~/ingestion/pipelines/sessionreplay/pipeline-types'
import { createRecordSessionEventStep } from '~/ingestion/pipelines/sessionreplay/record-session-event-step'
@@ -19,6 +21,7 @@ import { createMarkSeenStep } from '~/ingestion/pipelines/sessionreplay/session-
import { createResolveRetentionStep } from '~/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step'
import { createTrackAndGateStep } from '~/ingestion/pipelines/sessionreplay/session-batch-track-and-gate-step'
import { createResolveKeyStep } from '~/ingestion/pipelines/sessionreplay/session-resolve-key-step'
+import { MlImageScrubOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
import { createTeamFilterStep } from '~/ingestion/pipelines/sessionreplay/team-filter-step'
import { createValidateSessionReplayHeadersStep } from '~/ingestion/pipelines/sessionreplay/validate-headers-step'
@@ -27,9 +30,17 @@ export interface MlMirrorPipelineOptions {
anonymizeMaxConcurrency: number
}
+/** Enables the image-collection lane: inlined images become refs, originals go to the scrub topic. */
+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
+}
+
export function createMlMirrorReplayPipeline(
config: SessionReplayPipelineConfig,
- mlOptions: MlMirrorPipelineOptions
+ mlOptions: MlMirrorPipelineOptions,
+ imageScrub?: MlMirrorImageScrubProducer
): SessionReplayPipeline {
const {
outputs,
@@ -126,14 +137,26 @@ export function createMlMirrorReplayPipeline(
(b) => {
// The native Rust addon fuses parse+anonymize in one step.
const parsed = b.pipe(
- topHogWrapper(createParseAndAnonymizeMessageStep(), [
- timer('parse_time_ms_by_session_id', (input) => ({
- token: input.headers.token ?? 'unknown',
- session_id: input.headers.session_id ?? 'unknown',
- })),
- ])
+ topHogWrapper(
+ createParseAndAnonymizeMessageStep(
+ imageScrub && {
+ pseudonymSecret: imageScrub.pseudonymSecret,
+ }
+ ),
+ [
+ timer('parse_time_ms_by_session_id', (input) => ({
+ token: input.headers.token ?? 'unknown',
+ session_id: input.headers.session_id ?? 'unknown',
+ })),
+ ]
+ )
)
- return parsed.pipe(
+ const withImagesProduced = imageScrub
+ ? parsed.pipe(
+ createProduceCollectedImagesStep(imageScrub.outputs)
+ )
+ : parsed
+ return withImagesProduced.pipe(
topHogWrapper(
createRecordSessionEventStep({
isDebugLoggingEnabled,
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.ts
new file mode 100644
index 000000000000..df02a0a68787
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.test.ts
@@ -0,0 +1,86 @@
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import { PipelineResultType } from '~/ingestion/framework/results'
+import { CollectedImage } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'
+import { MlImageScrubOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
+
+import { createProduceCollectedImagesStep } from './produce-collected-images-step'
+
+describe('produceCollectedImagesStep', () => {
+ let queued: { key: string; value: Buffer }[][]
+ let outputs: IngestionOutputs<MlImageScrubOutput>
+ let queueMessages: jest.Mock
+
+ beforeEach(() => {
+ queued = []
+ queueMessages = jest.fn((_output: string, messages: { key: string; value: Buffer }[]) => {
+ queued.push(messages)
+ return Promise.resolve()
+ })
+ outputs = { queueMessages } as unknown as IngestionOutputs<MlImageScrubOutput>
+ })
+
+ function image(ref: string, byte = 1): CollectedImage {
+ return { ref, bytes: Buffer.from([byte]) }
+ }
+
+ async function run<T extends { collectedImages?: CollectedImage[] }>(
+ step: ReturnType<typeof createProduceCollectedImagesStep<T>>,
+ input: T
+ ) {
+ const result = await step(input)
+ if (result.type !== PipelineResultType.OK) {
+ throw new Error(`expected ok, got ${result.type}`)
+ }
+ await Promise.all(result.sideEffects)
+ return result
+ }
+
+ it('produces each image keyed by its ref as a side effect and strips them from the element', async () => {
+ const step = createProduceCollectedImagesStep(outputs)
+ const images = [image('image:aa:h1', 1), image('image:aa:h2', 2)]
+ const result = await run(step, { collectedImages: images })
+
+ expect(result.value.collectedImages).toBeUndefined()
+ expect(queued).toEqual([
+ [
+ { key: 'image:aa:h1', value: Buffer.from([1]) },
+ { key: 'image:aa:h2', value: Buffer.from([2]) },
+ ],
+ ])
+ })
+
+ it('passes through elements with no collected images without producing', async () => {
+ const step = createProduceCollectedImagesStep(outputs)
+ await run(step, { collectedImages: undefined })
+ await run(step, { collectedImages: [] })
+ expect(queueMessages).not.toHaveBeenCalled()
+ })
+
+ it('dedups refs it already produced across messages', async () => {
+ const step = createProduceCollectedImagesStep(outputs)
+ await run(step, { collectedImages: [image('image:aa:h1')] })
+ await run(step, { collectedImages: [image('image:aa:h1'), image('image:aa:h2')] })
+ expect(queued).toEqual([
+ [{ key: 'image:aa:h1', value: Buffer.from([1]) }],
+ [{ key: 'image:aa:h2', value: Buffer.from([1]) }],
+ ])
+ })
+
+ it('swallows produce failures (a dangling ref reads as a placeholder downstream)', async () => {
+ queueMessages.mockRejectedValueOnce(new Error('broker down'))
+ const step = createProduceCollectedImagesStep(outputs)
+ const result = await run(step, { collectedImages: [image('image:aa:h1')] })
+ expect(result.type).toBe(PipelineResultType.OK)
+ })
+
+ it('un-marks refs whose produce failed so a recurring image re-produces naturally', async () => {
+ queueMessages.mockRejectedValueOnce(new Error('broker down'))
+ const step = createProduceCollectedImagesStep(outputs)
+ await run(step, { collectedImages: [image('image:aa:h1')] })
+ await run(step, { collectedImages: [image('image:aa:h1')] })
+ expect(queueMessages).toHaveBeenCalledTimes(2)
+ // Once a produce succeeds, the ref dedups again.
+ await run(step, { collectedImages: [image('image:aa:h1')] })
+ expect(queueMessages).toHaveBeenCalledTimes(2)
+ })
+})
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.ts
new file mode 100644
index 000000000000..9343bd97a876
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts
@@ -0,0 +1,78 @@
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import { logger } from '~/common/utils/logger'
+import { ok } from '~/ingestion/framework/results'
+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'
+
+/**
+ * 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.
+ */
+const PRODUCED_REF_CACHE_MAX = 100_000
+
+/**
+ * Produce collected original images to the scrub topic as a fire-and-forget side effect, keyed by
+ * their `image:<pseudoTeam>:<hash>` ref. Delivery is deliberately not awaited and never blocks or
+ * fails the message: the mirrored lines already carry the refs, and a ref whose image never lands
+ * is defined as equivalent to a placeholder for training joins.
+ */
+export function createProduceCollectedImagesStep<T extends { collectedImages?: CollectedImage[] }>(
+ outputs: IngestionOutputs<MlImageScrubOutput>
+): ProcessingStep<T, T> {
+ const producedRefs = new Set<string>()
+
+ return function produceCollectedImagesStep(input) {
+ const images = input.collectedImages
+ if (!images?.length) {
+ return Promise.resolve(ok(input))
+ }
+
+ const fresh = images.filter((image) => !producedRefs.has(image.ref))
+ SessionRecordingIngesterMetrics.incrementMlImagesCollected('deduped', images.length - fresh.length)
+ if (fresh.length === 0) {
+ return Promise.resolve(ok({ ...input, collectedImages: undefined }))
+ }
+
+ if (producedRefs.size + fresh.length > PRODUCED_REF_CACHE_MAX) {
+ producedRefs.clear()
+ }
+ let bytes = 0
+ for (const image of fresh) {
+ producedRefs.add(image.ref)
+ bytes += image.bytes.length
+ }
+ SessionRecordingIngesterMetrics.incrementMlImagesCollected('queued', fresh.length)
+
+ // The ack handlers must capture only the refs: `image.bytes` are subarray views into the
+ // whole packed FFI buffer (up to 32 MB per source message), and queueMessages copies the
+ // slices synchronously — a closure holding `fresh` would pin the full packed buffer per
+ // in-flight produce, unbounded by the producer queue's byte accounting.
+ const refs = fresh.map((image) => image.ref)
+ const produce = outputs
+ .queueMessages(
+ ML_IMAGE_SCRUB_OUTPUT,
+ fresh.map((image) => ({ key: image.ref, value: image.bytes }))
+ )
+ .then(() => {
+ // queueMessages resolves on delivery acks, so `produced` counts what actually landed.
+ SessionRecordingIngesterMetrics.incrementMlImagesCollected('produced', refs.length)
+ SessionRecordingIngesterMetrics.incrementMlImageBytesProduced(bytes)
+ })
+ .catch((error) => {
+ // A dangling ref reads as a placeholder downstream, so a failed produce is logged,
+ // never re-thrown into the pipeline. Un-mark the refs: the same image recurring in
+ // a later snapshot then re-produces naturally (one attempt per recurrence, no retry
+ // loop), and duplicates are idempotent downstream (S3 keyed by hash).
+ for (const ref of refs) {
+ producedRefs.delete(ref)
+ }
+ logger.warn('🖼️', 'ml_image_scrub_produce_failed', { count: refs.length, error: String(error) })
+ SessionRecordingIngesterMetrics.incrementMlImagesCollected('produce_failed', refs.length)
+ })
+ return Promise.resolve(ok({ ...input, collectedImages: undefined }, [produce]))
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts
index 132a0a90d9e5..2aa12cf6fc5a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts
@@ -13,5 +13,7 @@ export function pseudonymize(secret: string | Buffer, namespace: string, value:
}
export const PSEUDONYM_TEAM = 'team'
+/** Namespace for the per-team image content-HMAC key (see ml-mirror-image-scrub/content-ref.ts). */
+export const PSEUDONYM_IMAGE_CONTENT_KEY = 'image-content-key'
export const PSEUDONYM_SESSION = 'session'
export const PSEUDONYM_DISTINCT_ID = 'distinct_id'
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts
index 49a9a5927244..b0215d98b739 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts
@@ -4,6 +4,12 @@ import { gzipSync, zstdDecompressSync } from 'zlib'
import { parseJSON } from '~/common/utils/json-parse'
import { logger } from '~/common/utils/logger'
+import {
+ hashImageBytes,
+ imageRef,
+ isImageRef,
+ parseImageRef,
+} from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'
// Shared fixtures pin the addon's behavior through the FFI; the pure-Rust side of the same
// fixtures is covered by rust/replay-anonymizer/tests/parity.rs.
@@ -211,3 +217,96 @@ describeAddon('native rust addon matches the shared fixtures', () => {
})
})
})
+
+describe('image content hash matches the shared fixtures', () => {
+ // Pins the keyed hashImageBytes to the Rust collector's HMAC (tests/parity.rs runs the same
+ // fixture): the consumer trusts the producer, so this is the only cross-implementation check.
+ interface HashCase {
+ name: string
+ keyAscii: string
+ bytesBase64: string
+ hash: string
+ }
+ test.each(load<HashCase>('image-hash.json').map((c) => [c.name, c] as const))('hash: %s', (_name, c) => {
+ expect(hashImageBytes(c.keyAscii, Buffer.from(c.bytesBase64, 'base64'))).toBe(c.hash)
+ })
+})
+
+describeAddon('native image collection', () => {
+ // A 16x16 PNG; any valid raster image works, the assertions only rely on byte identity.
+ const PNG_B64 =
+ 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAJUlEQVQokWN4plEBRyInbOAIlzjDINRAjCJk8cGoYRAG60iMBwA8H08Qor0ygQAAAABJRU5ErkJggg=='
+ const PSEUDO_TEAM = '0123456789abcdef0123456789abcdef'
+ const CONTENT_KEY = 'fedcba9876543210fedcba9876543210'
+
+ function imagePayload(): Buffer {
+ const inner = JSON.stringify({
+ event: '$snapshot_items',
+ properties: {
+ $snapshot_items: [
+ {
+ type: 2,
+ timestamp: 1_700_000_000_000,
+ data: {
+ node: {
+ type: 0,
+ childNodes: [
+ {
+ type: 2,
+ tagName: 'img',
+ attributes: { src: `data:image/png;base64,${PNG_B64}` },
+ childNodes: [],
+ },
+ ],
+ },
+ initialOffset: { top: 0, left: 0 },
+ },
+ },
+ ],
+ $session_id: 's-1',
+ $window_id: 'w',
+ },
+ })
+ return Buffer.from(JSON.stringify({ distinct_id: 'd-1', data: inner }))
+ }
+
+ it('replaces the image with a consumer-parseable ref and returns the original bytes', async () => {
+ rustAddon!.initAnonymizer({ text: [], url: [] })
+ const result = await rustAddon!.anonymizeKafkaPayload(imagePayload(), undefined, PSEUDO_TEAM, CONTENT_KEY)
+ expect(result.failed).toBe(false)
+
+ const png = Buffer.from(PNG_B64, 'base64')
+ const expectedRef = imageRef(PSEUDO_TEAM, hashImageBytes(CONTENT_KEY, png))
+ expect(isImageRef(expectedRef)).toBe(true)
+ expect(result.lines!.toString()).toContain(expectedRef)
+ expect(result.lines!.toString()).not.toContain(PNG_B64)
+
+ const meta = parseJSON(result.meta!) as { images?: { hash: string; offset: number; len: number }[] }
+ expect(meta.images).toHaveLength(1)
+ const entry = meta.images![0]
+ const bytes = result.images!.subarray(entry.offset, entry.offset + entry.len)
+ expect(Buffer.from(bytes)).toEqual(png)
+ // The Rust-emitted hash must be the keyed HMAC of the returned bytes.
+ expect(hashImageBytes(CONTENT_KEY, Buffer.from(bytes))).toBe(entry.hash)
+ expect(parseImageRef(expectedRef)).toEqual({ pseudoTeam: PSEUDO_TEAM, hash: entry.hash })
+ })
+
+ it('collects nothing without the collection keys and blurs inline instead', async () => {
+ rustAddon!.initAnonymizer({ text: [], url: [] })
+ const result = await rustAddon!.anonymizeKafkaPayload(imagePayload())
+ expect(result.failed).toBe(false)
+ expect(result.images).toBeNull()
+ expect(result.lines!.toString()).not.toContain(PNG_B64)
+ expect(result.lines!.toString()).not.toContain('image:')
+ })
+
+ it('rejects when pseudoTeam and contentKey are not passed together', async () => {
+ rustAddon!.initAnonymizer({ text: [], url: [] })
+ await expect(
+ rustAddon!.anonymizeKafkaPayload(imagePayload(), undefined, PSEUDO_TEAM, undefined)
+ ).rejects.toThrow('must be passed together')
+ await expect(
+ rustAddon!.anonymizeKafkaPayload(imagePayload(), undefined, undefined, CONTENT_KEY)
+ ).rejects.toThrow('must be passed together')
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/outputs/producer-registry.ts b/nodejs/src/ingestion/pipelines/sessionreplay/outputs/producer-registry.ts
index 5b632eaee1a2..266b717721b6 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/outputs/producer-registry.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/outputs/producer-registry.ts
@@ -4,17 +4,25 @@ import {
INGESTION_DOWNSTREAM_PRODUCER_CONFIG_MAP,
} from '~/ingestion/common/outputs/producers'
import {
+ INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER,
+ INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_CONFIG_MAP,
INGESTION_SESSIONREPLAY_PRODUCER,
INGESTION_SESSIONREPLAY_PRODUCER_CONFIG_MAP,
} from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'
/**
* Session replay's producer slots: DOWNSTREAM (warpstream-ingestion) for ClickHouse-bound
- * outputs, and SESSIONREPLAY (warpstream-replay) for replay-domain topics including their DLQ
- * and overflow. Replay does not use UPSTREAM.
+ * outputs, SESSIONREPLAY (warpstream-replay) for replay-domain topics including their DLQ
+ * and overflow, and ML_IMAGE_SCRUB (same replay cluster, dedicated client) so the image
+ * lane's heavy best-effort payloads cannot fill the SESSIONREPLAY queue and starve the
+ * critical outputs. Replay does not use UPSTREAM.
*/
export function createProducerRegistry(kafkaClientRack: string | undefined) {
return new KafkaProducerRegistryBuilder(kafkaClientRack)
.register(INGESTION_DOWNSTREAM_PRODUCER, INGESTION_DOWNSTREAM_PRODUCER_CONFIG_MAP)
.register(INGESTION_SESSIONREPLAY_PRODUCER, INGESTION_SESSIONREPLAY_PRODUCER_CONFIG_MAP)
+ .register(
+ INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER,
+ INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_CONFIG_MAP
+ )
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/outputs/registry.ts b/nodejs/src/ingestion/pipelines/sessionreplay/outputs/registry.ts
index 103a12defae8..69b7542957ad 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/outputs/registry.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/outputs/registry.ts
@@ -8,6 +8,7 @@ import {
import { IngestionOutputsBuilder } from '~/common/outputs/ingestion-outputs-builder'
import {
ML_BLOCK_METADATA_OUTPUT,
+ ML_IMAGE_SCRUB_OUTPUT,
REPLAY_EVENTS_OUTPUT,
SESSION_FEATURES_OUTPUT,
} from '~/ingestion/pipelines/sessionreplay/shared/outputs'
@@ -47,4 +48,8 @@ export function createOutputsRegistry() {
topicKey: 'INGESTION_SESSIONREPLAY_OUTPUT_ML_BLOCK_METADATA_TOPIC',
producerKey: 'INGESTION_SESSIONREPLAY_OUTPUT_ML_BLOCK_METADATA_PRODUCER',
})
+ .register(ML_IMAGE_SCRUB_OUTPUT, {
+ topicKey: 'INGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_SCRUB_TOPIC',
+ producerKey: 'INGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_SCRUB_PRODUCER',
+ })
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts
index ed563051469f..1c91b8868dca 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts
@@ -4,6 +4,8 @@ import { gzip } from 'zlib'
import { PipelineResultType } from '~/ingestion/framework/results'
+import { imageRef } from './ml-mirror-image-scrub/content-ref'
+import { PSEUDONYM_IMAGE_CONTENT_KEY, PSEUDONYM_TEAM, pseudonymize } from './ml-mirror/pseudonymize'
import { createParseAndAnonymizeMessageStep } from './parse-and-anonymize-step'
import { SessionReplayHeaders } from './pipeline-types'
@@ -14,14 +16,24 @@ const compressWithGzip = promisify(gzip)
// assembly — not the scrub itself (that's covered by the Rust suite + shared fixtures).
const mockAnonymizeKafkaPayload = jest.fn()
jest.mock('@posthog/replay-anonymizer', () => ({
- anonymizeKafkaPayload: (payload: Buffer, contentEncoding?: string | null) =>
- mockAnonymizeKafkaPayload(payload, contentEncoding),
+ anonymizeKafkaPayload: (
+ payload: Buffer,
+ contentEncoding?: string | null,
+ pseudoTeam?: string | null,
+ contentKey?: string | null
+ ) => mockAnonymizeKafkaPayload(payload, contentEncoding, pseudoTeam, contentKey),
}))
describe('createParseAndAnonymizeMessageStep', () => {
const step = createParseAndAnonymizeMessageStep()
const now = Date.now()
+ const team = {
+ teamId: 1,
+ consoleLogIngestionEnabled: true,
+ aiTrainingOptedIn: true,
+ }
+
const headers: SessionReplayHeaders = {
token: 'token-1',
distinct_id: 'user-1',
@@ -39,12 +51,13 @@ describe('createParseAndAnonymizeMessageStep', () => {
} as Message
}
- function addonSuccess(metaOverrides: Record<string, unknown> = {}): void {
+ function addonSuccess(metaOverrides: Record<string, unknown> = {}, images: Buffer | null = null): void {
mockAnonymizeKafkaPayload.mockResolvedValue({
failed: false,
reason: null,
error: null,
lines: Buffer.from('["window-1",{"type":3,"timestamp":' + now + '}]\n'),
+ images,
meta: JSON.stringify({
distinctId: 'user-1',
sessionId: 'session-1',
@@ -68,7 +81,7 @@ describe('createParseAndAnonymizeMessageStep', () => {
it('assembles a pre-serialized ParsedMessageData from the addon output', async () => {
addonSuccess()
- const result = await step({ message: kafkaMessage(), headers })
+ const result = await step({ message: kafkaMessage(), headers, team })
expect(result.type).toBe(PipelineResultType.OK)
const parsed = (result as any).value.parsedMessage
@@ -92,6 +105,7 @@ describe('createParseAndAnonymizeMessageStep', () => {
const result = await step({
message: kafkaMessage(),
headers: { ...headers, session_id: upper.toLowerCase() },
+ team,
})
expect(result.type).toBe(PipelineResultType.OK)
expect((result as any).value.parsedMessage.session_id).toBe(upper.toLowerCase())
@@ -101,15 +115,15 @@ describe('createParseAndAnonymizeMessageStep', () => {
addonSuccess()
const raw = Buffer.from(JSON.stringify({ distinct_id: 'user-1', data: '{}' }))
const zipped = await compressWithGzip(raw)
- await step({ message: kafkaMessage(zipped), headers })
- expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(zipped, null)
+ await step({ message: kafkaMessage(zipped), headers, team })
+ expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(zipped, null, undefined, undefined)
mockAnonymizeKafkaPayload.mockClear()
addonSuccess()
const lz4Message = kafkaMessage(raw)
lz4Message.headers = [{ 'content-encoding': Buffer.from('lz4') }]
- await step({ message: lz4Message, headers })
- expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(raw, 'lz4')
+ await step({ message: lz4Message, headers, team })
+ expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(raw, 'lz4', undefined, undefined)
})
test.each([
@@ -127,21 +141,21 @@ describe('createParseAndAnonymizeMessageStep', () => {
lines: null,
meta: null,
})
- const result = await step({ message: kafkaMessage(), headers })
+ const result = await step({ message: kafkaMessage(), headers, team })
expect(result.type).toBe(expectedType)
expect((result as any).reason).toBe(reason)
})
it('fails closed when the addon promise rejects', async () => {
mockAnonymizeKafkaPayload.mockRejectedValue(new Error('native panic'))
- const result = await step({ message: kafkaMessage(), headers })
+ const result = await step({ message: kafkaMessage(), headers, team })
expect(result).toMatchObject({ type: PipelineResultType.DROP, reason: 'anonymize_failed' })
})
it('drops messages whose timestamps are too far from now', async () => {
const monthAgo = now - 30 * 24 * 60 * 60 * 1000
addonSuccess({ startTs: monthAgo, endTs: monthAgo + 1000 })
- const result = await step({ message: kafkaMessage(), headers })
+ const result = await step({ message: kafkaMessage(), headers, team })
expect(result).toMatchObject({ type: PipelineResultType.DROP, reason: 'message_timestamp_diff_too_large' })
})
@@ -150,13 +164,120 @@ describe('createParseAndAnonymizeMessageStep', () => {
['distinct_id', { distinctId: 'other-user' }, 'distinct_id_header_body_mismatch'],
])('dlqs on a %s header/body mismatch', async (_field, metaOverrides, reason) => {
addonSuccess(metaOverrides)
- const result = await step({ message: kafkaMessage(), headers })
+ const result = await step({ message: kafkaMessage(), headers, team })
expect(result).toMatchObject({ type: PipelineResultType.DLQ, reason })
})
it('dlqs when the message value is empty', async () => {
- const result = await step({ message: kafkaMessage(null), headers })
+ const result = await step({ message: kafkaMessage(null), headers, team })
expect(result).toMatchObject({ type: PipelineResultType.DLQ, reason: 'message_value_or_timestamp_is_empty' })
expect(mockAnonymizeKafkaPayload).not.toHaveBeenCalled()
})
})
+
+describe('createParseAndAnonymizeMessageStep with image collection', () => {
+ const secret = 'test-pseudonym-secret'
+ const step = createParseAndAnonymizeMessageStep({ pseudonymSecret: secret })
+ const pseudoTeam = pseudonymize(secret, PSEUDONYM_TEAM, '1')
+ const contentKey = pseudonymize(secret, PSEUDONYM_IMAGE_CONTENT_KEY, '1')
+ const now = Date.now()
+
+ const team = {
+ teamId: 1,
+ consoleLogIngestionEnabled: true,
+ aiTrainingOptedIn: true,
+ }
+ const headers: SessionReplayHeaders = {
+ token: 'token-1',
+ distinct_id: 'user-1',
+ session_id: 'session-1',
+ } as SessionReplayHeaders
+
+ function kafkaMessage(): Message {
+ return {
+ value: Buffer.from('{}'),
+ timestamp: now,
+ partition: 3,
+ topic: 'snapshots',
+ offset: 42,
+ size: 2,
+ } as Message
+ }
+
+ function addonSuccessWithImages(
+ images: Buffer | null,
+ imageEntries?: { hash: string; offset: number; len: number }[]
+ ): void {
+ mockAnonymizeKafkaPayload.mockResolvedValue({
+ failed: false,
+ reason: null,
+ error: null,
+ lines: Buffer.from('["window-1",{"type":3,"timestamp":' + now + '}]\n'),
+ images,
+ meta: JSON.stringify({
+ distinctId: 'user-1',
+ sessionId: 'session-1',
+ windowId: 'window-1',
+ snapshotSource: 'web',
+ snapshotLibrary: 'posthog-js',
+ startTs: now,
+ endTs: now + 1000,
+ consoleLogCount: 0,
+ consoleWarnCount: 0,
+ consoleErrorCount: 0,
+ events: [{ ts: now, flags: 0 }],
+ images: imageEntries,
+ }),
+ })
+ }
+
+ beforeEach(() => {
+ mockAnonymizeKafkaPayload.mockReset()
+ })
+
+ it('passes the cached per-team pseudonym and content key to the addon', async () => {
+ addonSuccessWithImages(null)
+ await step({ message: kafkaMessage(), headers, team })
+ await step({ message: kafkaMessage(), headers, team })
+ expect(mockAnonymizeKafkaPayload).toHaveBeenCalledTimes(2)
+ for (const call of mockAnonymizeKafkaPayload.mock.calls) {
+ expect(call[2]).toBe(pseudoTeam)
+ expect(call[3]).toBe(contentKey)
+ expect(call[3]).not.toBe(call[2])
+ }
+ })
+
+ it('unpacks the packed image buffer into per-image produce records', async () => {
+ const packed = Buffer.concat([Buffer.from('aaa'), Buffer.from('bb')])
+ addonSuccessWithImages(packed, [
+ { hash: 'hashA', offset: 0, len: 3 },
+ { hash: 'hashB', offset: 3, len: 2 },
+ ])
+ const result = await step({ message: kafkaMessage(), headers, team })
+ expect(result.type).toBe(PipelineResultType.OK)
+ const images = (result as any).value.collectedImages
+ expect(images).toEqual([
+ { ref: imageRef(pseudoTeam, 'hashA'), bytes: Buffer.from('aaa') },
+ { ref: imageRef(pseudoTeam, 'hashB'), bytes: Buffer.from('bb') },
+ ])
+ })
+
+ it('skips out-of-bounds entries instead of failing the message', async () => {
+ addonSuccessWithImages(Buffer.from('aaa'), [
+ { hash: 'hashA', offset: 0, len: 3 },
+ { hash: 'hashBad', offset: 2, len: 5 },
+ ])
+ const result = await step({ message: kafkaMessage(), headers, team })
+ expect(result.type).toBe(PipelineResultType.OK)
+ expect((result as any).value.collectedImages).toEqual([
+ { ref: imageRef(pseudoTeam, 'hashA'), bytes: Buffer.from('aaa') },
+ ])
+ })
+
+ it('leaves collectedImages undefined when the addon collected nothing', async () => {
+ addonSuccessWithImages(null)
+ const result = await step({ message: kafkaMessage(), headers, team })
+ expect(result.type).toBe(PipelineResultType.OK)
+ expect((result as any).value.collectedImages).toBeUndefined()
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts
index 5793f9bba97b..a514a9b1823f 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts
@@ -10,7 +10,10 @@ import { ProcessingStep } from '~/ingestion/framework/steps'
import { recordAnonymizeTimingSpans } from '~/ingestion/pipelines/sessionreplay/anonymize-timing-spans'
import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'
import { SessionRecordingIngesterMetrics } from '~/ingestion/pipelines/sessionreplay/metrics'
+import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
+import { hashImageBytes, imageRef, isImageRef } from './ml-mirror-image-scrub/content-ref'
+import { PSEUDONYM_IMAGE_CONTENT_KEY, PSEUDONYM_TEAM, pseudonymize } from './ml-mirror/pseudonymize'
import { ParseMessageStepInput, ParseMessageStepOutput, getContentEncoding, isGzipped } from './parse-message-step'
const MESSAGE_TIMESTAMP_DIFF_THRESHOLD_DAYS = 7
@@ -34,6 +37,22 @@ const DLQ_REASONS = new Set([
'received_non_snapshot_message',
])
+/** An original image the addon collected for the out-of-band scrub lane, ready to produce. */
+export interface CollectedImage {
+ /** `image:<pseudoTeam>:<hash>` — the Kafka key the scrub consumer indexes the bytes under. */
+ ref: string
+ bytes: Buffer
+}
+
+export interface ParseAndAnonymizeStepOutput extends ParseMessageStepOutput {
+ collectedImages?: CollectedImage[]
+}
+
+export interface ImageCollectionConfig {
+ /** The ML pseudonym HMAC key; only its per-team derivatives (never the key) cross the FFI. */
+ pseudonymSecret: string | Buffer
+}
+
/**
* Fused parse + anonymize through the native Rust addon (`@posthog/replay-anonymizer`): the
* decompressed Kafka payload bytes go in, scrubbed JSONL block lines plus the envelope/per-event
@@ -44,10 +63,43 @@ const DLQ_REASONS = new Set([
* unencrypted ML bucket. Failure classification matches the TS parse step so DLQ/drop behavior and
* ingestion warnings are unchanged.
*/
-export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInput>(): ProcessingStep<
- T,
- T & ParseMessageStepOutput
-> {
+export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInput & { team: TeamForReplay }>(
+ imageCollection?: ImageCollectionConfig
+): ProcessingStep<T, T & ParseAndAnonymizeStepOutput> {
+ // Both are per-team HMACs of the same secret (domain-separated) — cache them rather than
+ // re-deriving on every message. The content key keys the image hash so the unencrypted bucket
+ // carries no unkeyed content digest; it never crosses the FFI as the raw secret.
+ interface TeamImageKeys {
+ pseudoTeam: string
+ contentKey: string
+ }
+ const teamKeysCache = new Map<number, TeamImageKeys>()
+ const teamKeysFor = (teamId: number): TeamImageKeys | undefined => {
+ if (!imageCollection) {
+ return undefined
+ }
+ let keys = teamKeysCache.get(teamId)
+ if (!keys) {
+ const pseudoTeam = pseudonymize(imageCollection.pseudonymSecret, PSEUDONYM_TEAM, String(teamId))
+ const contentKey = pseudonymize(
+ imageCollection.pseudonymSecret,
+ PSEUDONYM_IMAGE_CONTENT_KEY,
+ String(teamId)
+ )
+ // The consumer regex-validates every ref and silently drops non-matches, so a pseudonym
+ // format drift would zero the lane with no signal. Refuse to embed a ref the consumer
+ // would drop — those messages fall back to the inline blur, loudly.
+ if (!isImageRef(imageRef(pseudoTeam, hashImageBytes(contentKey, Buffer.alloc(0))))) {
+ logger.error('🖼️', 'ml_image_scrub_pseudo_team_shape_invalid', { teamId })
+ SessionRecordingIngesterMetrics.incrementMlImagePseudoTeamInvalid()
+ return undefined
+ }
+ keys = { pseudoTeam, contentKey }
+ teamKeysCache.set(teamId, keys)
+ }
+ return keys
+ }
+
return async function parseAndAnonymizeMessageStep(input) {
const { message, headers } = input
@@ -62,11 +114,17 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInp
contentEncoding ?? (isGzipped(message.value) ? 'gzip' : 'none')
)
+ const teamKeys = teamKeysFor(input.team.teamId)
const t0 = performance.now()
const callStartEpochMs = performance.timeOrigin + t0
let result
try {
- result = await getRustAnonymizer().anonymizeKafkaPayload(message.value, contentEncoding)
+ result = await getRustAnonymizer().anonymizeKafkaPayload(
+ message.value,
+ contentEncoding,
+ teamKeys?.pseudoTeam,
+ teamKeys?.contentKey
+ )
} catch (error) {
// A rejected promise (native panic, addon load failure) must fail closed.
logger.warn('🙈', 'anonymize_event_failed', { error: String(error) })
@@ -171,6 +229,35 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInp
snapshot_library: meta.snapshotLibrary,
}
- return ok({ ...input, parsedMessage })
+ const collectedImages = teamKeys ? unpackCollectedImages(teamKeys.pseudoTeam, meta, result.images) : undefined
+ return ok({ ...input, parsedMessage, collectedImages })
+ }
+}
+
+/**
+ * Slice the addon's packed image buffer into per-image produce records. The lines already carry the
+ * refs, so a skipped slice only means that ref stays dangling (same outcome as a failed produce) —
+ * never a blocked message.
+ */
+function unpackCollectedImages(
+ pseudoTeam: string,
+ meta: AnonymizeMeta,
+ packed: Buffer | null
+): CollectedImage[] | undefined {
+ if (!meta.images?.length || !packed) {
+ return undefined
+ }
+ const images: CollectedImage[] = []
+ for (const entry of meta.images) {
+ if (entry.offset < 0 || entry.len < 0 || entry.offset + entry.len > packed.length) {
+ logger.warn('🙈', 'collected_image_entry_out_of_bounds', { ...entry, packedLength: packed.length })
+ continue
+ }
+ images.push({
+ ref: imageRef(pseudoTeam, entry.hash),
+ bytes: packed.subarray(entry.offset, entry.offset + entry.len),
+ })
}
+ SessionRecordingIngesterMetrics.incrementMlImagesCollected('collected', images.length)
+ return images.length > 0 ? images : undefined
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/index.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/index.ts
index bf523ae09033..f0fa62a83be7 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/index.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/index.ts
@@ -11,3 +11,8 @@ export type SessionFeaturesOutput = typeof SESSION_FEATURES_OUTPUT
// Anonymized block metadata for the ML mirror; only the mirror deployment produces to it.
export const ML_BLOCK_METADATA_OUTPUT = 'ml_block_metadata' as const
export type MlBlockMetadataOutput = typeof ML_BLOCK_METADATA_OUTPUT
+
+// Original image bytes for the out-of-band scrub lane (key = `image:<pseudoTeam>:<hash>`);
+// only the mirror deployment produces to it.
+export const ML_IMAGE_SCRUB_OUTPUT = 'ml_image_scrub' as const
+export type MlImageScrubOutput = typeof ML_IMAGE_SCRUB_OUTPUT
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts
index 2697b61463bb..e21178bd5a57 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts
@@ -29,14 +29,20 @@ export const INGESTION_SESSIONREPLAY_PRODUCER_CONFIG_MAP = {
'KAFKA_INGESTION_SESSIONREPLAY_PRODUCER_MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION',
} as const satisfies Partial<Record<AllowedConfigKey, string>>
-/** Env var keys referenced by `INGESTION_SESSIONREPLAY_PRODUCER_CONFIG_MAP`. */
+/**
+ * Env var keys referenced by `INGESTION_SESSIONREPLAY_PRODUCER_CONFIG_MAP` plus the
+ * ML_IMAGE_SCRUB producer's own tuning keys (its broker/security keys are shared with the
+ * base map, so any server carrying this config can build both producers).
+ */
export type KafkaSessionreplayProducerEnvConfig = Record<
(typeof INGESTION_SESSIONREPLAY_PRODUCER_CONFIG_MAP)[keyof typeof INGESTION_SESSIONREPLAY_PRODUCER_CONFIG_MAP],
string
->
+> &
+ KafkaMlImageScrubProducerEnvConfig
export function getDefaultKafkaSessionreplayProducerEnvConfig(): KafkaSessionreplayProducerEnvConfig {
return {
+ ...getDefaultKafkaMlImageScrubProducerEnvConfig(),
KAFKA_INGESTION_SESSIONREPLAY_PRODUCER_CLIENT_ID: '',
KAFKA_INGESTION_SESSIONREPLAY_PRODUCER_METADATA_BROKER_LIST: '',
KAFKA_INGESTION_SESSIONREPLAY_PRODUCER_SECURITY_PROTOCOL: '',
@@ -55,3 +61,57 @@ export function getDefaultKafkaSessionreplayProducerEnvConfig(): KafkaSessionrep
KAFKA_INGESTION_SESSIONREPLAY_PRODUCER_MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION: '',
}
}
+
+/**
+ * ML_IMAGE_SCRUB producer — same replay cluster, but a dedicated client instance so the
+ * image-scrub lane's heavy, best-effort payloads (original image bytes, up to 32 MB per source
+ * message) buffer in their own librdkafka queue. A scrub-topic slowdown then fails fast inside
+ * this producer (failed produces are swallowed by design — a dangling ref reads as a placeholder)
+ * instead of filling the shared SESSIONREPLAY queue and starving DLQ/overflow/metadata produces.
+ * Broker/security config is shared with the SESSIONREPLAY producer; only the buffering knobs and
+ * compression differ (image bytes are already compressed, so codec defaults to none).
+ */
+export const INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER = 'INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB' as const
+export type IngestionSessionreplayMlImageScrubProducer = typeof INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER
+
+export const INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_CONFIG_MAP = {
+ 'client.id': 'KAFKA_INGESTION_SESSIONREPLAY_PRODUCER_CLIENT_ID',
+ 'metadata.broker.list': 'KAFKA_INGESTION_SESSIONREPLAY_PRODUCER_METADATA_BROKER_LIST',
+ 'security.protocol': 'KAFKA_INGESTION_SESSIONREPLAY_PRODUCER_SECURITY_PROTOCOL',
+ 'compression.codec': 'KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_COMPRESSION_CODEC',
+ 'linger.ms': 'KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_LINGER_MS',
+ 'queue.buffering.max.messages':
+ 'KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES',
+ 'queue.buffering.max.kbytes': 'KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES',
+ 'message.max.bytes': 'KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_MESSAGE_MAX_BYTES',
+ 'message.timeout.ms': 'KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_MESSAGE_TIMEOUT_MS',
+} as const satisfies Partial<Record<AllowedConfigKey, string>>
+
+/** Env var keys owned by `INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_CONFIG_MAP` (broker/security keys are shared). */
+export type KafkaMlImageScrubProducerEnvConfig = {
+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_COMPRESSION_CODEC: string
+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_LINGER_MS: string
+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES: string
+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES: string
+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_MESSAGE_MAX_BYTES: string
+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_MESSAGE_TIMEOUT_MS: string
+}
+
+export function getDefaultKafkaMlImageScrubProducerEnvConfig(): KafkaMlImageScrubProducerEnvConfig {
+ return {
+ // Image bytes are already-compressed formats; recompressing burns CPU for nothing.
+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_COMPRESSION_CODEC: 'none',
+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_LINGER_MS: '',
+ // Small queue by design: bounds the lane's RSS ceiling (~128 MB of ~900 KB records — four
+ // worst-case 32 MB source messages) and makes a scrub-topic backlog fail fast in this
+ // producer instead of accumulating.
+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES: '10000',
+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES: '131072',
+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_MESSAGE_MAX_BYTES: '',
+ // Short local delivery timeout (librdkafka defaults to 300s): the lane is best-effort and
+ // its ack promises join the mirror's pre-commit side-effect drain, so a scrub-topic
+ // slowdown must fail deliveries fast (dangling ref = placeholder) rather than stall the
+ // mirror's offset commits toward max.poll.interval.ms.
+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_MESSAGE_TIMEOUT_MS: '20000',
+ }
+}
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
index 52053b3162b9..8b5ecef972d2 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
@@ -158,11 +158,17 @@ export class IngestionSessionReplayMlMirrorServer implements NodeServer {
keyStore,
encryptor: new CleartextRecordingEncryptor(keyStore),
createPipeline: (pipelineConfig) =>
- createMlMirrorReplayPipeline(pipelineConfig, {
- anonymizeMaxConcurrency: resolveMlAnonymizeMaxConcurrency(
- this.config.SESSION_RECORDING_ML_ANONYMIZE_MAX_CONCURRENCY
- ),
- }),
+ createMlMirrorReplayPipeline(
+ pipelineConfig,
+ {
+ anonymizeMaxConcurrency: resolveMlAnonymizeMaxConcurrency(
+ this.config.SESSION_RECORDING_ML_ANONYMIZE_MAX_CONCURRENCY
+ ),
+ },
+ this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED
+ ? { outputs, pseudonymSecret }
+ : undefined
+ ),
// Isolate the mirror's session tracker/filter keys from the main lane. Sharing them would let
// the cleartext mirror mark a session seen without the main lane's KMS key, so the main lane
// would then fetch a missing key and record cleartext.
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index edccc86be448..025cf68537f8 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -8187,12 +8187,13 @@ dependencies = [
[[package]]
name = "posthog-replay-anonymizer"
-version = "0.3.0"
+version = "0.4.0"
dependencies = [
"ahash 0.8.12",
"anyhow",
"base64 0.22.1",
"flate2",
+ "hmac",
"image",
"jpeg-decoder",
"libdeflater",
@@ -8200,6 +8201,7 @@ dependencies = [
"memchr",
"serde",
"serde_json",
+ "sha2",
"simd-json",
"url",
"zstd",
diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.ts
index 7f1278ef9ed5..5c0e8ecd4609 100644
--- a/rust/replay-anonymizer-node/src/index.ts
+++ b/rust/replay-anonymizer-node/src/index.ts
@@ -19,6 +19,14 @@ export interface AnonymizeEventMeta {
href?: string
}
+/** One collected original image: `offset..offset+len` in {@link AnonymizeKafkaPayloadResult.images}. */
+export interface AnonymizeImageEntry {
+ /** First 22 base64url chars of `HMAC-SHA256(contentKey, bytes)` (`hashImageBytes` in content-ref.ts). */
+ hash: string
+ offset: number
+ len: number
+}
+
/** Envelope + per-event metadata parsed from {@link AnonymizeKafkaPayloadResult.meta}. */
export interface AnonymizeMeta {
distinctId: string
@@ -36,6 +44,8 @@ export interface AnonymizeMeta {
consoleWarnCount: number
consoleErrorCount: number
events: AnonymizeEventMeta[]
+ /** Collected original images (hash-sorted); present only when the collection lane was enabled and images were collected. */
+ images?: AnonymizeImageEntry[]
}
/**
@@ -85,6 +95,8 @@ export interface AnonymizeKafkaPayloadResult {
route: 'stream' | 'tree' | null
/** Phase timings; present on success and failure alike. `null` only if serialization failed. */
timings: AnonymizeTimings | null
+ /** Original bytes of the collected images, concatenated in `meta.images` order; null when none. */
+ images: Buffer | null
}
/** Initialize the process-wide allow lists. Call once at startup before {@link anonymizeKafkaPayload}. */
@@ -99,12 +111,25 @@ export function initAnonymizer(allow: AllowListsInput): void {
* decompression — runs off the Node event loop.
*
* `cv` payloads re-emit as zstd; the reader dispatches on magic bytes.
+ *
+ * Non-empty `pseudoTeam` + `contentKey` (the per-team HMAC pseudonym and content-hash key — never
+ * the raw team id or master secret) enable the image-collection lane: inlined images are replaced
+ * with `image:<pseudoTeam>:<hash>` refs (hash = keyed HMAC of the bytes) instead of the inline
+ * blur, and the original bytes come back in `images`/`meta.images` for the caller to produce to
+ * the scrub topic. Passing one without the other throws.
*/
export async function anonymizeKafkaPayload(
payload: Buffer,
- contentEncoding?: string | null
+ contentEncoding?: string | null,
+ pseudoTeam?: string | null,
+ contentKey?: string | null
): Promise<AnonymizeKafkaPayloadResult> {
- const result = await native.anonymizeKafkaPayload(payload, contentEncoding ?? undefined)
+ const result = await native.anonymizeKafkaPayload(
+ payload,
+ contentEncoding ?? undefined,
+ pseudoTeam ?? undefined,
+ contentKey ?? undefined
+ )
// Timings are best-effort telemetry: a malformed timings blob must never fail the message.
let timings: AnonymizeTimings | null = null
if (typeof result.timings === 'string') {
diff --git a/rust/replay-anonymizer-node/src/lib.rs b/rust/replay-anonymizer-node/src/lib.rs
index b9223ddb6b2d..8b067e748869 100644
--- a/rust/replay-anonymizer-node/src/lib.rs
+++ b/rust/replay-anonymizer-node/src/lib.rs
@@ -11,7 +11,9 @@ use std::sync::RwLock;
use neon::prelude::*;
use neon::types::buffer::TypedArray;
-use posthog_replay_anonymizer::{snapshot, AllowLists, FailKind, ImagePolicy, PhaseTimings};
+use posthog_replay_anonymizer::{
+ snapshot, AllowLists, FailKind, ImageCollection, ImagePolicy, PhaseTimings,
+};
use serde::Deserialize;
// The fail-closed contract depends on `catch_unwind` containing panics on untrusted input. Under
@@ -64,9 +66,11 @@ fn init_anonymizer(mut cx: FunctionContext) -> JsResult<JsNull> {
Ok(cx.null())
}
-/// The off-thread outcome: anonymized output, a classified failure (dlq/drop reason + detail), or an
-/// unclassified error (panic, missing init) that the caller must treat as `anonymize_failed`.
-type TaskOutcome = Result<Result<(Vec<u8>, String, &'static str), (&'static str, String)>, String>;
+/// The off-thread outcome: anonymized output (lines, meta JSON, route, packed image bytes), a
+/// classified failure (dlq/drop reason + detail), or an unclassified error (panic, missing init)
+/// that the caller must treat as `anonymize_failed`.
+type TaskOutcome =
+ Result<Result<(Vec<u8>, String, &'static str, Vec<u8>), (&'static str, String)>, String>;
/// The outcome plus the JSON phase timings, reported on every arm including panics.
type TaskResult = (TaskOutcome, Option<String>);
@@ -81,6 +85,28 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {
.argument_opt(1)
.and_then(|v| v.downcast::<JsString, _>(&mut cx).ok())
.map(|s| s.value(&mut cx));
+ // Present + non-empty (both of them) enables the image-collection lane, keyed to this
+ // pseudonymous team id and per-team content-HMAC key. A present-but-non-string argument, or one
+ // of the pair without the other, must fail loudly (the caller drops the message) rather than
+ // silently disable or mis-key collection; only absent/undefined/null mean "collection off".
+ let opt_string_arg = |cx: &mut FunctionContext, index: usize| -> NeonResult<Option<String>> {
+ Ok(match cx.argument_opt(index) {
+ Some(v) if v.is_a::<JsUndefined, _>(cx) || v.is_a::<JsNull, _>(cx) => None,
+ Some(v) => Some(v.downcast_or_throw::<JsString, _>(cx)?.value(cx)),
+ None => None,
+ }
+ .filter(|s| !s.is_empty()))
+ };
+ let pseudo_team = opt_string_arg(&mut cx, 2)?;
+ let content_key = opt_string_arg(&mut cx, 3)?;
+ let image_collection = match (pseudo_team, content_key) {
+ (Some(pseudo_team), Some(content_key)) => Some(ImageCollection {
+ pseudo_team,
+ content_key,
+ }),
+ (None, None) => None,
+ _ => return cx.throw_error("pseudoTeam and contentKey must be passed together"),
+ };
// Created on the JS thread so every offset shares one monotonic origin: the task-start mark
// becomes the threadpool queue wait, and no wall clock is involved.
let timings = PhaseTimings::new();
@@ -113,6 +139,7 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {
..Default::default()
},
Some(&timings),
+ image_collection,
);
timings.scrub_finished();
match scrubbed {
@@ -121,7 +148,7 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {
let meta = serde_json::to_string(&out.meta)
.map_err(|e| format!("serialize meta: {e}"))?;
timings.mark("done");
- Ok(Ok((out.lines, meta, out.route.as_str())))
+ Ok(Ok((out.lines, meta, out.route.as_str(), out.image_bytes)))
}
Err(f) => Ok(Err((f.kind.reason(), f.detail))),
}
@@ -158,10 +185,12 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {
obj.set(cx, "meta", null)?;
let null = cx.null();
obj.set(cx, "route", null)?;
+ let null = cx.null();
+ obj.set(cx, "images", null)?;
Ok(())
};
match result {
- Ok(Ok((lines, meta, route))) => {
+ Ok(Ok((lines, meta, route, image_bytes))) => {
let failed = cx.boolean(false);
obj.set(&mut cx, "failed", failed)?;
let null = cx.null();
@@ -176,6 +205,13 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {
obj.set(&mut cx, "meta", meta)?;
let route = cx.string(route);
obj.set(&mut cx, "route", route)?;
+ if image_bytes.is_empty() {
+ let null = cx.null();
+ obj.set(&mut cx, "images", null)?;
+ } else {
+ let images = JsBuffer::external(&mut cx, image_bytes);
+ obj.set(&mut cx, "images", images)?;
+ }
}
Ok(Err((reason, detail))) => set_failure(&mut cx, &obj, reason, detail)?,
// Fail closed: an unclassified error still drops the message.
diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.toml
index 59e1477cfdb5..ea05dee2ff5a 100644
--- a/rust/replay-anonymizer/Cargo.toml
+++ b/rust/replay-anonymizer/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "posthog-replay-anonymizer"
-version = "0.3.0"
+version = "0.4.0"
edition = "2021"
description = "PII scrubber for rrweb session-replay events: text/URL redaction, native image blur, and canvas/cv neutralization"
license = "MIT"
@@ -20,6 +20,7 @@ typed-parse = []
ahash = { workspace = true }
anyhow = { workspace = true }
base64 = { workspace = true }
+hmac = { workspace = true }
libdeflater = { workspace = true }
lz4 = { workspace = true }
memchr = "2"
@@ -27,6 +28,7 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg",
jpeg-decoder = { version = "0.3", default-features = false }
serde = { workspace = true }
serde_json = { workspace = true }
+sha2 = { workspace = true }
simd-json = { version = "0.15", features = ["serde_impl"] }
url = { workspace = true }
zstd = { workspace = true }
diff --git a/rust/replay-anonymizer/src/canvas.rs b/rust/replay-anonymizer/src/canvas.rs
index f29e74d612f5..cabf68b9dd8f 100644
--- a/rust/replay-anonymizer/src/canvas.rs
+++ b/rust/replay-anonymizer/src/canvas.rs
@@ -6,6 +6,7 @@ use base64::Engine;
use simd_json::borrowed::{Object, Value};
use crate::blur::{is_image_data_uri, split_data_uri, BLANK_PNG_BASE64};
+use crate::collect::{is_image_ref, normalize_collected_mime};
use crate::context::Ctx;
use crate::images::ImageFallback;
use crate::json::{
@@ -170,13 +171,21 @@ fn blur_blob_image(ctx: &Ctx<'_>, blob: &mut Object<'_>) -> bool {
None => return false,
};
let original = format!("data:{mime};base64,{base64}");
- // scrub_image never fails outward (fallbacks are baked in), so the split always succeeds; the
- // stated fallback keeps the fail-safe explicit if the URI shape ever changes.
- let (new_b64, new_type) =
- match split_data_uri(&ctx.scrub_image(&original, ImageFallback::Blank)) {
+ // scrub_image never fails outward (fallbacks are baked in). The collection lane's ref
+ // replaces the payload wholesale (it is the consumer's join key, not decodable bytes); the
+ // mime survives only through the raster allowlist — the blur path re-encoded and overwrote
+ // it, so the ref path must not let a client string through this field either. Otherwise the
+ // split always succeeds — the stated fallback keeps the fail-safe explicit if the URI shape
+ // ever changes.
+ let scrubbed = ctx.scrub_image(&original, ImageFallback::Blank);
+ let (new_b64, new_type) = if is_image_ref(&scrubbed) {
+ (scrubbed, normalize_collected_mime(&mime).to_string())
+ } else {
+ match split_data_uri(&scrubbed) {
Some((m, b64)) => (b64, m),
None => (BLANK_PNG_BASE64.to_string(), "image/png".to_string()),
- };
+ }
+ };
if let Some(ab) = blob
.get_mut("data")
.and_then(as_array_mut)
@@ -416,6 +425,45 @@ mod tests {
assert_ne!(src, uri, "raw image must not pass through");
}
+ #[test]
+ fn blob_mime_is_allowlisted_on_the_collection_lane() {
+ // The blur path re-encodes and overwrites the client-controlled `type`; the ref path has
+ // no bytes to re-encode, so it must normalize the mime instead of echoing client text.
+ use crate::collect::ImageCollection;
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let ctx = Ctx::with_image_collection(
+ &allow,
+ Some(ImageCollection {
+ pseudo_team: "0".repeat(32),
+ content_key: "k".repeat(32),
+ }),
+ );
+ let b64 = png_base64(8, 8, [10, 200, 10, 255]);
+ let scrub_with = |mime: &str| -> serde_json::Value {
+ let data_json = format!(
+ r#"{{"source":9,"id":1,"type":0,"commands":[{{"property":"drawImage","args":[{{"rr_type":"Blob","type":"{mime}","data":[{{"rr_type":"ArrayBuffer","base64":"{b64}"}}]}}]}}]}}"#
+ );
+ let mut bytes = data_json.as_bytes().to_vec();
+ let mut data = simd_json::to_borrowed_value(&mut bytes).unwrap();
+ scrub_canvas_mutation(&ctx, &mut data);
+ serde_json::from_str(&data.encode()).unwrap()
+ };
+ let arg = |v: &serde_json::Value| v["commands"][0]["args"][0].clone();
+
+ let kept = arg(&scrub_with("image/webp"));
+ assert_eq!(kept["type"], "image/webp", "known raster subtype survives");
+ assert!(kept["data"][0]["base64"]
+ .as_str()
+ .unwrap()
+ .starts_with("image:"));
+
+ let scrubbed = arg(&scrub_with("image/x-evil-client-text"));
+ assert_eq!(
+ scrubbed["type"], "image/png",
+ "unknown subtype must not echo"
+ );
+ }
+
#[test]
fn blob_image_bytes_are_neutralized() {
let b64 = png_base64(8, 8, [10, 200, 10, 255]);
diff --git a/rust/replay-anonymizer/src/collect.rs b/rust/replay-anonymizer/src/collect.rs
new file mode 100644
index 000000000000..ed1982097892
--- /dev/null
+++ b/rust/replay-anonymizer/src/collect.rs
@@ -0,0 +1,299 @@
+//! Collect original image bytes for the out-of-band scrub lane.
+//!
+//! With collection enabled (an [`ImageCollection`] on the anonymize call), each inlined image is
+//! replaced by a stable content reference — `image:<pseudoTeam>:<hash>` — instead of the native
+//! blur, and the original bytes ride back to the caller on the message. The caller produces them
+//! to the `session_replay_image_scrub` Kafka topic keyed by the ref; the scrub consumer trusts the
+//! ref (this producer is the only writer), blurs the bytes out of process, and writes them to the
+//! ML bucket indexed by `(pseudo_team, hash)` — so the ref embedded in the mirrored lines is the
+//! join key.
+//!
+//! The hash is a *keyed* HMAC, not a plain digest: the ML bucket is unencrypted, and a plain
+//! content hash would let any bucket reader confirm whether specific known bytes appeared in a
+//! session (and correlate identical images across teams). The per-team key is derived by the
+//! caller from the same KMS-held secret as the team pseudonym, so neither leaves the ingester.
+//! `image-hash.json` pins the construction against Node `createHmac` reference vectors.
+
+use std::collections::HashSet;
+
+use base64::Engine;
+use hmac::{Hmac, Mac};
+use sha2::Sha256;
+
+/// First 22 base64url chars of `HMAC-SHA256(content_key, bytes)`.
+pub fn hash_image_bytes(content_key: &[u8], bytes: &[u8]) -> String {
+ let mut mac = Hmac::<Sha256>::new_from_slice(content_key).expect("hmac accepts any key length");
+ mac.update(bytes);
+ let digest = mac.finalize().into_bytes();
+ let mut b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(digest);
+ b64.truncate(22);
+ b64
+}
+
+pub fn image_ref(pseudo_team: &str, hash: &str) -> String {
+ format!("image:{pseudo_team}:{hash}")
+}
+
+/// True for strings shaped like a content ref. The `image:` prefix cannot collide with a data URI,
+/// a URL (no scheme is registered as `image`), or base64 payloads (`:` is not in the alphabet).
+pub fn is_image_ref(s: &str) -> bool {
+ s.starts_with("image:")
+}
+
+/// Per-image cap: a collected image must fit in one Kafka message on the scrub topic with headroom
+/// under the broker's 1 MB default. Bigger images stay on the inline blur path.
+pub const MAX_IMAGE_BYTES: usize = 900 * 1024;
+/// Per-message caps bound what one payload can pin in memory and fan out onto the scrub topic;
+/// images past them stay on the inline blur path. The count cap is sized so the byte cap is the
+/// binding constraint for realistic payloads (only sub-64 KB average images can hit it first, and
+/// pages with hundreds of tiny icons dedup heavily) — an image-heavy but ordinary snapshot should
+/// never fall back on count alone.
+///
+/// Memory sizing: collection peaks at ~2x the byte cap in Rust per in-flight message (collector
+/// vec + packed FFI buffer), and the mirror anonymizes up to its configured concurrency of
+/// messages at once. Once produced, only the producer's bounded queue retains copies (the ack
+/// closures deliberately capture refs, not bytes), so the cap never compounds into producer-side
+/// backlog.
+pub const MAX_IMAGES_PER_MESSAGE: usize = 512;
+pub const MAX_TOTAL_BYTES_PER_MESSAGE: usize = 32 * 1024 * 1024;
+
+/// Enables collection for one anonymize call.
+#[derive(Debug, Clone)]
+pub struct ImageCollection {
+ /// The non-reversible HMAC team pseudonym (32 hex chars), computed by the caller — the secret
+ /// never crosses into this crate. Embedded verbatim in every emitted ref.
+ pub pseudo_team: String,
+ /// Per-team key for the content HMAC, derived by the caller alongside the pseudonym. Its ASCII
+ /// bytes key [`hash_image_bytes`].
+ pub content_key: String,
+}
+
+pub struct CollectedImage {
+ pub hash: String,
+ pub bytes: Vec<u8>,
+}
+
+/// Accumulates the images of one message. Byte-level dedup on the hash: the same image arriving
+/// under different URIs (or after the per-URI memo misses) is collected once but still gets its ref.
+pub struct ImageCollector {
+ pseudo_team: String,
+ content_key: String,
+ images: Vec<CollectedImage>,
+ seen: HashSet<String>,
+ total_bytes: usize,
+}
+
+impl ImageCollector {
+ pub fn new(collection: ImageCollection) -> Self {
+ Self {
+ pseudo_team: collection.pseudo_team,
+ content_key: collection.content_key,
+ images: Vec::new(),
+ seen: HashSet::new(),
+ total_bytes: 0,
+ }
+ }
+
+ /// Collect decoded image bytes and return their ref, or `None` when a cap says this image must
+ /// stay on the inline blur path.
+ pub fn collect(&mut self, bytes: Vec<u8>) -> Option<String> {
+ if bytes.len() > MAX_IMAGE_BYTES {
+ return None;
+ }
+ let hash = hash_image_bytes(self.content_key.as_bytes(), &bytes);
+ if self.seen.contains(&hash) {
+ return Some(image_ref(&self.pseudo_team, &hash));
+ }
+ if self.images.len() >= MAX_IMAGES_PER_MESSAGE
+ || self.total_bytes + bytes.len() > MAX_TOTAL_BYTES_PER_MESSAGE
+ {
+ return None;
+ }
+ self.total_bytes += bytes.len();
+ self.seen.insert(hash.clone());
+ self.images.push(CollectedImage {
+ hash: hash.clone(),
+ bytes,
+ });
+ Some(image_ref(&self.pseudo_team, &hash))
+ }
+
+ /// Drain, sorted by hash — a deterministic order that cannot depend on which scrub engine
+ /// walked the message (the differential tests assert meta equality across both).
+ pub fn into_images(mut self) -> Vec<CollectedImage> {
+ self.images.sort_by(|a, b| a.hash.cmp(&b.hash));
+ self.images
+ }
+}
+
+/// Raster subtypes preserved on a collected canvas blob's `type` field — downstream replay
+/// reassembly uses it as the format hint for the image behind the ref. Anything else (unknown
+/// subtypes, parameters — where client-controlled text could ride through unscrubbed) normalizes
+/// to `image/png`. Exact matches only: the old blur path re-encoded and overwrote this field, so
+/// no client string ever survived; the ref path must not weaken that.
+const COLLECTED_MIME_ALLOWLIST: &[&str] = &[
+ "image/png",
+ "image/jpeg",
+ "image/gif",
+ "image/webp",
+ "image/bmp",
+ "image/avif",
+];
+
+pub fn normalize_collected_mime(mime: &str) -> &'static str {
+ let lower = mime.trim().to_ascii_lowercase();
+ COLLECTED_MIME_ALLOWLIST
+ .iter()
+ .find(|allowed| **allowed == lower)
+ .copied()
+ .unwrap_or("image/png")
+}
+
+/// Decode the collectable payload of an image data URI. `None` (not collectable) for anything but
+/// a base64 raster image: SVG is a text format whose PII must stay on the inline scrub path, and
+/// non-base64 payloads mirror `blur_image_data_uri`'s refusal. MIME types are case-insensitive,
+/// so the checks run on a lowercased meta — `image/SVG+xml` must not dodge the SVG exclusion.
+pub fn collectable_data_uri_bytes(uri: &str) -> Option<Vec<u8>> {
+ let rest = uri.strip_prefix("data:")?;
+ let (meta, payload) = rest.split_once(',')?;
+ let meta = meta.to_ascii_lowercase();
+ if !meta.starts_with("image/") || !meta.contains("base64") {
+ return None;
+ }
+ if meta.starts_with("image/svg") {
+ return None;
+ }
+ // An encoded payload that can't decode under the per-image cap would be decoded here only to
+ // be rejected by `collect` (and then decoded again by the blur fallback) — bail on the
+ // encoded length instead.
+ if payload.len() > MAX_IMAGE_BYTES.div_ceil(3) * 4 {
+ return None;
+ }
+ base64::engine::general_purpose::STANDARD
+ .decode(payload.as_bytes())
+ .ok()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const TEST_KEY: &[u8] = b"0123456789abcdef0123456789abcdef";
+
+ fn collector() -> ImageCollector {
+ ImageCollector::new(ImageCollection {
+ pseudo_team: "a".repeat(32),
+ content_key: String::from_utf8(TEST_KEY.to_vec()).unwrap(),
+ })
+ }
+
+ #[test]
+ fn hash_is_22_base64url_chars_and_keyed() {
+ let hash = hash_image_bytes(TEST_KEY, b"hello world");
+ assert_eq!(hash.len(), 22);
+ assert!(hash
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'));
+ // Different keys must produce unrelated hashes for the same bytes — the keying is the
+ // point (no unkeyed content oracle in the ML bucket).
+ assert_ne!(hash, hash_image_bytes(b"another-key", b"hello world"));
+ }
+
+ #[test]
+ fn ref_matches_consumer_shape() {
+ // The consumer's REF_RE: image:<32 hex>:<22 base64url>.
+ let r = image_ref(&"ab".repeat(16), &hash_image_bytes(TEST_KEY, b"x"));
+ assert!(is_image_ref(&r));
+ let parts: Vec<&str> = r.splitn(3, ':').collect();
+ assert_eq!(parts[0], "image");
+ assert_eq!(parts[1].len(), 32);
+ assert_eq!(parts[2].len(), 22);
+ }
+
+ #[test]
+ fn collect_dedups_on_bytes_and_returns_the_same_ref() {
+ let mut c = collector();
+ let a = c.collect(vec![1, 2, 3]).unwrap();
+ let b = c.collect(vec![1, 2, 3]).unwrap();
+ assert_eq!(a, b);
+ assert_eq!(c.into_images().len(), 1);
+ }
+
+ #[test]
+ fn collect_rejects_oversized_image() {
+ let mut c = collector();
+ assert!(c.collect(vec![0u8; MAX_IMAGE_BYTES + 1]).is_none());
+ assert!(c.into_images().is_empty());
+ }
+
+ #[test]
+ fn collect_stops_at_the_per_message_count_cap_but_still_refs_seen_images() {
+ let mut c = collector();
+ for i in 0..MAX_IMAGES_PER_MESSAGE {
+ assert!(c.collect(i.to_le_bytes().to_vec()).is_some());
+ }
+ assert!(c.collect(b"one too many".to_vec()).is_none());
+ // A repeat of an already-collected image still resolves to its ref.
+ assert!(c.collect(0usize.to_le_bytes().to_vec()).is_some());
+ assert_eq!(c.into_images().len(), MAX_IMAGES_PER_MESSAGE);
+ }
+
+ #[test]
+ fn into_images_sorts_by_hash() {
+ let mut c = collector();
+ c.collect(b"bbb".to_vec());
+ c.collect(b"aaa".to_vec());
+ let images = c.into_images();
+ assert!(images[0].hash < images[1].hash);
+ }
+
+ #[test]
+ fn collectable_rejects_svg_non_base64_and_non_image() {
+ assert!(collectable_data_uri_bytes("data:image/svg+xml;base64,PHN2Zz4=").is_none());
+ assert!(collectable_data_uri_bytes("data:image/svg+xml;utf8,<svg/>").is_none());
+ assert!(collectable_data_uri_bytes("data:text/plain;base64,aGk=").is_none());
+ assert!(collectable_data_uri_bytes("data:image/png;utf8,notbase64").is_none());
+ assert!(collectable_data_uri_bytes("data:image/png;base64,%%%").is_none());
+ assert_eq!(
+ collectable_data_uri_bytes("data:image/png;base64,aGVsbG8=").as_deref(),
+ Some(b"hello".as_slice())
+ );
+ }
+
+ #[test]
+ fn collectable_rejects_oversized_encoded_payload_without_decoding() {
+ // 4/3 * MAX_IMAGE_BYTES encoded chars is the fit boundary; one full quartet past it means
+ // the decoded bytes cannot fit, so it must bail before paying the decode.
+ let over = "A".repeat(MAX_IMAGE_BYTES.div_ceil(3) * 4 + 4);
+ assert!(collectable_data_uri_bytes(&format!("data:image/png;base64,{over}")).is_none());
+ }
+
+ #[test]
+ fn collected_mime_normalizes_to_the_allowlist() {
+ assert_eq!(normalize_collected_mime("image/jpeg"), "image/jpeg");
+ assert_eq!(normalize_collected_mime("IMAGE/WebP"), "image/webp");
+ assert_eq!(normalize_collected_mime(" image/png "), "image/png");
+ // Parameters and unknown subtypes are exactly where client text could ride through.
+ assert_eq!(
+ normalize_collected_mime("image/png;evil=payload"),
+ "image/png"
+ );
+ assert_eq!(
+ normalize_collected_mime("image/x-arbitrary-client-text"),
+ "image/png"
+ );
+ assert_eq!(normalize_collected_mime("image/svg+xml"), "image/png");
+ }
+
+ #[test]
+ fn collectable_mime_checks_are_case_insensitive() {
+ // MIME types are case-insensitive; a mixed-case SVG must not dodge the text-format
+ // exclusion, and a mixed-case raster/base64 marker must still collect.
+ assert!(collectable_data_uri_bytes("data:image/SVG+xml;base64,PHN2Zz4=").is_none());
+ assert!(collectable_data_uri_bytes("data:image/Svg+Xml;base64,PHN2Zz4=").is_none());
+ assert_eq!(
+ collectable_data_uri_bytes("data:image/PNG;BASE64,aGVsbG8=").as_deref(),
+ Some(b"hello".as_slice())
+ );
+ }
+}
diff --git a/rust/replay-anonymizer/src/context.rs b/rust/replay-anonymizer/src/context.rs
index 271a9f22bb96..65de575cb4d0 100644
--- a/rust/replay-anonymizer/src/context.rs
+++ b/rust/replay-anonymizer/src/context.rs
@@ -13,6 +13,7 @@ use anyhow::{bail, Result};
use crate::allow_lists::AllowLists;
use crate::assets::PLACEHOLDER_SRC;
use crate::blur::{blank_image_data_uri, blur_image_data_uri, pixelate_raw_rgba};
+use crate::collect::{collectable_data_uri_bytes, CollectedImage, ImageCollection, ImageCollector};
use crate::images::{ImageFallback, ImagePolicy, ImageQueue};
use crate::timings::PhaseTimings;
@@ -21,26 +22,36 @@ use crate::timings::PhaseTimings;
/// fields can't decompress gigabytes serially. Real messages total under 10 MB.
const CV_MESSAGE_DECOMPRESSION_BUDGET: usize = 256 * 1024 * 1024;
-/// Scrub context: the allow lists, the cv decompression budget, the blur memo, and the image
-/// scrub policy (inline blur, or deferred onto the shared worker pool).
+/// Scrub context: the allow lists, the cv decompression budget, the blur memo, the image scrub
+/// policy (inline blur, or deferred onto the shared worker pool), and the optional collection lane.
pub struct Ctx<'a> {
pub allow: &'a AllowLists,
pub cv_budget: Cell<usize>,
// key: the original data URI (data-image blur), or `raw:{w}x{h}:{base64}` (raw RGBA pixelate).
- // value: the blurred result, or `None` when blurring failed (caller falls back to a blank pixel).
+ // value: the replacement — a content ref (collection lane), a blurred data URI — or `None`
+ // when neither could be produced (caller falls back to a blank pixel).
blur_cache: RefCell<HashMap<String, Option<String>>>,
timings: Option<&'a PhaseTimings>,
image_policy: ImagePolicy,
images: ImageQueue,
+ // `Some` routes collectable images to the scrub lane instead of the blur (inline or pooled).
+ collector: Option<RefCell<ImageCollector>>,
}
impl<'a> Ctx<'a> {
pub fn new(allow: &'a AllowLists) -> Self {
- Self::with_options(allow, None, ImagePolicy::Inline)
+ Self::with_options(allow, None, ImagePolicy::Inline, None)
}
pub fn with_timings(allow: &'a AllowLists, timings: Option<&'a PhaseTimings>) -> Self {
- Self::with_options(allow, timings, ImagePolicy::Inline)
+ Self::with_options(allow, timings, ImagePolicy::Inline, None)
+ }
+
+ pub fn with_image_collection(
+ allow: &'a AllowLists,
+ image_collection: Option<ImageCollection>,
+ ) -> Self {
+ Self::with_options(allow, None, ImagePolicy::Inline, image_collection)
}
// pub(crate): the token-patch barriers live only in the kafka snapshot pipeline, so a
@@ -49,6 +60,7 @@ impl<'a> Ctx<'a> {
allow: &'a AllowLists,
timings: Option<&'a PhaseTimings>,
image_policy: ImagePolicy,
+ image_collection: Option<ImageCollection>,
) -> Self {
Self {
allow,
@@ -57,14 +69,19 @@ impl<'a> Ctx<'a> {
timings,
image_policy,
images: ImageQueue::default(),
+ collector: image_collection.map(|c| RefCell::new(ImageCollector::new(c))),
}
}
- /// Scrub one image data URI per the policy: the blurred URI (inline), or a token the patch
- /// pass later replaces (parallel). Failures resolve to `fallback` either way. A message that
- /// exhausts the queued-bytes budget degrades to inline for the remainder — bounded memory,
- /// identical output.
+ /// Scrub one image data URI: the collection lane's content ref when it takes the image (no blur
+ /// work at all — the original bytes ride back to the caller for the out-of-band scrub), else
+ /// per the policy — the blurred URI (inline), or a token the patch pass later replaces
+ /// (parallel). Failures resolve to `fallback` either way. A message that exhausts the
+ /// queued-bytes budget degrades to inline for the remainder — bounded memory, identical output.
pub(crate) fn scrub_image(&self, original: &str, fallback: ImageFallback) -> String {
+ if let Some(collected) = self.collect_image(original) {
+ return collected;
+ }
if self.image_policy == ImagePolicy::Parallel {
if let Some(token) = self.images.submit(
original,
@@ -104,6 +121,14 @@ impl<'a> Ctx<'a> {
}
}
+ /// Drain the collected images (hash-sorted). Empty when collection was off.
+ pub fn into_collected_images(self) -> Vec<CollectedImage> {
+ match self.collector {
+ Some(collector) => collector.into_inner().into_images(),
+ None => Vec::new(),
+ }
+ }
+
/// Restore the full cv decompression budget. The budget bounds one message; per-line callers
/// ([`crate::event::anonymize_line_with_ctx`]) reset it each call so a long session file
/// cannot exhaust it, while the blur memo keeps spanning the whole `Ctx`.
@@ -126,7 +151,8 @@ impl<'a> Ctx<'a> {
// Borrow discipline: never hold a `blur_cache` borrow across the blur call — the compute runs
// borrow-free, so a future blur helper that re-entered `Ctx` still couldn't double-borrow-panic.
- /// Blur a data-image URI, memoized on the URI. `None` → caller falls back to a blank/placeholder.
+ /// Blur a data-image URI inline, memoized on the URI. `None` → caller falls back to a
+ /// blank/placeholder.
pub fn blur_data_uri(&self, original: &str) -> Option<String> {
if let Some(hit) = self.blur_cache.borrow().get(original) {
return hit.clone();
@@ -138,6 +164,22 @@ impl<'a> Ctx<'a> {
result
}
+ /// The collection lane's ref for a data URI, or `None` (collection off, non-collectable URI,
+ /// or a cap hit) — the caller then blurs per the policy as before. Refs are memoized in the
+ /// blur cache so a sprite recurring thousands of times hashes once.
+ fn collect_image(&self, original: &str) -> Option<String> {
+ let collector = self.collector.as_ref()?;
+ if let Some(Some(hit)) = self.blur_cache.borrow().get(original) {
+ return Some(hit.clone());
+ }
+ let bytes = collectable_data_uri_bytes(original)?;
+ let collected = collector.borrow_mut().collect(bytes)?;
+ self.blur_cache
+ .borrow_mut()
+ .insert(original.to_string(), Some(collected.clone()));
+ Some(collected)
+ }
+
/// Pixelate raw RGBA pixels, memoized on dimensions + bytes.
pub fn pixelate_raw(&self, rgba_base64: &str, width: u32, height: u32) -> Option<String> {
let key = format!("raw:{width}x{height}:{rgba_base64}");
diff --git a/rust/replay-anonymizer/src/lib.rs b/rust/replay-anonymizer/src/lib.rs
index ec913f562bfe..6908d43c20f7 100644
--- a/rust/replay-anonymizer/src/lib.rs
+++ b/rust/replay-anonymizer/src/lib.rs
@@ -34,6 +34,8 @@ pub mod bytewalk;
#[doc(hidden)]
pub mod canvas;
#[doc(hidden)]
+pub mod collect;
+#[doc(hidden)]
pub mod compression;
pub mod context;
#[doc(hidden)]
@@ -61,6 +63,7 @@ pub mod url;
pub mod value;
pub use allow_lists::AllowLists;
+pub use collect::ImageCollection;
pub use context::Ctx;
pub use event::{
anonymize_event, anonymize_event_str, anonymize_line, anonymize_line_with_ctx,
diff --git a/rust/replay-anonymizer/src/snapshot.rs b/rust/replay-anonymizer/src/snapshot.rs
index 2c7ae9454d12..292a444729eb 100644
--- a/rust/replay-anonymizer/src/snapshot.rs
+++ b/rust/replay-anonymizer/src/snapshot.rs
@@ -27,6 +27,7 @@ use simd_json::borrowed::Value;
use simd_json::prelude::Writable;
use crate::allow_lists::AllowLists;
+use crate::collect::{CollectedImage, ImageCollection};
use crate::context::Ctx;
use crate::event::{
route_data, route_event, SOURCE_ADOPTED_STYLESHEET, SOURCE_CANVAS_MUTATION, SOURCE_INPUT,
@@ -125,6 +126,14 @@ pub struct EventMeta {
pub href: Option<String>,
}
+/// One collected original image: `offset..offset+len` in [`AnonymizedMessage::image_bytes`].
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct ImageEntry {
+ pub hash: String,
+ pub offset: usize,
+ pub len: usize,
+}
+
/// Message envelope + per-event metadata the TS scaffolding needs for routing/batching.
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
@@ -144,6 +153,9 @@ pub struct SnapshotMeta {
pub console_warn_count: u32,
pub console_error_count: u32,
pub events: Vec<EventMeta>,
+ /// Collected original images (hash-sorted); non-empty only on the image-collection lane.
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub images: Vec<ImageEntry>,
}
/// Which implementation produced the output (tree = the whole-message fallback fired). Both are
@@ -191,6 +203,8 @@ pub struct AnonymizedMessage {
pub lines: Vec<u8>,
pub meta: SnapshotMeta,
pub route: Route,
+ /// Original bytes of the collected images, concatenated in `meta.images` order.
+ pub image_bytes: Vec<u8>,
}
const GZIP_MAGIC: &[u8; 4] = &[0x1f, 0x8b, 0x08, 0x00];
@@ -223,15 +237,16 @@ pub fn anonymize_kafka_payload(
allow: &AllowLists,
payload: &mut [u8],
) -> SResult<AnonymizedMessage> {
- anonymize_kafka_payload_opts(allow, payload, AnonymizeOpts::default())
+ anonymize_kafka_payload_opts(allow, payload, AnonymizeOpts::default(), None)
}
pub fn anonymize_kafka_payload_opts(
allow: &AllowLists,
payload: &mut [u8],
opts: AnonymizeOpts,
+ image_collection: Option<ImageCollection>,
) -> SResult<AnonymizedMessage> {
- anonymize_kafka_payload_timed(allow, payload, opts, None)
+ anonymize_kafka_payload_timed(allow, payload, opts, None, image_collection)
}
/// [`anonymize_kafka_payload_opts`] with a phase-timing sink, which the caller should own outside
@@ -241,8 +256,11 @@ pub fn anonymize_kafka_payload_timed(
payload: &mut [u8],
opts: AnonymizeOpts,
timings: Option<&PhaseTimings>,
+ image_collection: Option<ImageCollection>,
) -> SResult<AnonymizedMessage> {
- contain_panics(|| anonymize_kafka_payload_opts_impl(allow, payload, opts, timings))
+ contain_panics(|| {
+ anonymize_kafka_payload_opts_impl(allow, payload, opts, timings, image_collection)
+ })
}
fn anonymize_kafka_payload_opts_impl(
@@ -250,11 +268,18 @@ fn anonymize_kafka_payload_opts_impl(
payload: &mut [u8],
opts: AnonymizeOpts,
timings: Option<&PhaseTimings>,
+ image_collection: Option<ImageCollection>,
) -> SResult<AnonymizedMessage> {
if let Some((distinct_id_span, data_span)) = scan_outer_envelope(payload) {
// Resolve distinct_id to an owned string first — the unescape below rewrites the buffer.
let Ok(distinct_id) = scan::unescape(payload, distinct_id_span) else {
- return anonymize_kafka_payload_via_parse(allow, payload, opts, timings);
+ return anonymize_kafka_payload_via_parse(
+ allow,
+ payload,
+ opts,
+ timings,
+ image_collection,
+ );
};
let distinct_id = distinct_id.into_owned();
// Point of no return: the in-place unescape consumes the buffer, so failures past here are
@@ -272,9 +297,16 @@ fn anonymize_kafka_payload_opts_impl(
"invalid utf-8 in data string",
));
}
- return anonymize_snapshot_data_inner(allow, &distinct_id, inner, opts, timings);
+ return anonymize_snapshot_data_inner(
+ allow,
+ &distinct_id,
+ inner,
+ opts,
+ timings,
+ image_collection,
+ );
}
- anonymize_kafka_payload_via_parse(allow, payload, opts, timings)
+ anonymize_kafka_payload_via_parse(allow, payload, opts, timings, image_collection)
}
/// Locate the `distinct_id` + `data` string spans by scanning the outer object. `None` means "let
@@ -350,6 +382,7 @@ fn anonymize_kafka_payload_via_parse(
payload: &mut [u8],
opts: AnonymizeOpts,
timings: Option<&PhaseTimings>,
+ image_collection: Option<ImageCollection>,
) -> SResult<AnonymizedMessage> {
reject_if_too_deep(payload, "kafka payload")
.map_err(|e| Failure::new(FailKind::InvalidJson, e.to_string()))?;
@@ -375,7 +408,14 @@ fn anonymize_kafka_payload_via_parse(
};
// Rare path (the scanner bailed): one owned copy buys the in-place processing a mutable buffer.
let mut data_bytes = data.as_bytes().to_vec();
- anonymize_snapshot_data_inner(allow, distinct_id, &mut data_bytes, opts, timings)
+ anonymize_snapshot_data_inner(
+ allow,
+ distinct_id,
+ &mut data_bytes,
+ opts,
+ timings,
+ image_collection,
+ )
}
/// Anonymize the inner `$snapshot_items` event JSON (the payload's `data` string). The buffer is
@@ -386,7 +426,7 @@ pub fn anonymize_snapshot_data(
distinct_id: &str,
inner: &mut [u8],
) -> SResult<AnonymizedMessage> {
- anonymize_snapshot_data_opts(allow, distinct_id, inner, AnonymizeOpts::default())
+ anonymize_snapshot_data_opts(allow, distinct_id, inner, AnonymizeOpts::default(), None)
}
pub fn anonymize_snapshot_data_opts(
@@ -394,8 +434,11 @@ pub fn anonymize_snapshot_data_opts(
distinct_id: &str,
inner: &mut [u8],
opts: AnonymizeOpts,
+ image_collection: Option<ImageCollection>,
) -> SResult<AnonymizedMessage> {
- contain_panics(|| anonymize_snapshot_data_inner(allow, distinct_id, inner, opts, None))
+ contain_panics(|| {
+ anonymize_snapshot_data_inner(allow, distinct_id, inner, opts, None, image_collection)
+ })
}
fn anonymize_snapshot_data_inner(
@@ -404,17 +447,38 @@ fn anonymize_snapshot_data_inner(
inner: &mut [u8],
opts: AnonymizeOpts,
timings: Option<&PhaseTimings>,
+ image_collection: Option<ImageCollection>,
) -> SResult<AnonymizedMessage> {
// No whole-message depth pre-pass here: the byte walk bounds its own recursion and declines
// past its limit, and every recursive parse below is preceded by a span-local
// reject_if_too_deep — so the common all-walked path never pays a depth scan at all.
- let ctx = Ctx::with_options(allow, timings, opts.image_policy);
- match stream_message(&ctx, distinct_id, inner, opts)? {
- Some(msg) => Ok(msg),
+ let ctx = Ctx::with_options(allow, timings, opts.image_policy, image_collection);
+ let mut msg = match stream_message(&ctx, distinct_id, inner, opts)? {
+ Some(msg) => msg,
// Escaped/duplicate envelope keys: only a real parse resolves them, and nothing was
// consumed before the signal, so the tree path re-reads the intact buffer.
- None => anonymize_via_tree_mut(&ctx, distinct_id, inner),
+ None => anonymize_via_tree_mut(&ctx, distinct_id, inner)?,
+ };
+ let (entries, image_bytes) = pack_images(ctx.into_collected_images());
+ msg.meta.images = entries;
+ msg.image_bytes = image_bytes;
+ Ok(msg)
+}
+
+/// Concatenate the collected images into one buffer, describing each slice in an [`ImageEntry`].
+fn pack_images(images: Vec<CollectedImage>) -> (Vec<ImageEntry>, Vec<u8>) {
+ let total: usize = images.iter().map(|i| i.bytes.len()).sum();
+ let mut bytes = Vec::with_capacity(total);
+ let mut entries = Vec::with_capacity(images.len());
+ for image in images {
+ entries.push(ImageEntry {
+ hash: image.hash,
+ offset: bytes.len(),
+ len: image.bytes.len(),
+ });
+ bytes.extend_from_slice(&image.bytes);
}
+ (entries, bytes)
}
const MAX_FAIL_DETAIL: usize = 200;
@@ -821,7 +885,10 @@ fn finish(
console_warn_count: sink.console[1],
console_error_count: sink.console[2],
events: sink.events,
+ // The collector lives on the Ctx, not the Sink; the entry point packs it in.
+ images: Vec::new(),
},
+ image_bytes: Vec::new(),
})
}
diff --git a/rust/replay-anonymizer/tests/bench_images.rs b/rust/replay-anonymizer/tests/bench_images.rs
index d3c100b2ebdf..abefd676d07e 100644
--- a/rust/replay-anonymizer/tests/bench_images.rs
+++ b/rust/replay-anonymizer/tests/bench_images.rs
@@ -91,6 +91,7 @@ fn run(allow: &AllowLists, payload: &[u8], policy: ImagePolicy, iters: usize) ->
image_policy: policy,
..Default::default()
},
+ None,
)
.expect("bench payload must anonymize");
samples.push(start.elapsed().as_micros());
diff --git a/rust/replay-anonymizer/tests/fixtures/image-hash.json b/rust/replay-anonymizer/tests/fixtures/image-hash.json
new file mode 100644
index 000000000000..2e642328653c
--- /dev/null
+++ b/rust/replay-anonymizer/tests/fixtures/image-hash.json
@@ -0,0 +1,38 @@
+[
+ {
+ "name": "empty",
+ "keyAscii": "0123456789abcdef0123456789abcdef",
+ "bytesBase64": "",
+ "hash": "eWzTB4rxRjZ1PSaztVVUIv"
+ },
+ {
+ "name": "ascii-text-bytes",
+ "keyAscii": "0123456789abcdef0123456789abcdef",
+ "bytesBase64": "aGVsbG8gd29ybGQ=",
+ "hash": "YKCxmyvY3S_u1V9Ezm_cXa"
+ },
+ {
+ "name": "png-magic-plus-payload",
+ "keyAscii": "0123456789abcdef0123456789abcdef",
+ "bytesBase64": "iVBORw0KGgpub3QtYS1yZWFsLXBuZy1ib2R5",
+ "hash": "x1ZpYAdJtF5oO67iSJM1z7"
+ },
+ {
+ "name": "binary-256",
+ "keyAscii": "0123456789abcdef0123456789abcdef",
+ "bytesBase64": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==",
+ "hash": "0X79sr0a7jYwl2YxI23_P4"
+ },
+ {
+ "name": "high-bit-heavy",
+ "keyAscii": "0123456789abcdef0123456789abcdef",
+ "bytesBase64": "//79/Pv6+fj39vX08/Lx8O/u7ezr6uno5+bl5OPi4eDf3t3c29rZ2NfW1dTT0tHQz87NzMvKycjHxsXEw8LBwA==",
+ "hash": "8D2F1V0Edx00wAYif5H9zm"
+ },
+ {
+ "name": "ascii-text-bytes-other-key",
+ "keyAscii": "another-content-key-for-parity!!",
+ "bytesBase64": "aGVsbG8gd29ybGQ=",
+ "hash": "o7M8u2_XCjZvDMxbp4P9yV"
+ }
+]
diff --git a/rust/replay-anonymizer/tests/parity.rs b/rust/replay-anonymizer/tests/parity.rs
index c47a91931d2f..e58cbda5a88e 100644
--- a/rust/replay-anonymizer/tests/parity.rs
+++ b/rust/replay-anonymizer/tests/parity.rs
@@ -4,10 +4,11 @@
use std::path::Path;
use std::time::Instant;
+use base64::Engine;
use posthog_replay_anonymizer::allow_lists::AllowLists;
use posthog_replay_anonymizer::{
- anonymize_event_str, anonymize_message, context::Ctx, text::scrub_text, url::scrub_url,
- url::URL_SCHEME_ALLOWLIST,
+ anonymize_event_str, anonymize_message, collect::hash_image_bytes, context::Ctx,
+ text::scrub_text, url::scrub_url, url::URL_SCHEME_ALLOWLIST,
};
use serde_json::Value;
@@ -34,6 +35,25 @@ fn allow_of(case: &Value) -> AllowLists {
AllowLists::new(strings("text"), strings("url"))
}
+#[test]
+fn image_hash_fixtures() {
+ // Pins the keyed content hash against Node `createHmac('sha256', key)` reference vectors —
+ // the consumer trusts the producer, so this fixture is the only cross-implementation check
+ // on the construction (and what the training-side joins implicitly rely on).
+ for case in fixtures("image-hash.json") {
+ let key = case["keyAscii"].as_str().unwrap();
+ let bytes = base64::engine::general_purpose::STANDARD
+ .decode(case["bytesBase64"].as_str().unwrap())
+ .unwrap();
+ assert_eq!(
+ hash_image_bytes(key.as_bytes(), &bytes),
+ case["hash"].as_str().unwrap(),
+ "image hash case: {}",
+ case["name"]
+ );
+ }
+}
+
#[test]
fn text_fixtures() {
for case in fixtures("text.json") {
diff --git a/rust/replay-anonymizer/tests/snapshot.rs b/rust/replay-anonymizer/tests/snapshot.rs
index 15540986dc61..ddb47a702ed4 100644
--- a/rust/replay-anonymizer/tests/snapshot.rs
+++ b/rust/replay-anonymizer/tests/snapshot.rs
@@ -6,12 +6,13 @@
//! tree path plus targeted leak/contract cases.
use posthog_replay_anonymizer::allow_lists::AllowLists;
+use posthog_replay_anonymizer::collect::{hash_image_bytes, image_ref};
use posthog_replay_anonymizer::snapshot::{
anonymize_kafka_payload, anonymize_kafka_payload_opts, anonymize_via_tree, AnonymizeOpts,
AnonymizedMessage, FailKind, Failure, FLAG_ACTIVE, FLAG_CLICK, FLAG_KEYPRESS,
FLAG_MOUSE_ACTIVITY,
};
-use posthog_replay_anonymizer::{Ctx, ImagePolicy};
+use posthog_replay_anonymizer::{Ctx, ImageCollection, ImagePolicy};
use serde_json::{json, Value};
use std::path::Path;
@@ -380,6 +381,7 @@ fn assert_stream_matches_tree(allow: &AllowLists, inner_json: &str, label: &str)
byte_walk,
image_policy,
},
+ None,
);
match (&stream, &tree) {
(Ok(s), Ok(t)) => {
@@ -747,3 +749,139 @@ fn mutation_media_attr_past_the_prescan_budget_declines_to_the_parse() {
"media src past the attribute prescan budget",
);
}
+
+// A 16x16 PNG (the same one the stylesheet test uses), as raw base64 for building data URIs.
+const COLLECT_PNG_B64: &str = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAJUlEQVQokWN4plEBRyInbOAIlzjDINRAjCJk8cGoYRAG60iMBwA8H08Qor0ygQAAAABJRU5ErkJggg==";
+
+fn collect_payload() -> String {
+ let uri = format!("data:image/png;base64,{COLLECT_PNG_B64}");
+ let css = format!(".a{{background:url({uri})}}");
+ payload_of(&snapshot_message(json!([
+ // Media element src, inline rendered pixels, and a CSS background — three distinct
+ // collection funnels, all carrying the same image.
+ {
+ "type": 2,
+ "timestamp": TS0,
+ "data": {
+ "node": {"type": 0, "childNodes": [
+ {"type": 2, "tagName": "img", "attributes": {"src": uri}, "childNodes": []},
+ {"type": 2, "tagName": "div", "attributes": {"rr_dataURL": uri, "_cssText": css}, "childNodes": []}
+ ]},
+ "initialOffset": {"top": 0, "left": 0}
+ }
+ },
+ // Canvas blob carrying the same bytes under a bare base64 payload.
+ {
+ "type": 3,
+ "timestamp": TS0 + 1.0,
+ "data": {"source": 9, "id": 1, "type": 0, "commands": [{"property": "drawImage", "args": [
+ {"rr_type": "Blob", "type": "image/png", "data": [{"rr_type": "ArrayBuffer", "base64": COLLECT_PNG_B64}]}
+ ]}]}
+ },
+ ])))
+}
+
+#[test]
+fn image_collection_replaces_images_with_refs_and_returns_the_bytes() {
+ use base64::Engine;
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let pseudo_team = "0123456789abcdef0123456789abcdef".to_string();
+ let content_key = "fedcba9876543210fedcba9876543210".to_string();
+ let png = base64::engine::general_purpose::STANDARD
+ .decode(COLLECT_PNG_B64)
+ .unwrap();
+ let expected_ref = image_ref(
+ &pseudo_team,
+ &hash_image_bytes(content_key.as_bytes(), &png),
+ );
+
+ // Both image policies: collection must take precedence over the parallel worker pool — a
+ // collected image needs no blur, so it must come back as a ref, never a pool token.
+ for byte_walk in [true, false] {
+ for image_policy in [ImagePolicy::Inline, ImagePolicy::Parallel] {
+ let mut bytes = collect_payload().into_bytes();
+ let out = anonymize_kafka_payload_opts(
+ &allow,
+ &mut bytes,
+ AnonymizeOpts {
+ byte_walk,
+ image_policy,
+ },
+ Some(ImageCollection {
+ pseudo_team: pseudo_team.clone(),
+ content_key: content_key.clone(),
+ }),
+ )
+ .expect("anonymizes (walk={byte_walk})");
+
+ let lines = String::from_utf8(out.lines.clone()).unwrap();
+ assert!(
+ !lines.contains(COLLECT_PNG_B64),
+ "original image must not pass through (walk={byte_walk} images={image_policy:?})"
+ );
+ assert_eq!(
+ lines.matches(&expected_ref).count(),
+ 4,
+ "img src, rr_dataURL, css background, and canvas blob all carry the ref (walk={byte_walk} images={image_policy:?}): {lines}"
+ );
+
+ // One image (deduped across all four funnels), bytes returned verbatim.
+ assert_eq!(out.meta.images.len(), 1, "walk={byte_walk}");
+ let entry = &out.meta.images[0];
+ assert_eq!(entry.hash, hash_image_bytes(content_key.as_bytes(), &png));
+ assert_eq!(entry.offset, 0);
+ assert_eq!(entry.len, png.len());
+ assert_eq!(out.image_bytes, png, "walk={byte_walk}");
+ }
+ }
+}
+
+#[test]
+fn image_collection_off_blurs_inline_and_returns_no_bytes() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let mut bytes = collect_payload().into_bytes();
+ let out = anonymize_kafka_payload_opts(&allow, &mut bytes, AnonymizeOpts::default(), None)
+ .expect("anonymizes");
+ let lines = String::from_utf8(out.lines.clone()).unwrap();
+ assert!(
+ !lines.contains(COLLECT_PNG_B64),
+ "image must still be scrubbed"
+ );
+ assert!(!lines.contains("image:"), "no refs without collection");
+ assert!(out.meta.images.is_empty());
+ assert!(out.image_bytes.is_empty());
+}
+
+#[test]
+fn image_collection_svg_stays_on_the_inline_scrub_path() {
+ // SVG is text — PII inside it must not ride to the scrub topic as an "image".
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ use base64::Engine;
+ let svg = base64::engine::general_purpose::STANDARD.encode(
+ "<svg xmlns='http://www.w3.org/2000/svg'><text>[email protected]</text></svg>",
+ );
+ let inner = snapshot_message(json!([{
+ "type": 2,
+ "timestamp": TS0,
+ "data": {
+ "node": {"type": 0, "childNodes": [
+ {"type": 2, "tagName": "img", "attributes": {"src": format!("data:image/svg+xml;base64,{svg}")}, "childNodes": []}
+ ]},
+ "initialOffset": {"top": 0, "left": 0}
+ }
+ }]));
+ let mut bytes = payload_of(&inner).into_bytes();
+ let out = anonymize_kafka_payload_opts(
+ &allow,
+ &mut bytes,
+ AnonymizeOpts::default(),
+ Some(ImageCollection {
+ pseudo_team: "0123456789abcdef0123456789abcdef".to_string(),
+ content_key: "fedcba9876543210fedcba9876543210".to_string(),
+ }),
+ )
+ .expect("anonymizes");
+ let lines = String::from_utf8(out.lines.clone()).unwrap();
+ assert!(out.meta.images.is_empty(), "svg must not be collected");
+ assert!(!lines.contains(&svg), "raw svg must not pass through");
+}