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(replay): wait for a busy scrub sidecar, and park what it cannot process (#73732)

Robbie79fe1e7e26cb
diff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.ts
index 7768a292306e..9ac7c4e835a0 100644
--- a/nodejs/src/capabilities.ts
+++ b/nodejs/src/capabilities.ts
@@ -209,6 +209,7 @@ export function getPluginServerCapabilities(
case PluginServerMode.recordings_blob_ingestion_v2_ml_mirror:
case PluginServerMode.recordings_blob_ingestion_v2_ml_parquet_sink:
case PluginServerMode.recordings_blob_ingestion_v2_ml_image_scrub:
+ case PluginServerMode.recordings_blob_ingestion_v2_ml_image_scrub_dlq_replay:
case PluginServerMode.recording_api:
throw new Error(`Mode ${mode} is handled by IngestionSessionReplayServer, not PluginServer`)
}
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.ts
index 7bccfc24eba0..bedba16b9b98 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -25,6 +25,7 @@ export enum PluginServerMode {
recordings_blob_ingestion_v2_ml_mirror = 'recordings-blob-ingestion-v2-ml-mirror',
recordings_blob_ingestion_v2_ml_parquet_sink = 'recordings-blob-ingestion-v2-ml-parquet-sink',
recordings_blob_ingestion_v2_ml_image_scrub = 'recordings-blob-ingestion-v2-ml-image-scrub',
+ recordings_blob_ingestion_v2_ml_image_scrub_dlq_replay = 'recordings-blob-ingestion-v2-ml-image-scrub-dlq-replay',
cdp_processed_events = 'cdp-processed-events',
cdp_person_updates = 'cdp-person-updates',
cdp_data_warehouse_events = 'cdp-data-warehouse-events',
diff --git a/nodejs/src/common/config/kafka-topics.ts b/nodejs/src/common/config/kafka-topics.ts
index c0dd1ddcb23c..c928dae67e21 100644
--- a/nodejs/src/common/config/kafka-topics.ts
+++ b/nodejs/src/common/config/kafka-topics.ts
@@ -42,6 +42,11 @@ export const KAFKA_SESSION_REPLAY_ML_BLOCK_METADATA = `${prefix}session_replay_m
// raw inlined replay images: ml-mirror producer -> image-scrub worker
export const KAFKA_SESSION_REPLAY_IMAGE_SCRUB = `${prefix}session_replay_image_scrub${suffix}`
+// images the scrub sidecar cannot process, parked so they stop holding the head of their partition.
+// The original bytes are kept: unscrubbed content must never reach the ML bucket, but it must not be
+// thrown away either, so it waits here for the sidecar bug behind it to be fixed and replayed.
+export const KAFKA_SESSION_REPLAY_IMAGE_SCRUB_DLQ = `${prefix}session_replay_image_scrub_dlq${suffix}`
+
// write performance events to ClickHouse
export const KAFKA_PERFORMANCE_EVENTS = `${prefix}clickhouse_performance_events${suffix}`
// write heatmap events to ClickHouse
diff --git a/nodejs/src/common/kafka/consumer/consumer-v1.ts b/nodejs/src/common/kafka/consumer/consumer-v1.ts
index 3b3007982671..7a1ed95660e9 100644
--- a/nodejs/src/common/kafka/consumer/consumer-v1.ts
+++ b/nodejs/src/common/kafka/consumer/consumer-v1.ts
@@ -111,6 +111,14 @@ export type KafkaConsumerConfig = {
autoCommit?: boolean
enablePartitionEof?: boolean
waitForBackgroundTasksOnRebalance?: boolean
+ /**
+ * Messages pulled per poll, overriding CONSUMER_BATCH_SIZE for this consumer only.
+ *
+ * For lanes whose per-message work is slow or unbounded, batch size is what keeps a batch inside
+ * max.poll.interval.ms, so it belongs next to the code that depends on it rather than in a
+ * deployment value that can drift away from the assumption without anything noticing.
+ */
+ fetchBatchSize?: number
}
export type RdKafkaConsumerConfig = Omit<
@@ -166,7 +174,7 @@ export class KafkaConsumer {
this.config.callEachBatchWhenEmpty ??= false
this.config.waitForBackgroundTasksOnRebalance = defaultConfig.CONSUMER_WAIT_FOR_BACKGROUND_TASKS_ON_REBALANCE
this.maxBackgroundTasks = defaultConfig.CONSUMER_MAX_BACKGROUND_TASKS
- this.fetchBatchSize = defaultConfig.CONSUMER_BATCH_SIZE
+ this.fetchBatchSize = config.fetchBatchSize ?? defaultConfig.CONSUMER_BATCH_SIZE
this.maxHealthHeartbeatIntervalMs =
defaultConfig.CONSUMER_MAX_HEARTBEAT_INTERVAL_MS || MAX_HEALTH_HEARTBEAT_INTERVAL_MS
this.consumerLoopStallThresholdMs = defaultConfig.CONSUMER_LOOP_STALL_THRESHOLD_MS
diff --git a/nodejs/src/index.ts b/nodejs/src/index.ts
index 8f77672a1960..d43e010d9329 100644
--- a/nodejs/src/index.ts
+++ b/nodejs/src/index.ts
@@ -12,6 +12,7 @@ import { IngestionApiServer } from '~/servers/ingestion-api-server'
import { IngestionGeneralServer } from '~/servers/ingestion-general-server'
import { IngestionLogsServer } from '~/servers/ingestion-logs-server'
import { IngestionMetricsServer } from '~/servers/ingestion-metrics-server'
+import { IngestionSessionReplayMlImageScrubDlqReplayServer } from '~/servers/ingestion-session-replay-ml-image-scrub-dlq-replay-server'
import { IngestionSessionReplayMlImageScrubServer } from '~/servers/ingestion-session-replay-ml-image-scrub-server'
import { IngestionSessionReplayMlMirrorServer } from '~/servers/ingestion-session-replay-ml-mirror-server'
import { IngestionSessionReplayMlParquetSinkServer } from '~/servers/ingestion-session-replay-ml-parquet-sink-server'
@@ -44,6 +45,9 @@ function createServer(): NodeServer {
case PluginServerMode.recordings_blob_ingestion_v2_ml_image_scrub:
return new IngestionSessionReplayMlImageScrubServer()
+ case PluginServerMode.recordings_blob_ingestion_v2_ml_image_scrub_dlq_replay:
+ return new IngestionSessionReplayMlImageScrubDlqReplayServer()
+
case PluginServerMode.recording_api:
return new RecordingApiServer()
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 c6836c0509e4..0fe52da2c649 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,11 +10,70 @@ 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 **drops** the image on 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 **waits and retries** 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` (by `reason`: `busy`, `timeout`, `transport`, `aborted`, `deadline`, `unattempted`) and never reaches the bucket, so the failure costs coverage rather than leaking content.
-That counter is the lane's only health signal, so `IngestionSessionReplayImageScrubDropRate` alerts on its ratio to `..._scrubbed_total`: a pod dropping every image still passes its probes, keeps its lag flat, and keeps advancing offsets.
-Note `unattempted`: when a batch exhausts `SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_BATCH_SCRUB_MS` the rest of that poll batch is dropped without being offered to the sidecar at all, because Kafka offsets are a high-water mark and a later batch would commit past them regardless.
+**A busy sidecar is waited on, never given up on, and no image is ever dropped for lack of capacity.**
+Kafka is already holding the image durably, so a bounded retry buys nothing except the chance to discard data the log was keeping safe, while consuming more slowly costs only lag, which is what the topic is for.
+There is no batch time limit and no drop path: every message a poll batch takes is finished before any offset moves past it.
+
+The waiting _is_ the backpressure. A batch that spends longer on a jammed sidecar calls `consume()` that much later, so the consumer paces itself to whatever the sidecar can execute without needing to pause partitions explicitly.
+Lag grows while that happens, which is correct and is what the drain-time panels on the dashboard are for.
+
+Because the batch has no time limit, its duration is set by how many images it holds, so this lane runs a small `CONSUMER_BATCH_SIZE` (50, against a default of 500).
+A batch that outlives `max.poll.interval.ms` (300s) gets the pod evicted mid-batch, and that is not a clean retry: the evicted pod loses the offsets for work it already did, and the partition lands on a pod whose sidecar is equally busy and redoes the same images, so offered load rises while throughput falls.
+Keeping batches far inside the interval is what stops ordinary saturation reaching that point.
+If a revoke does land mid-batch, the batch stops as soon as a flush finds it no longer owns the partitions, rather than scrubbing on and writing a second shard for a span the new owner is already writing.
+
+A wedged sidecar still blocks its partitions rather than draining them, and no batch size prevents that.
+
+## Images the sidecar cannot process
+
+An image that fails the same way forever would otherwise hold the head of its partition against every team whose records share it, and the bytes are user-controlled, so that is a stall anyone can cause.
+Such an image is parked on `session_replay_image_scrub_dlq` and the partition moves on.
+
+The bytes published there are the **originals, never scrubbed**, so that topic holds unredacted content and nothing may treat it as scrubbed.
+Keeping them is the point: discarding would destroy the only reproduction of the sidecar bug that rejected them, and 30 days of retention is the window to fix the sidecar and replay.
+It is the same content the source topic already carries, on the same cluster, and it expires the same way: neither topic sets `cleanup.policy`, so both take Kafka's `delete` default and segments age out on their own.
+The one difference is that a parked image outlives its source copy, 30 days against 7, which is deliberately the width of that window.
+Why it was parked travels in headers, so the topic can be triaged without reading image content.
+
+**What makes an image poison rather than unlucky is the only question that matters here.**
+Under saturation every image waits a long time, so anything keyed on waiting or failure count alone would park the entire stream during a backlog, which is the mass loss the wait exists to prevent arriving through a different door.
+An image is blamed only when it keeps failing **while other images succeed**: a sidecar that is full or wedged fails everything equally, so no image ever meets that condition and the lane keeps waiting, which is correct.
+Only a considered answer counts towards blame, which is the `rejected` reason: the sidecar took the image, looked at it, and could not produce bytes.
+A 503 is it declining to look at all, and a refused or reset socket is true of every image at once.
+
+**The two deadlines are ordered on purpose, and inverting them reopens a hole.** The sidecar gives up on a job it cannot finish first (`IMAGE_SCRUB_JOB_TIMEOUT_MS`), retires the worker, and answers 500, which is a considered answer about that image and is what lets it be blamed and parked.
+The consumer waits longer than that (`SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_TIMEOUT_MS`, past the job deadline plus admission queue wait) so the answer actually arrives.
+Give up first and an unprocessable image looks merely slow on every attempt, never earns blame, and holds the head of a partition shared by every team whose records hash to it.
+A timeout then means what it should: the sidecar said nothing at all, which is true of every image at once and so is not blamable.
+
+The number of other successes required is deliberately small, and must stay below the pod's scrub concurrency.
+A batch cannot finish while one of its images is in flight, and a pod cannot poll for more work until its batch finishes, so the only successes that can ever arrive are from the few slots running alongside that image.
+Requiring more than that makes the gate unreachable for an image late in a batch: the batch never returns, and the pod stops consuming entirely while still reporting Ready.
+`ImageBatcher` refuses to start if the relationship is broken, so a future concurrency change fails at boot rather than in traffic.
+
+When no peer is available to vouch at all, a long enough run of considered rejections opens the gate on its own.
+That threshold has to fire comfortably inside `max.poll.interval.ms` (300s), which is the binding constraint rather than a preference: a batch cannot return while one of its images is in flight, so anything above the lease can never be reached — the group fences the pod first, the partition moves, and its new owner repeats the same work and is fenced in turn, circling the fleet forever.
+
+It is published through this lane's own producer slot on the replay cluster, which is where the source topic lives and which carries a `message.max.bytes` sized for these payloads; the generic slot points elsewhere with librdkafka's 1 MB default, where parking a normal image would fail on every attempt.
+The topic must exist before this ships, with `max.message.bytes` at least the source topic's: clearing `SESSION_RECORDING_ML_IMAGE_SCRUB_DLQ_TOPIC` is the rollback, and reverts to waiting.
+
+Parking happens before the ref is marked and before the slot retires, so a failed publish leaves the image exactly where it was, still unscrubbed and still uncommitted.
+A publish that keeps failing is retried rather than raised, because the Kafka loop exits the process on any batch error and a dead-letter topic that is missing, on the wrong cluster, or too small would otherwise crash-loop every pod in the lane on the same image.
+`ml_mirror_image_scrub_consumer_dead_letter_failed_total` is that condition, and it means the topic needs looking at rather than the image.
+With no dead-letter destination configured the client keeps waiting instead, because the only other option would be discarding.
+`ml_mirror_image_scrub_consumer_dead_lettered_total` should sit at zero; anything above a trickle is a sidecar bug reproducing across many images, and the fix belongs in the sidecar.
+
+Waiting only applies to answers a later attempt could change: 5xx, 408, 429, and transport failures (a refused socket is the ordinary case while the sidecar is still starting in the same pod).
+Any other status, and a 200 carrying no bytes, is the sidecar answering a question we did not think we were asking, so it fails the batch loudly instead.
+Waiting on a 404 from a misdirected `SIDECAR_URL` would otherwise turn a deploy mistake into a pod that consumes nothing, passes every probe, and surfaces only as lag.
+
+`ml_mirror_image_scrub_consumer_scrub_waits_total` (by `reason`: `busy`, `timeout`, `transport`) counts attempts that came back without bytes and will be retried, so it is a saturation signal and never a loss signal.
+`ml_mirror_image_scrub_consumer_stuck_images_total` re-increments while any one image is still being retried past the point a healthy sidecar would have finished it, so it reads as a level rather than a one-off edge.
+
+**A stalled pod on this lane looks healthy to Kubernetes.** The lane runs the legacy heartbeat health check (`CONSUMER_LOOP_BASED_HEALTH_CHECK` is unset), and the consumer refreshes that heartbeat every 10s for the whole batch, so a pod blocked on one image stays Ready and Live indefinitely.
+That is deliberate — restarting it would only replay the same image — but it means lag and the two counters above are the only evidence, and it is why the lane's alerts are lag-shaped.
**Nothing about a busy or unreachable sidecar may take the consumer down.**
The consumer's Kafka loop exits the process on any batch error, so a failure that reaches it costs the whole pod and hands its partitions to pods that are equally busy, spreading the saturation.
diff --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.ts
index 87a20a5fb9b3..0782f616074c 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
@@ -21,11 +21,12 @@ export interface Config {
// 413 above the ~10 MiB Kafka message ceiling — bigger is anomalous. The service owns its own memory bound.
maxBodyBytes: number
// How long one image may hold a worker, measured from dispatch, before that worker is treated as
- // wedged and replaced. Sized against the caller that actually gives up first: ScrubClient's
- // per-request timeout is SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_TIMEOUT_MS (10s), not the 120s
- // whole-batch budget. Past that point the consumer has already destroyed the socket and is
- // retrying, so the work is unwanted, and every extra second it runs holds one of maxConcurrency
- // against requests that are still wanted. The slack over 10s is for the reply crossing back.
+ // wedged and replaced. This must stay BELOW the consumer's per-request timeout
+ // (SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_TIMEOUT_MS): giving up here first is what turns an
+ // image this sidecar cannot finish into a 500, which is a considered answer about that image and
+ // is what lets the consumer blame it and park it. If the consumer gave up first the image would
+ // look merely slow forever and hold the head of its partition. Measured from dispatch rather
+ // than enqueue so queue wait is not charged to whichever worker happens to hold the job.
jobTimeoutMs: number
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dead-letter-sink.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dead-letter-sink.ts
new file mode 100644
index 000000000000..7988b9662711
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dead-letter-sink.ts
@@ -0,0 +1,30 @@
+import { KafkaProducerWrapper } from '~/common/kafka/producer'
+
+import { DeadLetterSink } from './image-batcher'
+
+/**
+ * Parks an image the sidecar cannot process onto a Kafka topic, keyed by ref like the source.
+ *
+ * The value is the original bytes, unchanged. That is the point: the image was never scrubbed, so it
+ * still carries whatever it always did and must not reach the ML bucket, but discarding it would
+ * destroy the only reproduction of the sidecar bug that rejected it. The topic keeps both properties
+ * at once, and the retention on it is the window in which someone can fix the sidecar and replay.
+ *
+ * Everything about why it was parked goes in headers rather than the value, so a consumer can triage
+ * the topic without reading a byte of image content.
+ */
+export class KafkaDeadLetterSink implements DeadLetterSink {
+ constructor(
+ private readonly producer: KafkaProducerWrapper,
+ private readonly topic: string
+ ) {}
+
+ public async park(image: { ref: string; bytes: Buffer; detail: Record<string, unknown> }): Promise<void> {
+ await this.producer.produce({
+ topic: this.topic,
+ key: Buffer.from(image.ref),
+ value: image.bytes,
+ headers: Object.fromEntries(Object.entries(image.detail).map(([k, v]) => [k, String(v)])),
+ })
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.test.ts
new file mode 100644
index 000000000000..fa56453db54f
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.test.ts
@@ -0,0 +1,77 @@
+import { Message } from 'node-rdkafka'
+
+import { KafkaProducerWrapper } from '~/common/kafka/producer'
+
+import { MAX_REPLAYS, replayBatch } from './dlq-replay'
+import { REPLAY_COUNT_HEADER } from './image-batcher'
+
+function parked(ref: string, bytes: string, replayCount?: number): Message {
+ return {
+ topic: 'session_replay_image_scrub_dlq',
+ partition: 0,
+ offset: 0,
+ key: Buffer.from(ref),
+ value: Buffer.from(bytes),
+ headers: [
+ { reason: Buffer.from('rejected') },
+ ...(replayCount === undefined ? [] : [{ [REPLAY_COUNT_HEADER]: Buffer.from(String(replayCount)) }]),
+ ],
+ } as unknown as Message
+}
+
+describe('replayBatch', () => {
+ let produced: { topic: string; key: string; value: string; headers?: Record<string, string> }[]
+ let producer: KafkaProducerWrapper
+
+ beforeEach(() => {
+ produced = []
+ producer = {
+ produce: (m: { topic: string; key: Buffer; value: Buffer; headers?: Record<string, string> }) => {
+ produced.push({
+ topic: m.topic,
+ key: m.key.toString(),
+ value: m.value.toString(),
+ headers: m.headers,
+ })
+ return Promise.resolve()
+ },
+ } as unknown as KafkaProducerWrapper
+ })
+
+ it('returns the original bytes to the source topic under the same ref', async () => {
+ const outcome = await replayBatch([parked('ref-1', 'original-image')], producer, 'session_replay_image_scrub')
+
+ expect(outcome).toEqual({ replayed: 1, exhausted: 0 })
+ expect(produced).toEqual([
+ {
+ topic: 'session_replay_image_scrub',
+ key: 'ref-1',
+ value: 'original-image',
+ // The park's diagnostic headers describe an old failure and must not travel with a
+ // fresh attempt; only the count that bounds the round trips survives.
+ headers: { [REPLAY_COUNT_HEADER]: '1' },
+ },
+ ])
+ })
+
+ it('stops replaying an image that has already been round-tripped its limit', async () => {
+ // A replay run is only worth making after the sidecar is fixed, and nothing enforces that.
+ // Capping the trips means running it too early costs one wasted pass rather than an image
+ // cycling between the two topics forever, spending scrub capacity on known-bad work.
+ const outcome = await replayBatch(
+ [parked('ref-1', 'poison', MAX_REPLAYS)],
+ producer,
+ 'session_replay_image_scrub'
+ )
+
+ expect(outcome).toEqual({ replayed: 0, exhausted: 1 })
+ // Left on the dead-letter topic, which holds the only copy of these bytes.
+ expect(produced).toEqual([])
+ })
+
+ it('carries the count forward so trips accumulate across runs', async () => {
+ await replayBatch([parked('ref-1', 'image', 1)], producer, 'session_replay_image_scrub')
+
+ expect(produced[0].headers).toEqual({ [REPLAY_COUNT_HEADER]: '2' })
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.ts
new file mode 100644
index 000000000000..fc9570ff5ddb
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.ts
@@ -0,0 +1,68 @@
+import { Message } from 'node-rdkafka'
+
+import { parseKafkaHeaders } from '~/common/kafka/consumer/consumer-v1'
+import { KafkaProducerWrapper } from '~/common/kafka/producer'
+import { logger } from '~/common/utils/logger'
+
+import { REPLAY_COUNT_HEADER } from './image-batcher'
+import { ImageScrubConsumerMetrics } from './metrics'
+
+/**
+ * Replays past which an image stays parked.
+ *
+ * A replay run is only worth making after the sidecar has been fixed, but nothing enforces that, and
+ * an image pushed back at a sidecar that still cannot handle it simply returns to the dead-letter
+ * topic. Capping the round trips means running the replay too early costs one wasted pass instead of
+ * a loop, so the safe outcome does not depend on an operator getting the order right.
+ */
+export const MAX_REPLAYS = 2
+
+export interface ReplayOutcome {
+ replayed: number
+ exhausted: number
+}
+
+/**
+ * Pushes parked images back onto the topic they came from.
+ *
+ * The value is passed through untouched, because it is the original image and the point of the
+ * exercise is to put it through a fixed sidecar exactly as it arrived the first time. The key is the
+ * ref, so it lands on the partition the rest of that image's copies hash to.
+ *
+ * Diagnostic headers from the park are deliberately dropped: they describe the failure that put the
+ * image here, and carrying them onto a topic where every other message has none would leave the
+ * scrub consumer reading stale reasons on a fresh attempt. Only the replay count survives, because
+ * it is what stops an image circling between the two topics.
+ */
+export async function replayBatch(
+ messages: Message[],
+ producer: KafkaProducerWrapper,
+ sourceTopic: string
+): Promise<ReplayOutcome> {
+ const outcome: ReplayOutcome = { replayed: 0, exhausted: 0 }
+ for (const message of messages) {
+ const ref = message.key?.toString('utf8')
+ if (!ref || !message.value) {
+ continue
+ }
+ const headers = parseKafkaHeaders(message.headers)
+ const replayCount = Number(headers[REPLAY_COUNT_HEADER] ?? 0) || 0
+ if (replayCount >= MAX_REPLAYS) {
+ // Left where it is rather than dropped: the bytes stay on the dead-letter topic for
+ // whatever retention it has, which is the only copy of them that exists.
+ outcome.exhausted += 1
+ ImageScrubConsumerMetrics.incReplayExhausted()
+ logger.warn('☠️', 'image_scrub_replay_exhausted', { ref, replayCount, reason: headers.reason })
+ continue
+ }
+ await producer.produce({
+ topic: sourceTopic,
+ key: Buffer.from(ref),
+ value: message.value,
+ headers: { [REPLAY_COUNT_HEADER]: String(replayCount + 1) },
+ })
+ outcome.replayed += 1
+ ImageScrubConsumerMetrics.incReplayed()
+ }
+ return outcome
+}
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 cd9a59d22097..f85e6567fccf 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,10 +1,9 @@
import { Message, TopicPartitionOffset } from 'node-rdkafka'
-import { register } from 'prom-client'
import { hashImageBytes, imageRef } from './content-ref'
import { ImageBatcher, OffsetStore } from './image-batcher'
import { ImageShardStore, ScrubbedImage } from './image-shard-store'
-import { ScrubClient, ScrubUnavailable } from './scrub-client'
+import { ScrubClient, ScrubPoisoned } from './scrub-client'
const pt = (n: number): string => String(n).padStart(32, '0')
const CONTENT_KEY = 'fedcba9876543210fedcba9876543210'
@@ -46,23 +45,11 @@ const scrubClient = {
scrub: (b: Buffer) => Promise.resolve(Buffer.concat([Buffer.from('x'), b])),
} as unknown as ScrubClient
-async function droppedByReason(): Promise<Record<string, number>> {
- const metric = await register.getSingleMetric('ml_mirror_image_scrub_consumer_dropped_total')!.get()
- const counts: Record<string, number> = { capacity: 0, unattempted: 0 }
- for (const v of metric.values) {
- counts[String(v.labels.reason)] = v.value
- }
- // The client's reasons all mean the same thing to this assertion: the sidecar was offered the
- // image and could not take it, as against never being offered it at all.
- counts.capacity = ['busy', 'timeout', 'transport', 'aborted', 'deadline'].reduce((n, r) => n + (counts[r] ?? 0), 0)
- return counts
-}
const options = {
flushIntervalMs: 0,
maxImages: 1000,
maxBytes: 1e9,
scrubConcurrency: 4,
- maxBatchScrubMs: 30_000,
dedupMaxRefs: 1000,
}
@@ -174,7 +161,7 @@ describe('ImageBatcher', () => {
slowStore as unknown as ImageShardStore,
offsets,
{ scrub: () => Promise.resolve(Buffer.alloc(16)) } as unknown as ScrubClient,
- { ...options, maxBytes: 32, scrubConcurrency: 2, maxBatchScrubMs: 60 },
+ { ...options, maxBytes: 32, scrubConcurrency: 2 },
0
)
@@ -495,94 +482,144 @@ describe('ImageBatcher', () => {
).toThrow('scrubConcurrency')
})
- 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.
+ it('parks a poison image and lets the batch move past it', async () => {
const store = new FakeStore()
const offsets = new FakeOffsets()
- const hangingClient = { scrub: () => new Promise<Buffer>(() => {}) } as unknown as ScrubClient
- const batcher = new ImageBatcher(
- store as unknown as ImageShardStore,
- offsets,
- hangingClient,
- { ...options, maxBatchScrubMs: 5 },
- 0
- )
+ const parked: string[] = []
+ const poisonClient = {
+ scrub: (b: Buffer) =>
+ b.toString() === 'poison'
+ ? Promise.reject(
+ new ScrubPoisoned('cannot process', {
+ reason: 'transport',
+ lastError: 'sidecar responded 500',
+ attempts: 12,
+ waitedMs: 60_000,
+ })
+ )
+ : Promise.resolve(b),
+ } as unknown as ScrubClient
+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, poisonClient, options, 0, {
+ park: (image) => Promise.resolve(void parked.push(image.ref)),
+ })
- await expect(batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))], 1)).resolves.toBeUndefined()
- expect(store.writes).toHaveLength(0)
+ await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('poison')), msg(0, 1, pt(1), Buffer.from('ok'))], 1)
+
+ expect(parked).toHaveLength(1)
+ // The healthy image behind it still gets written, and the offset advances over both.
+ expect(store.writes.flat()).toHaveLength(1)
+ expect(offsets.received.flat().map((o) => o.offset)).toEqual([2])
})
- it('counts the images a deadline never reached apart from the ones it actually attempted', async () => {
- // A stall past the deadline discards the whole remaining batch, not just the images in
- // flight, because the batch's abort controller cannot be un-aborted and everything submitted
- // after it rejects without the sidecar ever seeing it. That loss is accepted, but its size
- // has to be legible: rolled into one counter, two timed-out images and four hundred that were
- // never tried look identical, and the deadline is exactly the knob you would be trying to
- // size from that number.
- const hangingClient = { scrub: () => new Promise<Buffer>(() => {}) } as unknown as ScrubClient
+ it('preserves the replay count when re-parking, so round trips accumulate', async () => {
+ // The cap that stops an image cycling between the two topics only binds if the count comes
+ // back out with it. Dropped here, every replay run starts the image at zero and it can be
+ // pushed at a sidecar that still cannot take it forever.
+ const parked: Record<string, unknown>[] = []
+ const poisonClient = {
+ scrub: () =>
+ Promise.reject(
+ new ScrubPoisoned('cannot process', {
+ reason: 'rejected',
+ lastError: 'sidecar responded 500',
+ attempts: 12,
+ waitedMs: 60_000,
+ })
+ ),
+ } as unknown as ScrubClient
const batcher = new ImageBatcher(
new FakeStore() as unknown as ImageShardStore,
new FakeOffsets(),
- hangingClient,
- { ...options, scrubConcurrency: 2, maxBatchScrubMs: 5 },
- 0
+ poisonClient,
+ options,
+ 0,
+ { park: (image) => Promise.resolve(void parked.push(image.detail)) }
)
- const before = await droppedByReason()
- const messages = Array.from({ length: 20 }, (_, i) => msg(0, i, pt(1), Buffer.from(`img-${i}`)))
- await expect(batcher.handleBatch(messages, 1)).resolves.toBeUndefined()
- const after = await droppedByReason()
+ const replayed = msg(0, 0, pt(1), Buffer.from('poison'))
+ ;(replayed as unknown as { headers: unknown[] }).headers = [{ replayCount: Buffer.from('1') }]
+ await batcher.handleBatch([replayed], 1)
- expect(after.capacity - before.capacity).toBe(2)
- expect(after.unattempted - before.unattempted).toBe(18)
+ expect(parked[0].replayCount).toBe(1)
})
- 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.
+ it('refuses to start when concurrency is too low for dead-lettering to be reachable', () => {
+ // The poison gate can only ever count successes from slots running alongside the image it is
+ // judging: the batch holding that image cannot finish, and the pod cannot poll for more work
+ // until it does. At or below the threshold the gate is unreachable, so the first image the
+ // sidecar cannot scrub stops the pod consuming for good. Failing at boot beats deadlocking
+ // in traffic, where it presents as a pod that is Ready and quietly doing nothing.
+ expect(
+ () =>
+ new ImageBatcher(
+ new FakeStore() as unknown as ImageShardStore,
+ new FakeOffsets(),
+ scrubClient,
+ { ...options, scrubConcurrency: 2 },
+ 0,
+ { park: () => Promise.resolve() }
+ )
+ ).toThrow('scrubConcurrency must exceed')
+ })
+
+ it('retries a failed park rather than failing the batch over it', async () => {
+ // Ordering is the whole safety property here. Marking the ref or retiring the slot before the
+ // bytes are durably parked would advance the offset over an image held nowhere at all.
+ //
+ // Letting the failure escape is worse still than the stall it would replace: the Kafka loop
+ // exits the process on any batch error, so a dead-letter topic that is missing, on the wrong
+ // cluster, or smaller than a source image would crash-loop every pod in the lane on the same
+ // message. Retrying leaves the image where it was, which is what this lane did before a
+ // dead-letter topic existed.
const store = new FakeStore()
const offsets = new FakeOffsets()
- const busyClient = {
- scrub: () => Promise.reject(new ScrubUnavailable('scrub request timed out', 'timeout')),
+ const poisonClient = {
+ scrub: () =>
+ Promise.reject(
+ new ScrubPoisoned('cannot process', {
+ reason: 'transport',
+ lastError: 'sidecar responded 500',
+ attempts: 12,
+ waitedMs: 60_000,
+ })
+ ),
} as unknown as ScrubClient
- const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, busyClient, options, 0)
+ let parkAttempts = 0
+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, poisonClient, options, 0, {
+ park: () => {
+ parkAttempts += 1
+ return parkAttempts < 3 ? Promise.reject(new Error('dlq produce failed')) : Promise.resolve()
+ },
+ })
- 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])
+ await expect(batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('poison'))], 1)).resolves.toBeUndefined()
+
+ expect(parkAttempts).toBe(3)
+ // The offset only moves once the bytes are somewhere, never while parking is still failing.
+ expect(offsets.received.flat().map((o) => o.offset)).toEqual([1])
})
- 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', 'busy'))
- : Promise.resolve(b)
- },
- } as unknown as ScrubClient
+ it('returns when stopped, so shutdown does not wait on an unresponsive sidecar', async () => {
+ // disconnect() awaits the running batch, and the scrub client now waits on a busy sidecar
+ // rather than giving up, so a batch against a sidecar that is down never returns on its own.
+ // Without the interrupt a graceful stop runs to the termination grace period and is SIGKILLed.
const store = new FakeStore()
- const batcher = new ImageBatcher(
- store as unknown as ImageShardStore,
- new FakeOffsets(),
- busyOnceClient,
- options,
- 0
- )
- const sprite = Buffer.from('sprite')
+ const offsets = new FakeOffsets()
+ const hangingClient = {
+ scrub: (_b: Buffer, signal: AbortSignal) =>
+ new Promise<Buffer>((_resolve, reject) =>
+ signal.addEventListener('abort', () => reject(new Error('scrub batch aborted')), { once: true })
+ ),
+ } as unknown as ScrubClient
+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, hangingClient, options, 0)
- await batcher.handleBatch([msg(0, 0, pt(1), sprite)], 1)
- await batcher.handleBatch([msg(0, 0, pt(1), sprite)], 2)
+ const running = batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))], 1)
+ batcher.stop()
- expect(store.writes.flat()).toHaveLength(1)
+ await expect(running).resolves.toBeUndefined()
+ // Nothing finished, so nothing may be committed over: the image replays under the next owner.
+ expect(offsets.received.flat()).toEqual([])
+ expect(store.writes).toHaveLength(0)
})
it('discards offsets for a partition a rebalance already revoked, rather than exiting', async () => {
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 e88fb2e6b63f..ba2bd7cca697 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,6 +1,6 @@
import { LibrdKafkaError, Message, TopicPartitionOffset } from 'node-rdkafka'
-import { findOffsetsToCommit } from '~/common/kafka/consumer/consumer-v1'
+import { findOffsetsToCommit, parseKafkaHeaders } from '~/common/kafka/consumer/consumer-v1'
import { ConcurrencyController } from '~/common/utils/concurrencyController'
import { logger } from '~/common/utils/logger'
import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'
@@ -8,12 +8,23 @@ import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-de
import { parseImageRef } from './content-ref'
import { ImageShardStore, ScrubbedImage } from './image-shard-store'
import { ImageScrubConsumerMetrics } from './metrics'
-import { ScrubClient, ScrubUnavailable } from './scrub-client'
+import { POISON_MIN_OTHER_SUCCESSES, ScrubAborted, ScrubClient, ScrubPoisoned } from './scrub-client'
export interface OffsetStore {
offsetsStore(offsets: TopicPartitionOffset[]): void
}
+/**
+ * Where an image the sidecar cannot process goes.
+ *
+ * Deliberately the original bytes rather than anything derived: the image was never scrubbed, so it
+ * carries whatever PII it always did and must not reach the ML bucket, but discarding it would make
+ * the sidecar bug behind it unreproducible. Parking it keeps both properties.
+ */
+export interface DeadLetterSink {
+ park(image: { ref: string; bytes: Buffer; detail: Record<string, unknown> }): Promise<void>
+}
+
/**
* The librdkafka codes that mean "this partition is not ours to store an offset for".
*
@@ -23,6 +34,15 @@ export interface OffsetStore {
* us. All four have to be here: which one a given revoke produces is a matter of timing, so matching
* a subset leaves the rest of the window exiting the process.
*/
+/**
+ * Names how many replays an image has already survived.
+ *
+ * Read on the way in and written back on the way out, so re-parking preserves it. If the count reset
+ * on each pass, a replay run against a sidecar that still cannot handle the image would ping-pong it
+ * between the two topics forever, spending scrub capacity on work already known to fail.
+ */
+export const REPLAY_COUNT_HEADER = 'replayCount'
+
const REVOKED_PARTITION_CODES = new Set([
-172, // ERR__STATE
-190, // ERR__UNKNOWN_PARTITION
@@ -37,6 +57,18 @@ interface PlannedScrub {
pseudoTeam: string
hash: string
value: Buffer
+ /** Where this image came from, carried only so a parked one can be traced back to its source. */
+ sourceTopic: string
+ sourcePartition: number
+ sourceOffset: number
+ /**
+ * How many times this image has already been replayed out of the dead-letter topic.
+ *
+ * Carried through so re-parking preserves it. Without that the count resets on every pass and a
+ * replay run against a sidecar that still cannot handle the image ping-pongs it forever, which
+ * is worse than leaving it parked: it spends scrub capacity on work already known to fail.
+ */
+ replayCount: number
}
interface ScrubbedRef {
@@ -57,7 +89,6 @@ export interface ImageBatcherOptions {
maxImages: number
maxBytes: number
scrubConcurrency: number
- maxBatchScrubMs: number
dedupMaxRefs: number
}
@@ -79,13 +110,35 @@ export class ImageBatcher {
* one.
*/
private readonly seenRefs: RefDedupCache
+ /**
+ * The batch currently in flight, so shutdown can interrupt it.
+ *
+ * disconnect() waits on the running batch, and a batch waiting on a sidecar that is down waits
+ * forever, so without this a graceful stop runs to the termination grace period and ends in a
+ * SIGKILL. Aborting is safe: offsets are only recorded for images that finished, so whatever was
+ * still in flight replays under the partition's next owner.
+ */
+ private activeBatch: AbortController | null = null
+ private stopping = false
+ /**
+ * Set when a flush finds this pod no longer owns the partitions it is committing.
+ *
+ * Whatever is left of the batch belongs to another pod now, and scrubbing it anyway spends the
+ * same saturated sidecar twice on one image and writes a second shard for a span the new owner
+ * is already writing. That is load rising per unit of useful work exactly when capacity is what
+ * is scarce, so the batch stops instead.
+ */
+ private partitionsRevoked = false
+ /** Retired count of the running batch, read by the progress metric once it ends. */
+ private retiredInBatch = 0
constructor(
private readonly store: ImageShardStore,
private readonly offsetStore: OffsetStore,
private readonly scrubClient: ScrubClient,
private readonly options: ImageBatcherOptions,
- nowMs: number
+ nowMs: number,
+ private readonly deadLetters: DeadLetterSink | null = null
) {
// 0 would admit nothing and spin the loop forever; NaN would skip it entirely, committing
// offsets for unprocessed messages. Fail at boot rather than either.
@@ -93,12 +146,30 @@ export class ImageBatcher {
if (!Number.isInteger(this.maxInFlight) || this.maxInFlight < 1) {
throw new Error(`scrubConcurrency must be a positive number, got ${options.scrubConcurrency}`)
}
+ // The poison gate can only ever see successes from slots running alongside the image it is
+ // judging, because the batch holding it cannot finish and the pod cannot poll for more work
+ // until it does. Concurrency at or below the threshold therefore makes the gate unreachable
+ // and the pod deadlocks on the first unscrubbable image, so refuse to start instead.
+ if (deadLetters && this.maxInFlight <= POISON_MIN_OTHER_SUCCESSES) {
+ throw new Error(
+ `scrubConcurrency must exceed ${POISON_MIN_OTHER_SUCCESSES} for dead-lettering to be reachable, got ${this.maxInFlight}`
+ )
+ }
this.lastFlushMs = nowMs
this.scrubConcurrency = new ConcurrencyController(this.maxInFlight)
this.seenRefs = new RefDedupCache('image_scrub_consumer', options.dedupMaxRefs)
}
+ /** Interrupts the running batch so a graceful shutdown does not wait on an unresponsive sidecar. */
+ public stop(): void {
+ this.stopping = true
+ this.activeBatch?.abort()
+ }
+
public async handleBatch(messages: Message[], nowMs: number): Promise<void> {
+ if (this.stopping) {
+ return
+ }
// 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) {
@@ -115,19 +186,42 @@ export class ImageBatcher {
// can come back as a multi-MB full-resolution PNG), so submitting a whole poll batch at once
// could hold gigabytes. Peak is ~maxBytes plus the outputs of one window.
//
- // The deadline covers scrub time only: the timer is armed around each wait and the elapsed
- // time charged to the budget, 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.
+ // There is no time limit on the batch. A busy sidecar is waited on rather than given up on,
+ // so the batch takes as long as the sidecar needs and the next consume() happens that much
+ // later, which is the whole backpressure mechanism. Every message this batch took is finished
+ // before any offset moves past it.
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 an aborted job with and not as a scrub error at
- // all, so no amount of inspecting the error can tell this apart from a genuine fault.
- let deadlineExpired = false
+ this.activeBatch = controller
+ this.partitionsRevoked = false
+ const startedAt = performance.now()
+ try {
+ 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.
+ if (planned.length > 0) {
+ ImageScrubConsumerMetrics.observeBatchProgress(
+ this.retiredInBatch,
+ planned.length,
+ (performance.now() - startedAt) / 1000
+ )
+ }
+ // 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.
+ this.activeBatch = null
+ }
+ }
+
+ private async scrubAndStage(
+ messages: Message[],
+ planned: PlannedScrub[],
+ controller: AbortController,
+ nowMs: number
+ ): Promise<void> {
let spanStart = 0
let nextToSubmit = 0
let retired = 0
+ this.retiredInBatch = 0
const settled = new Array<boolean>(planned.length).fill(false)
const inFlight = new Map<number, Promise<SettledScrub>>()
// Results wait here until their slot retires, so the buffer only ever holds images whose
@@ -140,7 +234,6 @@ export class ImageBatcher {
while (nextToSubmit < planned.length || inFlight.size > 0) {
while (
- !deadlineExpired &&
nextToSubmit < planned.length &&
inFlight.size < this.maxInFlight &&
!this.overCapacity(stagedCount, stagedBytes)
@@ -148,45 +241,27 @@ export class ImageBatcher {
inFlight.set(nextToSubmit, this.submitScrub(nextToSubmit, planned[nextToSubmit], controller))
nextToSubmit++
}
+ // Only reachable over capacity with work left: flush to make room rather than spin.
if (inFlight.size === 0) {
- // The controller is per-batch and cannot be un-aborted, so anything submitted from
- // here rejects without the sidecar seeing it. Draining the tail that way would count
- // hundreds of untried images as capacity drops and read as a far worse sidecar
- // failure than actually occurred.
- if (deadlineExpired) {
+ await this.flushOrThrow(nowMs)
+ if (this.partitionsRevoked) {
break
}
- // Only reachable over capacity with work left: flush to make room rather than spin.
- await this.flushOrThrow(nowMs)
continue
}
- const waitStartMs = performance.now()
- const timer = setTimeout(() => {
- deadlineExpired = true
- controller.abort()
- }, scrubBudgetMs)
- let done: SettledScrub
- try {
- done = await Promise.race(inFlight.values())
- } finally {
- clearTimeout(timer)
- scrubBudgetMs -= performance.now() - waitStartMs
- }
+ const done = await Promise.race(inFlight.values())
inFlight.delete(done.slot)
if (done.error !== undefined) {
- 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
+ // Shutdown is not a failure. Everything retired so far is flushed below and its
+ // offsets are already recorded; the rest was never finished, so its offsets stay
+ // unrecorded and it replays wherever the partition lands next.
+ if (this.stopping) {
+ break
}
- // 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(
- deadlineExpired ? 'deadline' : (done.error as ScrubUnavailable).reason
- )
+ controller.abort() // one failure dooms the batch, so cancel the siblings still in flight
+ ImageScrubConsumerMetrics.incBatchFailed('scrub')
+ throw done.error
}
if (done.scrubbed) {
staged[done.slot] = done.scrubbed
@@ -215,6 +290,7 @@ export class ImageBatcher {
stagedBytes -= ready.image.bytes.length
}
retired++
+ this.retiredInBatch = retired
}
if (retired > retiredBefore) {
const spanEnd = planned[retired - 1].index + 1
@@ -224,13 +300,25 @@ export class ImageBatcher {
if (this.overCapacity(stagedCount, stagedBytes)) {
await this.flushOrThrow(nowMs)
}
+ if (this.partitionsRevoked) {
+ controller.abort()
+ break
+ }
+ }
+ if (this.partitionsRevoked) {
+ // Neither the offsets nor the shard belong to this pod any more. Writing it would only
+ // duplicate what the partition's new owner is already producing, under a fresh key that
+ // nothing later reconciles.
+ this.buffer = []
+ this.bufferBytes = 0
+ this.pendingOffsets.clear()
+ return
}
- // Kafka offsets are a high-water mark, so leaving this tail uncommitted would not save it:
- // the next batch stores a higher offset and buries the gap. Since it is lost either way, all
- // that is left to decide is whether the loss is legible, hence its own reason rather than
- // being folded in with images the sidecar was actually offered and refused.
- if (nextToSubmit < planned.length) {
- ImageScrubConsumerMetrics.incDropped('unattempted', planned.length - nextToSubmit)
+ if (this.stopping) {
+ // Deliberately no tail recordOffsets: past the last retired image nothing was finished,
+ // and moving offsets over it here would lose exactly what the wait exists to protect.
+ await this.flushOrThrow(nowMs)
+ return
}
// A batch whose tail is all skips, or which is nothing but skips, still has to move offsets.
this.recordOffsets(messages.slice(spanStart))
@@ -261,7 +349,17 @@ export class ImageBatcher {
ImageScrubConsumerMetrics.incDeduped('pod')
continue
}
- planned.push({ index, ref, pseudoTeam: parsed.pseudoTeam, hash: parsed.hash, value: m.value })
+ planned.push({
+ index,
+ ref,
+ pseudoTeam: parsed.pseudoTeam,
+ hash: parsed.hash,
+ value: m.value,
+ sourceTopic: m.topic,
+ sourcePartition: m.partition,
+ sourceOffset: m.offset,
+ replayCount: Number(parseKafkaHeaders(m.headers)[REPLAY_COUNT_HEADER] ?? 0) || 0,
+ })
}
return planned
}
@@ -298,7 +396,22 @@ export class ImageBatcher {
}
private async scrubOne(planned: PlannedScrub, signal: AbortSignal): Promise<ScrubbedImage | null> {
- const bytes = await this.scrubClient.scrub(planned.value, signal)
+ let bytes: Buffer | null
+ try {
+ bytes = await this.scrubClient.scrub(planned.value, signal, planned.ref)
+ } catch (error) {
+ if (!(error instanceof ScrubPoisoned) || !this.deadLetters) {
+ throw error
+ }
+ // Parked before the ref is marked and before the slot retires, so a failure to park
+ // leaves the image exactly where it was: still unscrubbed, still uncommitted, still
+ // waiting. Marking first would advance the offset over an image held nowhere.
+ await this.parkUntilAccepted(planned, error, signal)
+ logger.warn('☠️', 'image_scrub_dead_lettered', { ref: planned.ref, ...error.detail })
+ this.seenRefs.add(planned.ref)
+ ImageScrubConsumerMetrics.incDeadLettered(error.detail.reason)
+ return null
+ }
if (bytes === null) {
// Null is only ever a 422/413, a verdict on the content itself, so no retry can succeed.
// Marking it stops every later copy from re-earning the same rejection, and there is
@@ -311,6 +424,55 @@ export class ImageBatcher {
return { pseudoTeam: planned.pseudoTeam, hash: planned.hash, bytes }
}
+ /**
+ * Publishes to the dead-letter topic, retrying until it is accepted or the caller hangs up.
+ *
+ * A park that cannot succeed leaves the image at the head of its partition, which is exactly the
+ * behaviour this lane had before a dead-letter topic existed, and it is the only safe fallback:
+ * the image is unscrubbed and held nowhere else, so the alternatives are discarding it or
+ * advancing an offset over it. Letting the failure escape would be worse still, because the
+ * Kafka loop exits on any batch error and the same image is redelivered on restart, turning a
+ * misconfigured or undersized dead-letter topic into a crash loop across every pod in the lane.
+ */
+ private async parkUntilAccepted(
+ planned: PlannedScrub,
+ poisoned: ScrubPoisoned,
+ signal: AbortSignal
+ ): Promise<void> {
+ for (let attempt = 0; ; attempt++) {
+ if (signal.aborted) {
+ throw new ScrubAborted('scrub batch aborted')
+ }
+ try {
+ await this.deadLetters!.park({
+ ref: planned.ref,
+ bytes: planned.value,
+ detail: {
+ ...poisoned.detail,
+ pseudoTeam: planned.pseudoTeam,
+ hash: planned.hash,
+ sourceTopic: planned.sourceTopic,
+ sourcePartition: planned.sourcePartition,
+ sourceOffset: planned.sourceOffset,
+ // Carried back out, or the count restarts on every pass and the cap that
+ // bounds replay round trips never binds.
+ [REPLAY_COUNT_HEADER]: planned.replayCount,
+ },
+ })
+ return
+ } catch (error) {
+ ImageScrubConsumerMetrics.incDeadLetterFailed()
+ logger.error('☠️', 'image_scrub_dead_letter_failed', {
+ ref: planned.ref,
+ bytes: planned.value.length,
+ attempts: attempt + 1,
+ error: String(error),
+ })
+ await new Promise((resolve) => setTimeout(resolve, Math.min(30_000, 500 * 2 ** attempt)).unref())
+ }
+ }
+ }
+
/** Staged results are counted so a slow slot holding back retirement still applies backpressure. */
private overCapacity(stagedCount = 0, stagedBytes = 0): boolean {
return (
@@ -366,6 +528,7 @@ export class ImageBatcher {
code,
partitions: offsets.map((o) => o.partition),
})
+ this.partitionsRevoked = true
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.ts
index 4a53b19ea150..c01adc83dd2d 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts
@@ -1,9 +1,6 @@
import { Counter, Histogram } from 'prom-client'
-import { ScrubUnavailableReason } from './scrub-client'
-
-/** The scrub client's reasons, plus the two the batch itself owns and the client never sees. */
-export type DropReason = ScrubUnavailableReason | 'deadline' | 'unattempted'
+import { ScrubWaitReason } from './scrub-client'
export class ImageScrubConsumerMetrics {
private static readonly scrubbed = new Counter({
@@ -50,18 +47,90 @@ export class ImageScrubConsumerMetrics {
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. Nothing else reports that:
- * a pod dropping every image still passes its probes, keeps its lag flat, and keeps advancing
- * offsets.
+ * The saturation signal, and the one to alert on.
+ *
+ * Each increment is one attempt that came back without bytes and will be retried rather than
+ * abandoned, so this never means data was lost. What it means is that the consumer is spending
+ * wall time waiting on the sidecar instead of draining, which is the thing that turns into lag.
+ * Read it against `scrubbed`: a small ratio is a lane near its ceiling, and a large one means the
+ * sidecar is not keeping up and the backlog is growing.
*/
- private static readonly dropped = new Counter({
- name: 'ml_mirror_image_scrub_consumer_dropped_total',
- help: 'Images dropped because the sidecar could not take them. Never published, so this is lost coverage rather than leaked content. By reason: "busy" (503, shed), "timeout" (no reply inside the request timeout), "transport" (socket refused or reset, or an unexpected status), "aborted" (a sibling failure ended the batch), "deadline" (in flight when the batch scrub budget expired), "unattempted" (never submitted, because the budget expired first)',
+ private static readonly scrubWaits = new Counter({
+ name: 'ml_mirror_image_scrub_consumer_scrub_waits_total',
+ help: 'Scrub attempts that returned no bytes and will be retried, by reason: "busy" (503, shed), "timeout" (no reply inside the request timeout), "transport" (socket refused or reset, or an unexpected status). Retried rather than dropped, so this is backpressure and not loss',
labelNames: ['reason'],
})
+ /**
+ * Images that have been retried long past what any healthy sidecar needs for one image.
+ *
+ * Separate from the wait counter because it means something different. Waits rise and fall with
+ * load; this rising while `scrub_waits_total{reason="busy"}` is flat points at one image the
+ * sidecar cannot process rather than at capacity, and that image is holding the head of its
+ * partition. The log line beside it carries the ref.
+ */
+ private static readonly stuckImages = new Counter({
+ name: 'ml_mirror_image_scrub_consumer_stuck_images_total',
+ help: 'Images still being retried after the point where a healthy sidecar would have finished, so likely unprocessable rather than merely queued. Each one holds the head of its partition until it succeeds',
+ })
+ /**
+ * How much of a batch reached a recordable offset, and how long the batch took.
+ *
+ * Offsets retire contiguously from the front, so one image stuck at the head holds back every
+ * completed image behind it: the pod carries their bytes without being able to commit any of
+ * them. Nothing else distinguishes that from a batch that was simply slow, and the difference
+ * matters, because a batch running long against max.poll.interval.ms is what gets the pod
+ * evicted and its work redone elsewhere.
+ */
+ private static readonly batchRetiredRatio = new Histogram({
+ name: 'ml_mirror_image_scrub_consumer_batch_retired_ratio',
+ help: 'Share of a batch that retired to a recordable offset. Well under 1 means head-of-line blocking: later images finished but a stuck one at the front prevented any offset advancing',
+ buckets: [0, 0.25, 0.5, 0.75, 0.9, 0.99, 1],
+ })
+ private static readonly batchDuration = new Histogram({
+ name: 'ml_mirror_image_scrub_consumer_batch_duration_seconds',
+ help: 'Wall time per poll batch. Read against Kafka max.poll.interval.ms (300s): batches approaching it get the pod evicted mid-batch, and the partition is redone by whoever picks it up',
+ buckets: [1, 5, 15, 30, 60, 120, 240, 300, 600],
+ })
+ /**
+ * Images parked on the dead-letter topic because the sidecar could not process them.
+ *
+ * Not a loss counter: the bytes are still in Kafka, and the reason this exists at all is that
+ * one such image otherwise holds the head of its partition against every team whose records
+ * share it. It should sit at zero. Anything above a trickle is a sidecar bug reproducing across
+ * many images rather than a genuinely odd one, and the fix is in the sidecar, not here.
+ */
+ private static readonly deadLettered = new Counter({
+ name: 'ml_mirror_image_scrub_consumer_dead_lettered_total',
+ help: 'Images published to the dead-letter topic after the sidecar repeatedly failed on them while succeeding on others. The bytes are retained, so this is quarantine rather than loss',
+ labelNames: ['reason'],
+ })
+ /**
+ * Failed attempts to park an image, each of which leaves it at the head of its partition.
+ *
+ * Distinct from the dead-letter counter because the consequence is opposite: this is the lane
+ * stalled on an image it cannot scrub and cannot put anywhere, which is the pre-dead-letter
+ * behaviour and needs the topic looked at (wrong cluster, missing, or max.message.bytes below
+ * what a source image can be).
+ */
+ private static readonly deadLetterFailed = new Counter({
+ name: 'ml_mirror_image_scrub_consumer_dead_letter_failed_total',
+ help: 'Attempts to publish to the dead-letter topic that failed. Each leaves an unscrubbed image holding the head of its partition, so a sustained rate means the topic is misconfigured rather than that images are bad',
+ })
+ /**
+ * Parked images pushed back at the source topic by a replay run, and those left behind.
+ *
+ * `exhausted` is the one that needs reading: those images have been round-tripped as often as
+ * they are allowed to be and will not be replayed again, so they stay parked until someone
+ * either fixes what rejects them or accepts losing them to retention.
+ */
+ private static readonly replayed = new Counter({
+ name: 'ml_mirror_image_scrub_consumer_replayed_total',
+ help: 'Parked images published back to the source topic by a replay run',
+ })
+ private static readonly replayExhausted = new Counter({
+ name: 'ml_mirror_image_scrub_consumer_replay_exhausted_total',
+ help: 'Parked images a replay run left in place because they have already been round-tripped the maximum number of times, so the sidecar still cannot process them',
+ })
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',
@@ -81,8 +150,29 @@ export class ImageScrubConsumerMetrics {
public static incSkipped(): void {
this.skipped.inc()
}
- public static incDropped(reason: DropReason, count = 1): void {
- this.dropped.labels(reason).inc(count)
+ public static incScrubWait(reason: ScrubWaitReason): void {
+ this.scrubWaits.labels(reason).inc()
+ }
+ public static incStuckImage(): void {
+ this.stuckImages.inc()
+ }
+ public static observeBatchProgress(retired: number, planned: number, durationSeconds: number): void {
+ if (planned > 0) {
+ this.batchRetiredRatio.observe(retired / planned)
+ }
+ this.batchDuration.observe(durationSeconds)
+ }
+ public static incDeadLettered(reason: string): void {
+ this.deadLettered.labels(reason).inc()
+ }
+ public static incDeadLetterFailed(): void {
+ this.deadLetterFailed.inc()
+ }
+ public static incReplayed(): void {
+ this.replayed.inc()
+ }
+ public static incReplayExhausted(): void {
+ this.replayExhausted.inc()
}
public static incOffsetsDiscarded(count: number): void {
this.offsetsDiscarded.inc(count)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.test.ts
new file mode 100644
index 000000000000..b1bfbd3f23be
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.test.ts
@@ -0,0 +1,173 @@
+import { Server, createServer } from 'node:http'
+import { AddressInfo } from 'node:net'
+
+import { ScrubAborted, ScrubClient, ScrubContractError, ScrubPoisoned } from './scrub-client'
+
+type Reply = { status: number; body?: string }
+
+describe('ScrubClient', () => {
+ let server: Server
+ let replies: Reply[]
+ let requests: number
+ let replyFor: ((body: string) => Reply | undefined) | undefined
+
+ // A real loopback server rather than a mocked `request`: the retry loop only matters in terms of
+ // what it does with actual responses, and the 503 shed path in particular is a status the sidecar
+ // sends without reading the body, which a mock would not reproduce.
+ beforeEach(async () => {
+ replies = []
+ requests = 0
+ replyFor = undefined
+ server = createServer((req, res) => {
+ requests += 1
+ const chunks: Buffer[] = []
+ req.on('data', (c: Buffer) => chunks.push(c))
+ req.on('end', () => {
+ // Keyed on the request body when a rule is set, so a poison image and its healthy
+ // neighbours can be in flight at once, which is the only arrangement in which the
+ // "failing while others succeed" rule means anything.
+ const reply = replyFor?.(Buffer.concat(chunks).toString()) ??
+ replies.shift() ?? { status: 200, body: 'scrubbed' }
+ res.writeHead(reply.status).end(reply.body ?? '')
+ })
+ })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ })
+
+ afterEach(async () => {
+ await new Promise((resolve) => server.close(resolve))
+ })
+
+ const client = (deadLetters = false): ScrubClient =>
+ new ScrubClient(
+ `http://127.0.0.1:${(server.address() as AddressInfo).port}`,
+ 1000,
+ deadLetters,
+ // Backoff is asserted separately; sleeping for real would only make this slow and flaky.
+ () => Promise.resolve(),
+ () => 1
+ )
+
+ it.each([
+ ['shed with 503', 503],
+ ['a 500 from a struggling sidecar', 500],
+ ['a 502 from a half-started sidecar', 502],
+ ['a 429', 429],
+ // Reachable from image content, not from a bad deployment: the sidecar's success path
+ // returns whatever the scrub produced, so a zero-length result is a plain 200 with no body.
+ ['success with no bytes', 200],
+ ])('keeps waiting through %s until the sidecar returns bytes', async (_label, status) => {
+ // The regression this exists for: a bounded retry that gives up turns a saturated sidecar
+ // into permanent data loss, when Kafka is already holding the image durably and the only
+ // cost of waiting is lag. Nothing here may resolve to null or throw.
+ replies = Array.from({ length: 25 }, () => ({ status, body: '' }))
+
+ await expect(client().scrub(Buffer.from('image'))).resolves.toEqual(Buffer.from('scrubbed'))
+ expect(requests).toBe(26)
+ })
+
+ it.each([
+ ['a misdirected URL or renamed route', 404, ''],
+ ['a drifted request contract', 400, ''],
+ ['a method the sidecar does not serve', 405, ''],
+ ])('fails the batch on %s rather than waiting on it', async (_label, status, body) => {
+ // Waiting only makes sense for answers a later attempt could change. These say the deployment
+ // is wrong, and waiting on them forever would turn a config mistake into a pod that consumes
+ // nothing, passes every probe, and shows up only as lag hours later.
+ replies = [{ status, body }]
+
+ await expect(client().scrub(Buffer.from('image'))).rejects.toThrow(ScrubContractError)
+ expect(requests).toBe(1)
+ })
+
+ it.each([
+ ['undecodable', 422],
+ ['too large', 413],
+ ])('gives up immediately on %s, which no retry could change', async (_label, status) => {
+ replies = [{ status }]
+
+ await expect(client().scrub(Buffer.from('image'))).resolves.toBeNull()
+ expect(requests).toBe(1)
+ })
+
+ it('never dead-letters on saturation alone, however long the sidecar sheds', async () => {
+ // The safety property of the whole dead-letter path. Under a backlog every image waits a
+ // long time, so anything keyed on waiting or failure count alone would park the entire
+ // stream, which is the mass loss the wait exists to prevent arriving through another door.
+ // Nothing succeeds here, so nothing may be blamed on any one image.
+ replies = Array.from({ length: 400 }, () => ({ status: 503, body: '' }))
+
+ await expect(client(true).scrub(Buffer.from('image'))).resolves.toEqual(Buffer.from('scrubbed'))
+ })
+
+ it('holds an image through a sidecar failing everything, rather than parking it for the outage', async () => {
+ // A sidecar 500ing on every image is the sidecar, not the content, and parking images for it
+ // would quarantine the whole stream for a bug that has nothing to do with them. How long it
+ // rides out is bounded by Kafka's poll lease rather than chosen: the batch cannot return
+ // while this image is in flight, so a pod that waits past the lease is fenced and the work
+ // simply moves to another pod to be repeated.
+ replies = Array.from({ length: 8 }, () => ({ status: 500, body: '' }))
+
+ await expect(client(true).scrub(Buffer.from('image'))).resolves.toEqual(Buffer.from('scrubbed'))
+ })
+
+ it('parks an image eventually even with no peers to prove the sidecar works', async () => {
+ // The success test cannot pass when nothing else is succeeding, and the images in a batch are
+ // chosen by whoever produced them: fill one with content the sidecar rejects and no peer is
+ // left to vouch for it. Without a way out, that stalls a partition shared by every team whose
+ // records hash to it, which is worse than parking for an outage — parking keeps the bytes and
+ // is loud, a stall keeps nothing moving and is silent.
+ replies = Array.from({ length: 5000 }, () => ({ status: 500, body: '' }))
+
+ await expect(client(true).scrub(Buffer.from('image'), undefined, 'ref-1')).rejects.toThrow(ScrubPoisoned)
+ })
+
+ /**
+ * One image the sidecar always 500s on, alongside a stream it scrubs fine, in flight together.
+ *
+ * Returned wrapped, because awaiting an async function that returns a promise adopts that
+ * promise instead of handing it back, which would await the poison scrub here rather than in the
+ * assertion.
+ */
+ const poisonAmongHealthy = async (c: ScrubClient): Promise<{ inFlight: Promise<Buffer | null> }> => {
+ replyFor = (body) => (body.startsWith('poison') ? { status: 500, body: '' } : undefined)
+ const inFlight = c.scrub(Buffer.from('poison'), undefined, 'ref-1')
+ inFlight.catch(() => {}) // settled by the caller; this only stops an unhandled rejection
+ // Only a handful, deliberately: a poison image late in a batch has just its few concurrent
+ // neighbours to prove the sidecar works, because the batch cannot finish while it is in
+ // flight and the pod cannot poll for more. A gate needing more than that never opens.
+ for (let i = 0; i < 4; i++) {
+ await c.scrub(Buffer.from(`healthy-${i}`))
+ }
+ return { inFlight }
+ }
+
+ it('dead-letters an image that keeps failing while the sidecar succeeds on others', async () => {
+ // The case the dead-letter topic exists for: the sidecar demonstrably works, and this one
+ // image still cannot get through, so it is the content and it must stop holding the head of
+ // its partition.
+ const { inFlight } = await poisonAmongHealthy(client(true))
+
+ await expect(inFlight).rejects.toThrow(ScrubPoisoned)
+ })
+
+ it('keeps waiting on a poison image when there is nowhere to park it', async () => {
+ // Without a dead-letter destination the only alternative to waiting is discarding, so a
+ // misconfigured producer must cost throughput on one partition rather than the image.
+ const { inFlight } = await poisonAmongHealthy(client(false))
+ replyFor = undefined
+
+ await expect(inFlight).resolves.toEqual(Buffer.from('scrubbed'))
+ })
+
+ it('stops waiting when the caller hangs up', async () => {
+ // The one escape from the loop. Without it a shutdown would block on a sidecar that is never
+ // going to answer, and the pod would have to be killed rather than draining.
+ replies = Array.from({ length: 50 }, () => ({ status: 503, body: '' }))
+ const controller = new AbortController()
+ const scrubbing = client().scrub(Buffer.from('image'), controller.signal)
+ controller.abort()
+
+ await expect(scrubbing).rejects.toThrow(ScrubAborted)
+ })
+})
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.ts
index 830f46be3792..5d1c96eaa0cb 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
@@ -1,49 +1,168 @@
import { request } from 'node:http'
-import { promiseRetry } from '~/common/utils/retries'
+import { logger } from '~/common/utils/logger'
-class PermanentScrubReject extends Error {}
+import { ImageScrubConsumerMetrics } from './metrics'
/** The timeout's own message, matched on rather than duplicated, so the reason label cannot drift. */
const REQUEST_TIMED_OUT = 'scrub request timed out'
/**
- * 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.
+ * Why a single attempt did not come back with bytes.
*
- * Separated from every other failure because the two need opposite handling: failing the batch over
- * a busy sidecar exits the consumer process, and the partitions it gives up land on pods that are
- * equally busy, so the saturation spreads rather than easing.
- *
- * The reasons blur into each other under load, which is why they are one class. The 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.
+ * `rejected` is kept apart from `transport` because only it means the sidecar took the image,
+ * looked at it, and could not produce bytes. A refused or reset socket says nothing about content.
*/
-export type ScrubUnavailableReason = 'busy' | 'timeout' | 'transport' | 'aborted'
+export type ScrubWaitReason = 'busy' | 'timeout' | 'transport' | 'rejected'
+
+/** Raised only when the caller hangs up, which is the one condition that stops the wait. */
+export class ScrubAborted extends Error {}
-export class ScrubUnavailable extends Error {
+/** A response no amount of waiting can turn into bytes, so the batch fails loudly instead. */
+export class ScrubContractError extends Error {}
+
+/**
+ * This image, specifically, is one the sidecar cannot process. Its bytes belong in the dead-letter
+ * topic so the partition can move on.
+ */
+export class ScrubPoisoned extends Error {
constructor(
message: string,
- readonly reason: ScrubUnavailableReason,
- options?: ErrorOptions
+ readonly detail: { reason: ScrubWaitReason; lastError: string; attempts: number; waitedMs: number }
) {
- super(message, options)
+ super(message)
}
}
-class ScrubAborted extends ScrubUnavailable {
- constructor(message: string) {
- super(message, 'aborted')
- }
+/**
+ * What makes an image poison rather than unlucky.
+ *
+ * This is the whole safety question for the dead-letter path, because under saturation every image
+ * waits a long time, so anything keyed on waiting alone would dead-letter the entire stream during a
+ * backlog. That is the mass loss the wait exists to prevent, arriving through a different door.
+ *
+ * A poison image is distinguished by failing WHILE OTHER IMAGES SUCCEED. A sidecar that is full or
+ * wedged fails everything equally, so no image ever meets the second condition and the lane keeps
+ * waiting, which is correct. Only once the sidecar has demonstrably scrubbed other images can a
+ * persistent failure be attributed to this one.
+ *
+ * A 503 is excluded from the count for the same reason: it is the sidecar declining to look at the
+ * image at all, so it says nothing about the content, and under load an unlucky image can collect
+ * plenty of them while its neighbours get slots.
+ */
+const POISON_MIN_FAILURES = 12
+
+/**
+ * Other images the sidecar must scrub while this one keeps being rejected.
+ *
+ * Deliberately small, and it must stay below the pod's scrub concurrency. A batch cannot finish
+ * while one of its images is still in flight, and a pod cannot poll for more work until its batch
+ * finishes, so the only successes that can ever arrive are from the handful of slots running
+ * alongside this image right now. Ask for more than that and an image late in a batch can never
+ * reach the threshold, the batch never returns, and the pod stops consuming for good: a deadlock
+ * rather than the stall the dead-letter topic was added to remove. ImageBatcher asserts the
+ * relationship at construction so a future concurrency change fails at boot instead of in traffic.
+ */
+export const POISON_MIN_OTHER_SUCCESSES = 3
+
+/**
+ * Accumulated backoff after which a sidecar that keeps answering is taken at its word.
+ *
+ * The success test cannot be satisfied when nothing else is succeeding, and the images in a batch
+ * are chosen by whoever produced them: fill one with content the sidecar rejects and no peer is left
+ * to prove it works, so the gate never opens. This is the way out. It only applies while the sidecar
+ * is still returning considered answers, so a full or unreachable one still waits forever.
+ *
+ * It has to fire comfortably inside Kafka's max.poll.interval.ms (300s), and that is the binding
+ * constraint rather than a preference. A batch cannot return while one of its images is in flight,
+ * so a threshold above the lease can never be reached: the group fences the pod first, the partition
+ * moves, and its new owner repeats the same work and is fenced in turn. The gate would be dead code
+ * and the images would circle the fleet. This counts backoff only, and real elapsed time is longer,
+ * so the margin below the lease has to be generous rather than exact.
+ *
+ * The trade is deliberate. A sidecar broken for this long parks images rather than holding them,
+ * which keeps every byte, is loud in the dead-letter counter, and is replayable, against a silent
+ * stall that holds a shared partition hostage and moves nothing.
+ */
+export const POISON_MAX_WAITED_MS = 120_000
+
+const BACKOFF_BASE_MS = 100
+/**
+ * Ceilings on the wait, by what the failure says about the sidecar.
+ *
+ * A 503 is the sidecar stating it is full, so backing off hard is the point: at the short cap eight
+ * in-flight images per pod keep up a steady stream of re-posts against something already shedding,
+ * which is load rather than backpressure and slows the recovery it is waiting for. A refused socket
+ * is different, because the ordinary cause is the sidecar still starting up in the same pod, and
+ * waiting half a minute to notice it came up is a needless stall.
+ */
+const BACKOFF_MAX_MS: Record<ScrubWaitReason, number> = {
+ busy: 30_000,
+ timeout: 5_000,
+ transport: 5_000,
+ // The sidecar answered, so it is neither full nor unreachable, and re-asking quickly costs it a
+ // whole scrub attempt each time. Backed off like a shed request rather than like a lost socket.
+ rejected: 30_000,
+}
+
+/**
+ * Backoff time on one image before it is called out by ref, and the interval between repeats.
+ *
+ * Measured in time rather than attempts because the per-reason caps differ by six times, so a fixed
+ * attempt count means three minutes on the busy path and forty seconds on the others. Two minutes is
+ * far longer than any healthy sidecar spends on one image, so crossing it means either a sidecar
+ * that is down or an image it cannot process. The second is the one that needs naming: the bytes are
+ * user-controlled, and an image that fails the same way forever holds the head of its partition,
+ * which is a stall shared by every team whose records hash to it. Waiting still beats discarding,
+ * but it must not be silent.
+ *
+ * Accumulated from the backoffs rather than read off a clock, so it measures time spent waiting on
+ * the sidecar rather than time the process spent descheduled, and so tests can drive it.
+ */
+const STUCK_AFTER_WAITED_MS = 120_000
+
+/** Full jitter, so a pod's eight in-flight images do not all re-post to a busy sidecar in lockstep. */
+function backoffMs(attempt: number, reason: ScrubWaitReason, random: () => number): number {
+ return Math.round(random() * Math.min(BACKOFF_MAX_MS[reason], BACKOFF_BASE_MS * 2 ** attempt))
+}
+
+/**
+ * Whether waiting could ever change the answer.
+ *
+ * 5xx and the two "come back later" 4xx are the sidecar being unable to serve this image right now.
+ * Any other status is the sidecar answering a question we did not think we were asking: a 404 from a
+ * misdirected SIDECAR_URL or a renamed route, a 400 from a contract that has drifted. Waiting on
+ * those forever converts a deploy-time mistake into a pod that consumes nothing, passes every probe,
+ * and shows up only as lag, so they are raised instead.
+ */
+function isWaitable(status: number): boolean {
+ return status >= 500 || status === 408 || status === 429
}
export class ScrubClient {
private readonly url: URL
+ /**
+ * Images this pod has scrubbed, ever. Only ever read as a difference, to answer "has the sidecar
+ * been working while this one image kept failing", which is what separates poison from load.
+ */
+ private successes = 0
constructor(
baseUrl: string,
private readonly timeoutMs: number,
- private readonly maxRetries: number
+ /**
+ * Whether a dead-letter destination exists. Without one there is nowhere to put a poison
+ * image, and the only alternative to waiting would be discarding it, so the client keeps
+ * waiting instead. Failing safe here means a misconfigured producer costs throughput on one
+ * partition rather than data.
+ */
+ private readonly deadLetters: boolean = false,
+ // unref'd: an abort stops the wait but leaves this timer scheduled, and a referenced one
+ // holds the event loop open for the rest of its interval, which on the busy path is half a
+ // minute of a process that has already finished shutting down.
+ private readonly sleep: (ms: number) => Promise<void> = (ms) =>
+ new Promise((resolve) => setTimeout(resolve, ms).unref()),
+ private readonly random: () => number = Math.random
) {
this.url = new URL('/scrub', baseUrl)
}
@@ -51,54 +170,122 @@ export class ScrubClient {
/**
* 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. Keeping that guarantee at this boundary is what leaves the caller free
- * to lose a single image, since anything escaping it reaches the Kafka loop, which exits the
- * process on any error.
+ * A sidecar with no capacity is waited on, not given up on, however long that takes. Kafka is
+ * already holding this image durably, so the only thing a bounded retry buys is the chance to
+ * throw away data the log was keeping safe; consuming more slowly costs nothing but lag, which
+ * the topic exists to absorb. The wait is what applies backpressure: a batch that takes longer
+ * calls consume() later, so the consumer paces itself to whatever the sidecar can execute,
+ * without needing to pause partitions explicitly.
+ *
+ * Only two things end the loop. Bytes, or a verdict on the content that no retry could change.
+ * The caller hanging up raises [[ScrubAborted]], which belongs to shutdown rather than to load.
*/
- public async scrub(bytes: Buffer, signal?: AbortSignal): Promise<Buffer | null> {
- try {
- return await promiseRetry(
- async () => {
- if (signal?.aborted) {
- throw new ScrubAborted('scrub batch aborted')
- }
- const { status, body } = await this.post(bytes, signal)
- if (status === 200) {
- if (body.length === 0) {
- throw new ScrubUnavailable('sidecar returned an empty 200 body', 'transport')
- }
- return body
- }
- if (status === 422 || status === 413) {
- throw new PermanentScrubReject(`sidecar rejected the input (${status})`)
- }
- throw new ScrubUnavailable(`sidecar responded ${status}`, status === 503 ? 'busy' : 'transport')
- },
- 'image-scrub-sidecar',
- // promiseRetry count is total attempts; +1 makes maxRetries mean retries after the first try.
- this.maxRetries + 1,
- undefined,
- undefined,
- [PermanentScrubReject, ScrubAborted]
- )
- } catch (error) {
- if (error instanceof PermanentScrubReject) {
- return null
+ public async scrub(bytes: Buffer, signal?: AbortSignal, ref?: string): Promise<Buffer | null> {
+ let waitedMs = 0
+ let stuckReports = 0
+ let blamableFailures = 0
+ const successesAtStart = this.successes
+ for (let attempt = 0; ; attempt++) {
+ if (signal?.aborted) {
+ throw new ScrubAborted('scrub batch aborted')
}
- if (error instanceof ScrubUnavailable) {
- throw error
+ let reason: ScrubWaitReason
+ let detail: string
+ try {
+ const { status, body } = await this.post(bytes, signal)
+ if (status === 200 && body.length > 0) {
+ this.successes += 1
+ return body
+ }
+ if (status === 422 || status === 413) {
+ return null
+ }
+ // An empty 200 is deliberately NOT a contract error: the sidecar's success path
+ // returns whatever the scrub produced, so a zero-length result is reachable from
+ // image content. Treating it as a deployment fault would let one image crash-loop
+ // every pod, which is the failure this whole lane has been climbing out of.
+ if (status !== 200 && !isWaitable(status)) {
+ throw new ScrubContractError(`sidecar responded ${status}, which no wait can change`)
+ }
+ reason = status === 503 ? 'busy' : 'rejected'
+ detail = status === 200 ? 'sidecar returned an empty body' : `sidecar responded ${status}`
+ } catch (error) {
+ if (error instanceof ScrubAborted || error instanceof ScrubContractError) {
+ throw error
+ }
+ // Refused, reset, or destroyed by the request timeout. None of them say anything
+ // about this image, and none of them are fixed by dropping it.
+ detail = (error as Error)?.message ?? String(error)
+ reason = detail === REQUEST_TIMED_OUT ? 'timeout' : 'transport'
+ }
+ if (signal?.aborted) {
+ throw new ScrubAborted('scrub batch aborted')
+ }
+ ImageScrubConsumerMetrics.incScrubWait(reason)
+ // Only a considered answer counts towards blaming the content. A 503 is the sidecar
+ // declining to look at the image at all; a timeout is this caller giving up first, since
+ // its budget is shorter than the sidecar's own job deadline, so an image that is merely
+ // slow trips it while the sidecar is still working; and a refused or reset socket is the
+ // sidecar being unreachable, which is true of every image at once.
+ if (reason === 'rejected') {
+ blamableFailures += 1
+ }
+ const sidecarProvenHealthy = this.successes - successesAtStart >= POISON_MIN_OTHER_SUCCESSES
+ const waitedTooLong = waitedMs >= POISON_MAX_WAITED_MS
+ if (
+ this.deadLetters &&
+ blamableFailures >= POISON_MIN_FAILURES &&
+ (sidecarProvenHealthy || waitedTooLong)
+ ) {
+ throw new ScrubPoisoned(`sidecar cannot process this image: ${detail}`, {
+ reason,
+ lastError: detail,
+ attempts: attempt + 1,
+ waitedMs,
+ })
+ }
+ const delayMs = backoffMs(attempt, reason, this.random)
+ waitedMs += delayMs
+ // Repeated rather than emitted once: a single increment lets a rate() alert fire and then
+ // resolve itself while the partition is still stalled, which is the opposite of what a
+ // head-of-line block should look like.
+ if (waitedMs >= STUCK_AFTER_WAITED_MS * (stuckReports + 1)) {
+ stuckReports += 1
+ ImageScrubConsumerMetrics.incStuckImage()
+ // The error text exists nowhere else: the caller sees a counter, and telling a
+ // misdirected URL apart from genuine saturation needs the message, not the label.
+ logger.warn('🚨', 'image_scrub_image_stuck', {
+ ref,
+ reason,
+ detail,
+ attempts: attempt + 1,
+ waitedMs,
+ bytes: bytes.length,
+ })
}
- // 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. The
- // original is kept as `cause`: this is the last place the real reason exists, and the
- // caller only records a counter.
- const message = error instanceof Error ? error.message : String(error)
- throw new ScrubUnavailable(message, message === REQUEST_TIMED_OUT ? 'timeout' : 'transport', {
- cause: error,
- })
+ await this.waitOrAbort(delayMs, signal)
+ }
+ }
+
+ /** Sleeps, but gives the wait up the moment the caller hangs up rather than after the full backoff. */
+ private async waitOrAbort(ms: number, signal?: AbortSignal): Promise<void> {
+ if (!signal) {
+ await this.sleep(ms)
+ return
+ }
+ let release = (): void => {}
+ const aborted = new Promise<void>((resolve) => {
+ const onAbort = (): void => resolve()
+ release = () => signal.removeEventListener('abort', onAbort)
+ signal.addEventListener('abort', onAbort, { once: true })
+ })
+ try {
+ await Promise.race([this.sleep(ms), aborted])
+ } finally {
+ release()
+ }
+ if (signal.aborted) {
+ throw new ScrubAborted('scrub batch aborted')
}
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
index 65002cb7ca4d..3178072c0307 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
@@ -1,5 +1,7 @@
import os from 'node:os'
+import { KAFKA_SESSION_REPLAY_IMAGE_SCRUB_DLQ } from '~/common/config/kafka-topics'
+
export type MlMirrorConfig = {
/** S3 key prefix under the bucket for the block-metadata Parquet dataset (used by the sink). */
SESSION_RECORDING_ML_METADATA_PREFIX: string
@@ -55,16 +57,24 @@ export type MlMirrorConfig = {
* memory incident should not need a code deploy of the shared replay ingester.
*/
SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCED_REF_CACHE_MAX: number
+ /**
+ * How long to wait for the sidecar to answer one image.
+ *
+ * Must exceed the sidecar's own IMAGE_SCRUB_JOB_TIMEOUT_MS plus the time a request can sit in
+ * its admission queue, and the ordering is load-bearing rather than a matter of taste. The
+ * sidecar answers a job it cannot finish by retiring the worker and returning 500, which is a
+ * considered answer about that image and is what lets a genuinely unprocessable one be blamed
+ * and parked. Give up first and that answer never arrives: the image looks merely slow on every
+ * attempt, never earns blame, and sits at the head of a partition shared by every team whose
+ * records hash to it. A timeout is then what it should be, the sidecar saying nothing at all.
+ */
SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_TIMEOUT_MS: number
- SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_RETRIES: number
+ /** Where images the sidecar cannot process are parked so they stop holding their partition. */
+ 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.
SESSION_RECORDING_ML_IMAGE_SCRUB_S3_WRITE_TIMEOUT_MS: number
- // 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
-
/**
* Cap on messages scrubbed concurrently per pod. Each in-flight scrub occupies one libuv
* threadpool thread (UV_THREADPOOL_SIZE, default 4, shared with the recorder's snappy
@@ -96,10 +106,10 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {
SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_CONCURRENCY: 8,
SESSION_RECORDING_ML_IMAGE_SCRUB_DEDUP_MAX_REFS: 250_000,
SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCED_REF_CACHE_MAX: 500_000,
- SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_TIMEOUT_MS: 10 * 1000,
- SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_RETRIES: 3,
+ SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_TIMEOUT_MS: 45 * 1000,
+ SESSION_RECORDING_ML_IMAGE_SCRUB_DLQ_TOPIC: KAFKA_SESSION_REPLAY_IMAGE_SCRUB_DLQ,
+ SESSION_RECORDING_ML_IMAGE_SCRUB_BATCH_SIZE: 50,
SESSION_RECORDING_ML_IMAGE_SCRUB_S3_WRITE_TIMEOUT_MS: 30 * 1000,
- SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_BATCH_SCRUB_MS: 120 * 1000,
SESSION_RECORDING_ML_ANONYMIZE_MAX_CONCURRENCY: 0,
}
}
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-dlq-replay-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-dlq-replay-server.ts
new file mode 100644
index 000000000000..f293b2a1470b
--- /dev/null
+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-dlq-replay-server.ts
@@ -0,0 +1,112 @@
+import { initializePrometheusLabels } from '~/common/api/router'
+import { KafkaConsumer } from '~/common/kafka/consumer/consumer-v1'
+import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'
+import { SessionReplayProducerName } from '~/ingestion/pipelines/sessionreplay/config'
+import { replayBatch } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay'
+import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'
+import { INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER } from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'
+
+import { logger } from '../common/utils/logger'
+import { CleanupResources, NodeServer, ServerLifecycle } from './base-server'
+import {
+ IngestionSessionReplayMlMirrorServerConfig,
+ buildMlMirrorServerConfig,
+} from './ingestion-session-replay-ml-mirror-server'
+
+/**
+ * Pushes images the scrub sidecar could not process back onto the topic they came from.
+ *
+ * Run deliberately, after the sidecar bug that parked them has been fixed and deployed, by scaling
+ * this to one replica. It reads to the end of the dead-letter topic and stops, so it drains what is
+ * there and does not sit re-driving whatever arrives next.
+ *
+ * That it stops is the point rather than an implementation detail. A dead-letter topic earns its
+ * keep by holding images still: something continuously pushing them back would either empty the
+ * quarantine before anyone had looked at it, or, against a sidecar that is still broken, cycle the
+ * same images between the two topics and spend scrub capacity on work already known to fail. The
+ * lane has no capacity to spare for that.
+ */
+export class IngestionSessionReplayMlImageScrubDlqReplayServer implements NodeServer {
+ readonly lifecycle: ServerLifecycle
+ private config: IngestionSessionReplayMlMirrorServerConfig
+ private producerRegistry?: KafkaProducerRegistry<SessionReplayProducerName>
+
+ constructor(config: Partial<IngestionSessionReplayMlMirrorServerConfig> = {}) {
+ this.config = buildMlMirrorServerConfig(config)
+ this.lifecycle = new ServerLifecycle(this.config)
+ }
+
+ async start(): Promise<void> {
+ return this.lifecycle.start(
+ () => this.startServices(),
+ () => this.getCleanupResources()
+ )
+ }
+
+ async stop(error?: Error): Promise<void> {
+ return this.lifecycle.stop(() => this.getCleanupResources(), error)
+ }
+
+ private async startServices(): Promise<void> {
+ initializePrometheusLabels(this.config.INGESTION_PIPELINE, this.config.INGESTION_LANE)
+
+ const dlqTopic = this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_DLQ_TOPIC
+ if (!dlqTopic) {
+ throw new Error('SESSION_RECORDING_ML_IMAGE_SCRUB_DLQ_TOPIC must be set to replay from it')
+ }
+ this.producerRegistry = await createProducerRegistry(this.config.KAFKA_CLIENT_RACK).build(this.config)
+ const producer = this.producerRegistry.getProducer(INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER)
+
+ // A separate group from the scrub consumer's, and its own topic, so a replay run cannot
+ // disturb the offsets of the lane it is feeding.
+ const consumer = new KafkaConsumer({
+ topic: dlqTopic,
+ groupId: `${this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_GROUP_ID}-dlq-replay`,
+ autoCommit: true,
+ autoOffsetStore: true,
+ // Committing as it goes means an interrupted run resumes rather than starting over and
+ // replaying images the fixed sidecar has already taken.
+ callEachBatchWhenEmpty: true,
+ })
+
+ let idlePolls = 0
+ let replayed = 0
+ let exhausted = 0
+ await consumer.connect(async (messages) => {
+ if (messages.length === 0) {
+ idlePolls += 1
+ // Two consecutive empty polls means the topic is drained as of now. Stopping here is
+ // what makes the run bounded: the operator scaled this up to clear a backlog, not to
+ // leave something watching the quarantine.
+ if (idlePolls >= 2) {
+ logger.info('☠️', 'image_scrub_dlq_replay_complete', { replayed, exhausted })
+ void this.stop()
+ }
+ return
+ }
+ idlePolls = 0
+ const outcome = await replayBatch(
+ messages,
+ producer,
+ this.config.INGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_SCRUB_TOPIC
+ )
+ replayed += outcome.replayed
+ exhausted += outcome.exhausted
+ logger.info('☠️', 'image_scrub_dlq_replay_progress', { replayed, exhausted })
+ })
+
+ this.lifecycle.services.push({
+ id: 'session-replay-ml-image-scrub-dlq-replay',
+ onShutdown: () => consumer.disconnect(),
+ healthcheck: () => consumer.isHealthy(),
+ })
+ }
+
+ private getCleanupResources(): CleanupResources {
+ return {
+ kafkaProducers: [],
+ redisPools: [],
+ additionalCleanup: () => this.producerRegistry?.disconnectAll(),
+ }
+ }
+}
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 92ff276b0343..a8903ed528bc 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
@@ -3,9 +3,14 @@ import { S3Client } from '@aws-sdk/client-s3'
import { initializePrometheusLabels } from '~/common/api/router'
import { KAFKA_SESSION_REPLAY_IMAGE_SCRUB } from '~/common/config/kafka-topics'
import { KafkaConsumer, KafkaConsumerConfig } from '~/common/kafka/consumer/consumer-v1'
+import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'
+import { SessionReplayProducerName } from '~/ingestion/pipelines/sessionreplay/config'
+import { KafkaDeadLetterSink } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dead-letter-sink'
import { ImageBatcher } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher'
import { ImageShardStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store'
import { ScrubClient } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client'
+import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'
+import { INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER } from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'
import { buildSessionRecordingS3Client } from '~/ingestion/pipelines/sessionreplay/shared/s3-client'
import { CleanupResources, NodeServer, ServerLifecycle } from './base-server'
@@ -32,12 +37,21 @@ export function buildImageScrubConsumerConfig(config: IngestionSessionReplayMlMi
autoCommit: true,
autoOffsetStore: false,
callEachBatchWhenEmpty: true,
+ // Far below the 500 default, because this lane's batch has no time limit: a busy sidecar is
+ // waited on rather than dropped, so batch duration is set by how many images it holds. 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 just as busy and redoes the same images, so
+ // offered load rises while throughput falls. Set here rather than as a deployment value so
+ // the bound cannot drift away from the design that needs it.
+ fetchBatchSize: config.SESSION_RECORDING_ML_IMAGE_SCRUB_BATCH_SIZE,
}
}
export class IngestionSessionReplayMlImageScrubServer implements NodeServer {
readonly lifecycle: ServerLifecycle
private config: IngestionSessionReplayMlMirrorServerConfig
+ private producerRegistry?: KafkaProducerRegistry<SessionReplayProducerName>
constructor(config: Partial<IngestionSessionReplayMlMirrorServerConfig> = {}) {
this.config = buildMlMirrorServerConfig(config)
@@ -65,10 +79,28 @@ export class IngestionSessionReplayMlImageScrubServer implements NodeServer {
this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PREFIX,
this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_S3_WRITE_TIMEOUT_MS
)
+ // The lane's own producer slot, not the generic one. It is on the replay cluster that holds
+ // the source topic and carries this lane's message.max.bytes, and a parked image is an
+ // original of the same size as the source message. The generic slot points at a different
+ // cluster with librdkafka's 1 MB default, where every park of a normal image would fail
+ // non-retriably.
+ const dlqTopic = this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_DLQ_TOPIC
+ let deadLetters: KafkaDeadLetterSink | null = null
+ if (dlqTopic) {
+ this.producerRegistry = await createProducerRegistry(this.config.KAFKA_CLIENT_RACK).build(this.config)
+ deadLetters = new KafkaDeadLetterSink(
+ this.producerRegistry.getProducer(INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER),
+ dlqTopic
+ )
+ }
+ // Built after, because whether a dead-letter destination exists changes what the client does
+ // with an image it cannot get scrubbed: park it, or keep waiting on it forever. Clearing the
+ // topic is therefore the rollback, and it reverts to the documented waiting behaviour rather
+ // than to producing at an empty topic name.
const scrubClient = new ScrubClient(
this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_SIDECAR_URL,
this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_TIMEOUT_MS,
- this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_RETRIES
+ deadLetters !== null
)
const consumer = new KafkaConsumer(buildImageScrubConsumerConfig(this.config))
@@ -81,10 +113,10 @@ export class IngestionSessionReplayMlImageScrubServer implements NodeServer {
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,
- maxBatchScrubMs: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_BATCH_SCRUB_MS,
dedupMaxRefs: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_DEDUP_MAX_REFS,
},
- Date.now()
+ Date.now(),
+ deadLetters
)
await consumer.connect((messages) => {
const heartbeat = setInterval(() => consumer.heartbeat(), BATCH_HEARTBEAT_INTERVAL_MS)
@@ -93,10 +125,16 @@ export class IngestionSessionReplayMlImageScrubServer implements NodeServer {
this.lifecycle.services.push({
id: 'session-replay-ml-image-scrub',
- // disconnect() stops the poll loop and commits stored offsets. The un-flushed buffer's offsets were
- // never stored, so those messages just replay on restart — a final flush here would only race the
- // still-running loop over the shared buffer.
- onShutdown: () => consumer.disconnect(),
+ // batcher.stop() first: disconnect() waits on the running batch, and a batch waiting on an
+ // unresponsive sidecar never returns, so without the interrupt a graceful stop runs to the
+ // termination grace period and ends in a SIGKILL. Then disconnect() stops the poll loop and
+ // commits stored offsets. The un-flushed buffer's offsets were never stored, so those
+ // messages just replay on restart — a final flush here would only race the still-running
+ // loop over the shared buffer.
+ onShutdown: async () => {
+ batcher.stop()
+ await consumer.disconnect()
+ },
healthcheck: () => consumer.isHealthy(),
})
}
@@ -104,6 +142,7 @@ export class IngestionSessionReplayMlImageScrubServer implements NodeServer {
private getCleanupResources(): CleanupResources {
return {
kafkaProducers: [],
+ additionalCleanup: () => this.producerRegistry?.disconnectAll(),
redisPools: [],
}
}