:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(replay): stop a busy scrub sidecar crash-looping the consumer (#73726)
Robbiedfd0f9e5df19
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.mdindex f14009489c62..b7a83d03e9de 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@@ -10,7 +10,14 @@ It runs a simple http server, receives an image and replies with the scrubbed im## HTTP contract-`POST /scrub` with the raw image bytes returns the scrubbed bytes (200). The status split is load-bearing and both sides must change together: the consumer permanently skips 413 (too large) and 422 (undecodable), and retries then replays 500 (transient) and 503 (busy). See `scrub-client.ts` for the consumer half.+`POST /scrub` with the raw image bytes returns the scrubbed bytes (200). The status split is load-bearing and both sides must change together: the consumer permanently skips 413 (too large) and 422 (undecodable), and retries then **drops** the image on 500 (transient) and 503 (busy). See `scrub-client.ts` for the consumer half.++A dropped image is counted in `ml_mirror_image_scrub_consumer_dropped_total` and never reaches the bucket, so the failure costs coverage rather than leaking content.+It used to fail the Kafka batch instead, which exits the consumer process: a saturated sidecar therefore crash-looped its pod, and the partitions it gave up landed on pods that were equally saturated, so saturation spread rather than eased.+Nothing about a busy or unreachable sidecar should ever take the consumer down, because the sidecar is a separate container that a consumer restart does not fix.++`maxConcurrency` is derived from `SCRUB_WORKERS` rather than set independently, so the sidecar sheds load it cannot execute instead of admitting it into an accept queue.+That matters because the consumer's per-request timeout is an inactivity timeout: a queued request sends no bytes, so queueing reads to the consumer as an unresponsive sidecar rather than a busy one, and a fast 503 is the signal it can actually act on.## The scrubdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/config.tsindex 4fb55e2cddd7..9fc7ed74a00f 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/config.ts@@ -1,5 +1,17 @@+import { SCRUB_WORKERS } from './cores.ts'import { numFromEnv } from './env.ts'+/**+ * Requests admitted per worker.+ *+ * One would leave a worker idle for the width of a request body while the next one is read, so the+ * spare slot per worker is what keeps them fed. More than that is queue, and queue is the thing to+ * avoid: an admitted request produces no bytes until a worker frees up, and the consumer's timeout+ * is an inactivity timeout, so queueing reads to it as an unresponsive sidecar rather than as a busy+ * one. Shedding early gives it a 503 it can act on immediately.+ */+const ADMITTED_PER_WORKER = 2+export interface Config {port: number// Loopback-only /scrub must not be reachable off-pod, but Prometheus scrapes the pod IP, so /metrics + health@@ -24,7 +36,10 @@ export function loadConfig(): Config {return {port: numFromEnv('IMAGE_SCRUB_PORT', 9010, 1, 65535),metricsPort: numFromEnv('IMAGE_SCRUB_METRICS_PORT', 9011, 1, 65535),- maxConcurrency: numFromEnv('IMAGE_SCRUB_CONCURRENCY', 8, 1, 256),+ // Derived from the worker count rather than fixed, so the two cannot drift apart. A fixed 8+ // against a pod that could execute fewer left the difference sitting in the accept queue,+ // where it timed out the consumer instead of being shed.+ maxConcurrency: numFromEnv('IMAGE_SCRUB_CONCURRENCY', ADMITTED_PER_WORKER * SCRUB_WORKERS, 1, 256),maxBodyBytes: numFromEnv('IMAGE_SCRUB_MAX_BODY_BYTES', 20 * 1024 * 1024, 1024, 512 * 1024 * 1024),jobTimeoutMs: numFromEnv('IMAGE_SCRUB_JOB_TIMEOUT_MS', 15_000, 1000, 600_000),}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.tsindex 4a33dc78cfd8..e9d1ab1b7234 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@@ -3,7 +3,7 @@ import { Message, TopicPartitionOffset } from 'node-rdkafka'import { hashImageBytes, imageRef } from './content-ref'import { ImageBatcher, OffsetStore } from './image-batcher'import { ImageShardStore, ScrubbedImage } from './image-shard-store'-import { ScrubClient } from './scrub-client'+import { ScrubClient, ScrubUnavailable } from './scrub-client'const pt = (n: number): string => String(n).padStart(32, '0')const CONTENT_KEY = 'fedcba9876543210fedcba9876543210'@@ -482,7 +482,10 @@ describe('ImageBatcher', () => {).toThrow('scrubConcurrency')})- it('aborts the batch and replays when scrubbing exceeds the deadline', async () => {+ it('drops the images still in flight when scrubbing exceeds the deadline, without failing the batch', async () => {+ // Every capacity failure has to end this way, the deadline included. It reaches the batch as+ // whatever the concurrency controller rejects an aborted job with rather than as a scrub+ // error, so classifying by error type alone leaves this one path still killing the pod.const store = new FakeStore()const offsets = new FakeOffsets()const hangingClient = { scrub: () => new Promise<Buffer>(() => {}) } as unknown as ScrubClient@@ -494,8 +497,79 @@ describe('ImageBatcher', () => {0)- await expect(batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))], 1)).rejects.toThrow()- expect(offsets.stored).toBe(0)+ await expect(batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))], 1)).resolves.toBeUndefined()+ expect(store.writes).toHaveLength(0)+ })++ it('drops an image the sidecar has no capacity for instead of failing the batch', async () => {+ // The lane's crash loop: a saturated sidecar times out, the batch rethrows, and the Kafka+ // loop exits the process on any throw. The partitions then land on pods that are just as+ // busy, so every pod took its turn dying and the lane never recovered on its own.+ const store = new FakeStore()+ const offsets = new FakeOffsets()+ const busyClient = {+ scrub: () => Promise.reject(new ScrubUnavailable('scrub request timed out')),+ } as unknown as ScrubClient+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, busyClient, options, 0)++ await expect(+ batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a')), msg(0, 1, pt(1), Buffer.from('b'))], 1)+ ).resolves.toBeUndefined()expect(store.writes).toHaveLength(0)+ expect(offsets.received.flat().map((o) => o.offset)).toEqual([2])+ })++ it('leaves a dropped ref unmarked so a later copy still gets scrubbed', async () => {+ // The drop must not look like the permanent 422 rejection, which does mark the ref. Marking+ // here would let one busy moment permanently exclude that image from the mirror.+ let attempts = 0+ const busyOnceClient = {+ scrub: (b: Buffer) => {+ attempts += 1+ return attempts === 1+ ? Promise.reject(new ScrubUnavailable('sidecar responded 503'))+ : Promise.resolve(b)+ },+ } as unknown as ScrubClient+ const store = new FakeStore()+ const batcher = new ImageBatcher(+ store as unknown as ImageShardStore,+ new FakeOffsets(),+ busyOnceClient,+ options,+ 0+ )+ const sprite = Buffer.from('sprite')++ await batcher.handleBatch([msg(0, 0, pt(1), sprite)], 1)+ await batcher.handleBatch([msg(0, 0, pt(1), sprite)], 2)++ expect(store.writes.flat()).toHaveLength(1)+ })++ it('discards offsets for a partition a rebalance already revoked, rather than exiting', async () => {+ // librdkafka raises ERR__STATE for a partition we no longer hold. The shard is already on S3,+ // so the span simply rescrubs under its new owner. Propagating it exits the process, and a+ // pod exiting is itself what triggers the next rebalance.+ const store = new FakeStore()+ const revoked = new FakeOffsets()+ revoked.offsetsStore = () => {+ throw Object.assign(new Error('Local: Erroneous state'), { code: -172 })+ }+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, revoked, scrubClient, options, 0)++ await expect(batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))], 1)).resolves.toBeUndefined()+ expect(store.writes).toHaveLength(1)+ })++ it('still fails the batch when storing offsets fails for any other reason', async () => {+ const store = new FakeStore()+ const broken = new FakeOffsets()+ broken.offsetsStore = () => {+ throw Object.assign(new Error('Broker: Not coordinator'), { code: 16 })+ }+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, broken, scrubClient, options, 0)++ await expect(batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))], 1)).rejects.toThrow('Not coordinator')})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.tsindex a36eaa03f562..abef2f5f13a1 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts@@ -1,4 +1,4 @@-import { Message, TopicPartitionOffset } from 'node-rdkafka'+import { LibrdKafkaError, Message, TopicPartitionOffset } from 'node-rdkafka'import { findOffsetsToCommit } from '~/common/kafka/consumer/consumer-v1'import { ConcurrencyController } from '~/common/utils/concurrencyController'@@ -7,12 +7,15 @@ import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-deimport { parseImageRef } from './content-ref'import { ImageShardStore, ScrubbedImage } from './image-shard-store'import { ImageScrubConsumerMetrics } from './metrics'-import { ScrubClient } from './scrub-client'+import { ScrubClient, ScrubUnavailable } from './scrub-client'export interface OffsetStore {offsetsStore(offsets: TopicPartitionOffset[]): void}+/** librdkafka's RD_KAFKA_RESP_ERR__STATE, which offsetsStore raises for a partition we no longer hold. */+const ERR__STATE = -172+/** The batch index is what lets offsets advance across the messages planning skipped. */interface PlannedScrub {index: number@@ -104,6 +107,11 @@ export class ImageBatcher {// the sidecar.const controller = new AbortController()let scrubBudgetMs = this.options.maxBatchScrubMs+ // Set by the deadline rather than inferred from the error, because the abort surfaces as+ // whatever the concurrency controller rejects with and not as a scrub error at all. Reading+ // it back off the error is how the deadline stayed fatal while every other capacity failure+ // was made survivable, which would have moved the crash rather than removed it.+ let deadlineExpired = falselet spanStart = 0let nextToSubmit = 0let retired = 0@@ -133,7 +141,10 @@ export class ImageBatcher {}const waitStartMs = performance.now()- const timer = setTimeout(() => controller.abort(), scrubBudgetMs)+ const timer = setTimeout(() => {+ deadlineExpired = true+ controller.abort()+ }, scrubBudgetMs)let done: SettledScrubtry {done = await Promise.race(inFlight.values())@@ -143,9 +154,16 @@ export class ImageBatcher {}inFlight.delete(done.slot)if (done.error !== undefined) {- controller.abort() // one failure dooms the batch, so cancel the siblings still in flight- ImageScrubConsumerMetrics.incBatchFailed('scrub')- throw done.error+ if (!deadlineExpired && !(done.error instanceof ScrubUnavailable)) {+ controller.abort() // one failure dooms the batch, so cancel the siblings still in flight+ ImageScrubConsumerMetrics.incBatchFailed('scrub')+ throw done.error+ }+ // The sidecar could not take this image. Losing it costs one frame from a best-effort+ // mirror, and the ref is deliberately left unmarked so a later copy still gets a turn.+ // Failing the batch instead costs the pod, because the Kafka loop exits the process on+ // any throw, and the partitions it was holding land on pods that are already as busy.+ ImageScrubConsumerMetrics.incDropped()}if (done.scrubbed) {staged[done.slot] = done.scrubbed@@ -288,8 +306,27 @@ export class ImageBatcher {this.bufferBytes = 0}if (this.pendingOffsets.size > 0) {- this.offsetStore.offsetsStore([...this.pendingOffsets.values()])+ this.storeOffsetsUnlessRevoked([...this.pendingOffsets.values()])this.pendingOffsets.clear()}}++ /**+ * librdkafka refuses to store an offset for a partition this consumer no longer holds, raising+ * ERR__STATE. A rebalance during a batch is ordinary, and the shard is already on S3 by this+ * point, so the only thing lost is the record of how far we got: whoever picks the partition up+ * rescrubs from the last committed offset, which is the at-least-once behaviour a restart has+ * always had. Letting it propagate exited the process instead, and since a pod exiting triggers+ * the next rebalance, the condition kept producing itself.+ */+ private storeOffsetsUnlessRevoked(offsets: TopicPartitionOffset[]): void {+ try {+ this.offsetStore.offsetsStore(offsets)+ } catch (error) {+ if ((error as LibrdKafkaError | undefined)?.code !== ERR__STATE) {+ throw error+ }+ ImageScrubConsumerMetrics.incOffsetsDiscarded(offsets.length)+ }+ }}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.tsindex 9664cfa02464..3bd4f5e03981 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@@ -44,6 +44,21 @@ export class ImageScrubConsumerMetrics {name: 'ml_mirror_image_scrub_consumer_shard_bytes_total',help: 'Scrubbed image bytes written into shards',})+ /**+ * The lane's data-loss signal, and the one to alert on. Every drop here is an image that reached+ * the consumer and will never reach the bucket, because the sidecar had no capacity for it inside+ * the batch's budget. A low background rate is the shape of a lane running near its ceiling; a+ * rate approaching `scrubbed` means the sidecar is effectively down, which no longer announces+ * itself by crash-looping the pods.+ */+ private static readonly dropped = new Counter({+ name: 'ml_mirror_image_scrub_consumer_dropped_total',+ help: 'Images dropped because the sidecar had no capacity for them (busy, timed out, or the batch scrub budget expired). Never published, so this is lost coverage rather than leaked content',+ })+ private static readonly offsetsDiscarded = new Counter({+ name: 'ml_mirror_image_scrub_consumer_offsets_discarded_total',+ help: 'Offsets that could not be stored because a rebalance had already revoked the partition, so that span rescrubs under its new owner',+ })private static readonly batchFailed = new Counter({name: 'ml_mirror_image_scrub_consumer_batch_failed_total',help: 'Batches that threw and will replay, by cause (scrub or write)',@@ -59,6 +74,12 @@ export class ImageScrubConsumerMetrics {public static incSkipped(): void {this.skipped.inc()}+ public static incDropped(): void {+ this.dropped.inc()+ }+ public static incOffsetsDiscarded(count: number): void {+ this.offsetsDiscarded.inc(count)+ }public static incDeduped(scope: 'batch' | 'pod'): void {this.deduped.labels(scope).inc()}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.tsindex 073f212f78ad..f3d2f2a72334 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.ts@@ -4,7 +4,20 @@ import { promiseRetry } from '~/common/utils/retries'class PermanentScrubReject extends Error {}-class ScrubAborted extends Error {}+/**+ * The sidecar had no capacity for this image: it shed the load, or it never answered inside the+ * request timeout, or the batch ran out of scrub budget while the image was queued.+ *+ * Separated from every other failure because the two need opposite handling. A verdict on the image+ * or a broken sidecar is worth failing the batch over; being busy is not, and treating it that way+ * crash-looped the lane. The consumer's per-request timeout is an inactivity timeout, so an image+ * merely sitting in the sidecar's accept queue trips it, and the retries queue behind the same jam.+ * Every pod then exited on a saturated sidecar, which handed its partitions to the pods that were+ * already saturating, so saturation spread instead of easing.+ */+export class ScrubUnavailable extends Error {}++class ScrubAborted extends ScrubUnavailable {}export class ScrubClient {private readonly url: URL@@ -17,6 +30,14 @@ export class ScrubClient {this.url = new URL('/scrub', baseUrl)}+ /**+ * Scrubbed bytes, or null when the sidecar permanently rejected the content (422/413).+ *+ * Anything else throws [[ScrubUnavailable]], and only that: every way the sidecar can fail to+ * return bytes is a fact about this one image plus the sidecar's current load, never a reason to+ * bring the consumer down. The caller decides what to do with a single lost image; it used to+ * have no choice, because the failure reached the Kafka loop, which exits the process.+ */public async scrub(bytes: Buffer, signal?: AbortSignal): Promise<Buffer | null> {try {return await promiseRetry(@@ -27,14 +48,14 @@ export class ScrubClient {const { status, body } = await this.post(bytes, signal)if (status === 200) {if (body.length === 0) {- throw new Error('sidecar returned an empty 200 body')+ throw new ScrubUnavailable('sidecar returned an empty 200 body')}return body}if (status === 422 || status === 413) {throw new PermanentScrubReject(`sidecar rejected the input (${status})`)}- throw new Error(`sidecar responded ${status}`)+ throw new ScrubUnavailable(`sidecar responded ${status}`)},'image-scrub-sidecar',// promiseRetry count is total attempts; +1 makes maxRetries mean retries after the first try.@@ -47,7 +68,13 @@ export class ScrubClient {if (error instanceof PermanentScrubReject) {return null}- throw error+ if (error instanceof ScrubUnavailable) {+ throw error+ }+ // A transport error: the socket was refused, reset, or destroyed by the request timeout.+ // Restarting the consumer cannot fix any of them, since the sidecar is a separate+ // container that keeps running, so this is one lost image rather than a lost pod.+ throw new ScrubUnavailable(String(error instanceof Error ? error.message : error))}}