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.

fix(ai-research): harden the image-scrub write lane (#103737)

Robbiea08d56cc5e22
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md
index bc40adcb1744..5a5f6fd98f4a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md
@@ -23,7 +23,7 @@ Because the batch has no time limit, its duration is set by how many images it h
A batch that outlives `max.poll.interval.ms` (300s) gets the pod evicted mid-batch, and that is not a clean retry: the evicted pod loses the offsets for work it already did, and the partition lands on a pod whose sidecar is equally busy and redoes the same images, so offered load rises while throughput falls.
Keeping batches far inside the interval is what stops ordinary saturation reaching that point.
If a revoke does land mid-batch, the batch stops as soon as a write finds it no longer owns the partitions, rather than scrubbing on and writing a second shard for a span the new owner is already writing.
-The S3 writes of a batch run behind the scrub of the next batch, so the batch duration the consumer reports covers the scrub only; `ml_mirror_image_scrub_consumer_write_duration_seconds` covers the writes.
+The S3 writes run behind the scrub of the next batches, so the batch duration the consumer reports covers the scrub plus any time the batch waited for the write lane to have room (`ml_mirror_image_scrub_consumer_write_wait_seconds`); `ml_mirror_image_scrub_consumer_write_duration_seconds` covers the writes themselves.
A wedged sidecar still blocks its partitions rather than draining them, and no batch size prevents that.
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts
index 20bd78e58a8c..56af639f0dcc 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
@@ -75,6 +75,7 @@ const scrubClient = {
} as unknown as ScrubClient
const options = {
+ flushIntervalMs: 0,
maxImages: 1000,
maxBytes: 1e9,
scrubConcurrency: 4,
@@ -1060,14 +1061,23 @@ describe('ImageBatcher', () => {
const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, recordingClient, options)
await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('first'))])
- await batcher.handleBatch([msg(0, 1, pt(1), Buffer.from('second'))])
+ let secondSettled = false
+ const second = batcher.handleBatch([msg(0, 1, pt(1), Buffer.from('second'))]).then(() => {
+ secondSettled = true
+ })
+ for (let tick = 0; tick < 20; tick++) {
+ await new Promise((resolve) => setImmediate(resolve))
+ }
// Both batches scrubbed while the first write is still held open, and nothing is stored yet.
+ // The second batch then waits at its hand-off, because one write is running and one is queued.
expect(scrubbed).toEqual(['first', 'second'])
expect(store.writes).toHaveLength(0)
expect(offsets.received).toEqual([])
+ expect(secondSettled).toBe(false)
releaseWrite()
+ await second
await batcher.drain()
expect(store.writes.flat()).toHaveLength(2)
@@ -1094,7 +1104,7 @@ describe('ImageBatcher', () => {
expect(maximumActive).toBe(2)
})
- it('waits on the oldest hand-off once two are in flight, so a stalled S3 bounds what a pod holds', async () => {
+ it('waits on the oldest hand-off once one is writing and one is queued, so a stalled S3 bounds what a pod holds', async () => {
const store = new FakeStore()
let releaseWrite = (): void => {}
const writeGate = new Promise<void>((resolve) => (releaseWrite = resolve))
@@ -1106,20 +1116,108 @@ describe('ImageBatcher', () => {
const batcher = new ImageBatcher(store as unknown as ImageShardStore, new FakeOffsets(), scrubClient, options)
await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))])
- await batcher.handleBatch([msg(0, 1, pt(1), Buffer.from('b'))])
- let thirdSettled = false
- const third = batcher.handleBatch([msg(0, 2, pt(1), Buffer.from('c'))]).then(() => {
- thirdSettled = true
+ let secondSettled = false
+ const second = batcher.handleBatch([msg(0, 1, pt(1), Buffer.from('b'))]).then(() => {
+ secondSettled = true
})
for (let tick = 0; tick < 20; tick++) {
await new Promise((resolve) => setImmediate(resolve))
}
- expect(thirdSettled).toBe(false)
+ expect(secondSettled).toBe(false)
releaseWrite()
- await third
+ await second
await batcher.drain()
- expect(store.writes.flat()).toHaveLength(3)
+ expect(store.writes.flat()).toHaveLength(2)
+ })
+
+ it('drains the write lane before a failed batch is raised, so its offsets are stored while Kafka is still connected', async () => {
+ // The Kafka loop disconnects the client as soon as a batch rejects, before shutdown reaches
+ // stop(). A hand-off still writing at that point would find no client for its offsets and its
+ // shards would be written again after the restart.
+ const store = new FakeStore()
+ let releaseWrite = (): void => {}
+ const writeGate = new Promise<void>((resolve) => (releaseWrite = resolve))
+ const writeShard = store.writeShard.bind(store)
+ store.writeShard = async (images) => {
+ await writeGate
+ return writeShard(images)
+ }
+ const offsets = new FakeOffsets()
+ const failingClient = {
+ scrub: (b: Buffer) =>
+ b.toString() === 'boom' ? Promise.reject(new Error('sidecar down')) : Promise.resolve(b),
+ } as unknown as ScrubClient
+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, failingClient, options)
+
+ await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))])
+ let outcome: unknown = 'pending'
+ const failing = batcher.handleBatch([msg(0, 1, pt(1), Buffer.from('boom'))]).then(
+ () => (outcome = 'resolved'),
+ (error) => (outcome = error)
+ )
+ for (let tick = 0; tick < 20; tick++) {
+ await new Promise((resolve) => setImmediate(resolve))
+ }
+ expect(outcome).toBe('pending')
+ expect(offsets.received).toEqual([])
+
+ releaseWrite()
+ await failing
+ expect(outcome).toBeInstanceOf(Error)
+ expect(store.writes.flat()).toHaveLength(1)
+ expect(offsets.received.flat().map((offset) => offset.offset)).toEqual([1])
+ })
+
+ it('accumulates images across batches until the flush interval, so shards stay batched', async () => {
+ // A hand-off per poll would split one team-month across many small shards and multiply the
+ // shard, index and lookup objects per image.
+ const store = new FakeStore()
+ const offsets = new FakeOffsets()
+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, scrubClient, {
+ ...options,
+ flushIntervalMs: 30_000,
+ })
+
+ await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))], 0)
+ await batcher.drain()
+ expect(store.writes).toHaveLength(1)
+
+ await batcher.handleBatch([msg(0, 1, pt(1), Buffer.from('b'))], 1_000)
+ await batcher.handleBatch([msg(0, 2, pt(1), Buffer.from('c'))], 20_000)
+ await batcher.drain()
+ expect(store.writes).toHaveLength(1)
+ expect(offsets.received.flat().map((offset) => offset.offset)).toEqual([1])
+
+ await batcher.handleBatch([msg(0, 3, pt(1), Buffer.from('d'))], 30_000)
+ await batcher.drain()
+ expect(store.writes).toHaveLength(2)
+ expect(store.writes[1]).toHaveLength(3)
+ expect(offsets.received.flat().map((offset) => offset.offset)).toEqual([1, 4])
+ })
+
+ it('hands off the tail of a batch once the interval has passed, even after a capacity hand-off in the same batch', async () => {
+ // The batch clock is read once per batch, so a capacity hand-off must not reset the interval
+ // or the tail behind it would wait for a later batch and hold its offsets uncommitted.
+ const store = new FakeStore()
+ const offsets = new FakeOffsets()
+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, scrubClient, {
+ ...options,
+ flushIntervalMs: 30_000,
+ maxImages: 2,
+ scrubConcurrency: 1,
+ })
+
+ await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))], 0)
+ await batcher.drain()
+ expect(store.writes).toHaveLength(1)
+
+ const late = Array.from({ length: 5 }, (_, i) => msg(0, 1 + i, pt(1), Buffer.from(`late-${i}`)))
+ await batcher.handleBatch(late, 40_000)
+ await batcher.drain()
+
+ expect(store.writes.flat()).toHaveLength(6)
+ expect(offsets.received.at(-1)).toEqual([{ topic: 'session_replay_image_scrub', partition: 0, offset: 6 }])
})
it('stop() waits for the write lane, so finished images reach S3 and their offsets are stored', async () => {
@@ -1170,8 +1268,10 @@ describe('ImageBatcher', () => {
const batcher = new ImageBatcher(store as unknown as ImageShardStore, revoked, scrubClient, options)
await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))])
- await batcher.handleBatch([msg(0, 1, pt(1), Buffer.from('b'))])
+ // The second batch queues its hand-off behind the gated first one and waits for it.
+ const second = batcher.handleBatch([msg(0, 1, pt(1), Buffer.from('b'))])
releaseWrite()
+ await second
await batcher.drain()
expect(store.writes.flat()).toHaveLength(1)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts
index 18f62438da2f..fea4a7839752 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
@@ -114,6 +114,8 @@ interface SettledScrub {
}
export interface ImageBatcherOptions {
+ /** How long scrubbed images accumulate before a hand-off, so images of one team-month across several polls share a shard. */
+ flushIntervalMs: number
maxImages: number
maxBytes: number
scrubConcurrency: number
@@ -125,17 +127,21 @@ export interface ImageBatcherOptions {
*
* A batch's images spread over as many shard groups as it has team-months, which is most of them,
* so written one after another the groups cost a round trip each and the sidecar idles for the sum.
- * Written together they cost about one. Bounded so a burst cannot exhaust the S3 client's socket
- * pool, and separate from the scrub concurrency so a write never takes a slot from the next batch.
+ * Written together they cost about one. Bounded so that, together with the store's own lookup
+ * limiter, a burst stays under the S3 client's socket pool, and separate from the scrub concurrency
+ * so a write never takes a slot from the next batch.
*/
export const WRITE_CONCURRENCY = 8
/**
- * Hand-offs the write lane may hold before the scrub waits on it: one writing, one queued.
+ * Hand-offs the write lane may hold: one writing, one queued. A batch that hands off while both
+ * are held waits for the oldest to finish before it continues.
*
- * Writes run behind the scrub of the next batch, so an S3 slowdown would otherwise queue hand-offs
- * without limit and hold their images in memory. Waiting on the oldest hand-off bounds that at
- * two batches of scrubbed output plus the batch in flight.
+ * Writes run behind the scrub of the next batches, so an S3 slowdown would otherwise queue
+ * hand-offs without limit and hold their images in memory. The wait bounds resident scrubbed output
+ * at two hand-offs plus what the running batch has staged, and the hand-off being written is copied
+ * twice more (Buffer.concat, then the encryption envelope). That multiplier is what the MAX_BYTES
+ * comment in ml-mirror/config.ts states, so change both together.
*/
const MAX_WRITES_IN_FLIGHT = 2
@@ -166,6 +172,13 @@ export class ImageBatcher {
private outgoing: ScrubbedRef[] = []
private outgoingBytes = 0
private outgoingOffsets = new Map<string, TopicPartitionOffset>()
+ /**
+ * When an interval-driven hand-off last happened. Undefined until the first one, so the first
+ * batch does not wait a whole interval. Capacity hand-offs do not reset it: the batch clock is
+ * read once per batch, so a reset would leave the tail behind a capacity hand-off waiting for a
+ * later batch with its offsets uncommitted.
+ */
+ private lastHandOffMs: number | undefined
/**
* Writes hand-offs one at a time, in the order the batches retired them.
*
@@ -267,7 +280,7 @@ export class ImageBatcher {
}
}
- public async handleBatch(messages: Message[]): Promise<void> {
+ public async handleBatch(messages: Message[], nowMs = Date.now()): Promise<void> {
if (this.stopping) {
return
}
@@ -279,7 +292,7 @@ export class ImageBatcher {
const controller = new AbortController()
this.activeBatch = controller
this.partitionsRevoked = false
- const running = this.handleActiveBatch(messages, controller)
+ const running = this.handleActiveBatch(messages, controller, nowMs)
this.activeBatchSettled = running.then(
() => undefined,
() => undefined
@@ -287,9 +300,21 @@ export class ImageBatcher {
try {
await running
} catch (error) {
- if (!(this.stopping && error instanceof ScrubAborted)) {
- throw error
+ if (this.stopping && error instanceof ScrubAborted) {
+ return
+ }
+ // The Kafka loop disconnects the client as soon as this rejects, before shutdown reaches
+ // stop(), so a hand-off still writing would find no client to store its offsets with and
+ // its shards would be written again after the restart. A poisoned lane has nothing left
+ // that could store, so its own failure is raised straight away.
+ if (error !== this.writeFailure) {
+ // Logged rather than raised, so the batch failure stays the one the process exits on,
+ // and the storage failure behind it is still on record for whoever reads the logs.
+ await this.drain().catch((writeError) =>
+ logger.error('🔥', 'image_scrub_write_failed_behind_failed_batch', { error: String(writeError) })
+ )
}
+ throw error
} finally {
// Cleared here rather than on the success path: a throwing batch that left this set would
// have shutdown abort a controller belonging to a batch that is already over.
@@ -297,7 +322,7 @@ export class ImageBatcher {
}
}
- private async handleActiveBatch(messages: Message[], controller: AbortController): Promise<void> {
+ private async handleActiveBatch(messages: Message[], controller: AbortController, nowMs: number): Promise<void> {
// Skips resolve up front so the window only ever holds real work: a duplicate admitted into a
// slot would occupy it and complete instantly, spending the pod's concurrency on no-ops.
if (messages.length) {
@@ -363,7 +388,7 @@ export class ImageBatcher {
ImageScrubConsumerMetrics.startBatch()
}
try {
- await this.scrubAndStage(messages, planned, controller)
+ await this.scrubAndStage(messages, planned, controller, nowMs)
} finally {
// Empty polls arrive on a timer under callEachBatchWhenEmpty and would otherwise bury
// the real distribution of both histograms in a zero bucket.
@@ -381,7 +406,8 @@ export class ImageBatcher {
private async scrubAndStage(
messages: Message[],
planned: PlannedScrub[],
- controller: AbortController
+ controller: AbortController,
+ nowMs: number
): Promise<void> {
let spanStart = 0
let nextToSubmit = 0
@@ -408,7 +434,7 @@ export class ImageBatcher {
}
// Only reachable over capacity with work left: hand off to make room rather than spin.
if (inFlight.size === 0) {
- await this.handOff()
+ await this.handOffOrAbort(controller)
if (this.partitionsRevoked) {
break
}
@@ -470,7 +496,7 @@ export class ImageBatcher {
spanStart = spanEnd
}
if (this.overCapacity(stagedCount, stagedBytes)) {
- await this.handOff()
+ await this.handOffOrAbort(controller)
}
if (this.partitionsRevoked) {
controller.abort()
@@ -495,7 +521,22 @@ export class ImageBatcher {
}
// A batch whose tail is all skips, or which is nothing but skips, still has to move offsets.
this.recordOffsets(messages.slice(spanStart))
- await this.handOff()
+ // nowMs is the batch's start. A batch that crosses the interval leaves its tail to the next
+ // poll, and empty polls run this check too, so that is at most one poll timeout later.
+ if (this.lastHandOffMs === undefined || nowMs - this.lastHandOffMs >= this.options.flushIntervalMs) {
+ this.lastHandOffMs = nowMs
+ await this.handOff()
+ }
+ }
+
+ /** A rejected wait on the lane ends the batch like a failed scrub does: the sidecar must not keep working on results nobody will read. */
+ private async handOffOrAbort(controller: AbortController): Promise<void> {
+ try {
+ await this.handOff()
+ } catch (error) {
+ controller.abort()
+ throw error
+ }
}
/**
@@ -520,8 +561,13 @@ export class ImageBatcher {
}
}
void write.then(forget, forget)
- if (this.writesInFlight.length > MAX_WRITES_IN_FLIGHT) {
- await this.writesInFlight[0]
+ if (this.writesInFlight.length >= MAX_WRITES_IN_FLIGHT) {
+ const waitedFrom = performance.now()
+ try {
+ await this.writesInFlight[0]
+ } finally {
+ ImageScrubConsumerMetrics.observeWriteWait((performance.now() - waitedFrom) / 1000)
+ }
}
}
@@ -532,6 +578,11 @@ export class ImageBatcher {
// Found by the hand-off ahead of this one, whose offsets could not be stored: the span belongs
// to another pod now, and writing it here would leave a second shard under a random key.
if (this.partitionsRevoked) {
+ logger.warn('🔁', 'image_scrub_handoff_discarded_after_revoke', {
+ images: handoff.images.length,
+ partitions: handoff.offsets.map((offset) => offset.partition),
+ })
+ ImageScrubConsumerMetrics.incOffsetsDiscarded(handoff.offsets.length)
this.forgetUnwritten(handoff.images)
return
}
@@ -544,9 +595,9 @@ export class ImageBatcher {
}
ImageScrubConsumerMetrics.incBatchFailed('write')
throw error
- } finally {
- ImageScrubConsumerMetrics.observeWrite((performance.now() - startedAt) / 1000)
}
+ // Observed on success only, so an S3 incident's retry budgets do not read as slow writes.
+ ImageScrubConsumerMetrics.observeWrite((performance.now() - startedAt) / 1000)
}
/** Retains nothing between batches, so unlike [[seenRefs]] this dedup cannot be sized wrong or disabled. */
@@ -893,6 +944,11 @@ export class ImageBatcher {
*
* The disconnected client throws a plain Error with no code at all, which is the same situation
* arriving during shutdown, so it is tolerated on the same grounds.
+ *
+ * The write lane runs while the loop keeps polling, so a revoke can also land while a hand-off
+ * is still writing. Its offsets are discarded here and the new owner rescrubs that span, which
+ * can cost MAX_WRITES_IN_FLIGHT hand-offs per pod per rebalance. That is the accepted price of
+ * overlapping the writes, and incOffsetsDiscarded is where it shows.
*/
private storeOffsetsUnlessRevoked(offsets: TopicPartitionOffset[]): void {
try {
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 ac937c3b8f2e..146fb92cada9 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts
@@ -106,14 +106,19 @@ export class ImageScrubConsumerMetrics {
})
private static readonly batchDuration = new Histogram({
name: 'ml_mirror_image_scrub_consumer_batch_duration_seconds',
- help: 'Wall time per poll batch, from its first scrub until its images are handed to the write lane; the S3 writes run behind the next batch and are timed by write_duration_seconds. Read against Kafka max.poll.interval.ms (300s): batches approaching it get the pod evicted mid-batch, and the partition is redone by whoever picks it up',
+ help: 'Wall time per poll batch, from its first scrub until its images are handed to the write lane, including any wait for the lane to have room (write_wait_seconds); the S3 writes themselves run behind the next batch and are timed by write_duration_seconds. Read against Kafka max.poll.interval.ms (300s): batches approaching it get the pod evicted mid-batch, and the partition is redone by whoever picks it up',
buckets: [1, 5, 15, 30, 60, 120, 240, 300, 600],
})
private static readonly writeDuration = new Histogram({
name: 'ml_mirror_image_scrub_consumer_write_duration_seconds',
- help: 'Wall time one hand-off spends writing its shards, URL images and offsets, excluding the wait behind the previous hand-off. It overlaps the next batch, so it only costs throughput once it exceeds batch_duration_seconds',
+ help: 'Wall time one successful hand-off spends writing its shards, URL images and offsets, excluding the wait behind the previous hand-off. It overlaps the next batch, so it only costs throughput once it exceeds batch_duration_seconds',
buckets: [0.1, 0.5, 1, 2, 5, 15, 30, 60, 120],
})
+ private static readonly writeWait = new Histogram({
+ name: 'ml_mirror_image_scrub_consumer_write_wait_seconds',
+ help: 'Time a batch spent blocked because the write lane already held one writing and one queued hand-off. This is the only place S3 latency reaches the scrub, so a rising value means S3, not the sidecar, is what is slow',
+ buckets: [0.01, 0.1, 0.5, 1, 2, 5, 15, 30, 60, 120],
+ })
private static activeBatchStartedAtMs: number | undefined
private static readonly activeBatchElapsed = new Gauge({
name: 'ml_mirror_image_scrub_consumer_active_batch_elapsed_seconds',
@@ -197,6 +202,9 @@ export class ImageScrubConsumerMetrics {
public static observeWrite(durationSeconds: number): void {
this.writeDuration.observe(durationSeconds)
}
+ public static observeWriteWait(durationSeconds: number): void {
+ this.writeWait.observe(durationSeconds)
+ }
public static startBatch(nowMs = performance.now()): void {
this.activeBatchStartedAtMs = nowMs
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
index 03f1f0db3028..c1eeb1833f73 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
@@ -170,8 +170,9 @@ export type MlMirrorConfig = {
SESSION_RECORDING_ML_IMAGE_SCRUB_GROUP_ID: string
SESSION_RECORDING_ML_IMAGE_SCRUB_PREFIX: string
SESSION_RECORDING_ML_IMAGE_SCRUB_SIDECAR_URL: string
+ SESSION_RECORDING_ML_IMAGE_SCRUB_FLUSH_INTERVAL_MS: number
SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_IMAGES: number
- // Real peak memory is ~2x this: the flush does a Buffer.concat copy.
+ // Real peak memory is about 5x this: the running batch's staged images, one hand-off queued, and one hand-off writing, which is copied by Buffer.concat and again by the encryption envelope (MAX_WRITES_IN_FLIGHT in image-batcher.ts).
SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_BYTES: number
SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_CONCURRENCY: number
/**
@@ -180,7 +181,7 @@ export type MlMirrorConfig = {
* per entry, of which lru-cache commits about an eighth up front by preallocating its backing
* arrays. Sized against the 2000M consumer container in
* https://github.com/PostHog/charts/blob/main/apps/ingestion-sessionreplay-ml-image-scrub/values.yaml,
- * which also has to hold MAX_BYTES of scrubbed images at ~2x during a flush. Start low and raise
+ * which also has to hold about 5x MAX_BYTES of scrubbed images while the write lane is full. Start low and raise
* it off ml_mirror_ref_cache_capacity_probe_total rather than guessing.
*
* 0 disables only this cross-batch cache; duplicates within a poll batch always collapse.
@@ -208,7 +209,7 @@ export type MlMirrorConfig = {
SESSION_RECORDING_ML_IMAGE_SCRUB_DLQ_TOPIC: string
/** Messages per poll. Bounds batch wall time against Kafka's max.poll.interval.ms (300s). */
SESSION_RECORDING_ML_IMAGE_SCRUB_BATCH_SIZE: number
- // Per-write timeout (the S3 client has no built-in one). A flush does two writes, so it bounds at 2x this.
+ // Per-write timeout (the S3 client has no built-in one). A hand-off writes its shard groups concurrently, each as a shard, an index and per-image lookups, so a hand-off bounds at 3x this plus the lookup budget.
SESSION_RECORDING_ML_IMAGE_SCRUB_S3_WRITE_TIMEOUT_MS: number
}
@@ -274,6 +275,7 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {
SESSION_RECORDING_ML_IMAGE_SCRUB_PREFIX: 'scrubbed-images',
// 127.0.0.1, not localhost: the sidecar binds IPv4 loopback, and localhost can resolve to ::1 first.
SESSION_RECORDING_ML_IMAGE_SCRUB_SIDECAR_URL: 'http://127.0.0.1:9010',
+ SESSION_RECORDING_ML_IMAGE_SCRUB_FLUSH_INTERVAL_MS: 30 * 1000,
SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_IMAGES: 1000,
SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_BYTES: 128 * 1024 * 1024,
SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_CONCURRENCY: 8,
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.ts
index def16b1c5cc7..db74bb909010 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.ts
@@ -102,6 +102,7 @@ export class IngestionSessionReplayMlImageScrubServer extends MlMirrorConsumerSe
consumer,
scrubClient,
{
+ flushIntervalMs: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_FLUSH_INTERVAL_MS,
maxImages: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_IMAGES,
maxBytes: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_BYTES,
scrubConcurrency: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_CONCURRENCY,
@@ -113,7 +114,7 @@ export class IngestionSessionReplayMlImageScrubServer extends MlMirrorConsumerSe
await scrubClient.waitUntilReachable()
await consumer.connect((messages) => {
const heartbeat = setInterval(() => consumer.heartbeat(), BATCH_HEARTBEAT_INTERVAL_MS)
- return batcher.handleBatch(messages).finally(() => clearInterval(heartbeat))
+ return batcher.handleBatch(messages, Date.now()).finally(() => clearInterval(heartbeat))
})
this.lifecycle.services.push({
diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.md
index 4296dc67146c..2df2ef38f29b 100644
--- a/products/ai_training/docs/replay-data.md
+++ b/products/ai_training/docs/replay-data.md
@@ -209,8 +209,8 @@ Consumers reject malformed UUIDv7 session identifiers before reading DynamoDB.
Oversized identifiers cannot fail a whole bulk key lookup.
Inline images have an encrypted lookup for each reference, published after the shard and its index.
Readers fetch that lookup directly; a missing image does not require a scan of the team's image history.
-The image scrubber writes the shards of one poll batch while it scrubs the next batch, and writes the shard groups of a batch concurrently.
-The offsets of a batch are stored after its writes complete, in batch order, so a failed write stops every later store and the pod replays from the last stored offset.
+The image scrubber hands the images it scrubbed to a write lane every 30 seconds or when its buffer is full, writes them while it scrubs the next batches, and writes the shard groups of one hand-off concurrently.
+The offsets of a hand-off are stored after its writes complete, in hand-off order, so a failed write stops every later store and the pod replays from the last stored offset.
Source deduplication includes the session, so deleting one source session cannot suppress another session's copy.
The v2 image-fetch frontier uses a separate, initially empty DynamoDB history table.
Its URL history expires eight days after the end of the session's UTC month.