:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(replay): make the scrub's drops legible and stop over-dropping (#73728)
Robbie60d4b28091ee
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.mdindex b7a83d03e9de..c6836c0509e4 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@@ -12,9 +12,13 @@ It runs a simple http server, receives an image and replies with the scrubbed im`POST /scrub` with the raw image bytes returns the scrubbed bytes (200). The status split is load-bearing and both sides must change together: the consumer permanently skips 413 (too large) and 422 (undecodable), and retries then **drops** the image on 500 (transient) and 503 (busy). See `scrub-client.ts` for the consumer half.-A dropped image is counted in `ml_mirror_image_scrub_consumer_dropped_total` and never reaches the bucket, so the failure costs coverage rather than leaking content.-It used to fail the Kafka batch instead, which exits the consumer process: a saturated sidecar therefore crash-looped its pod, and the partitions it gave up landed on pods that were equally saturated, so saturation spread rather than eased.-Nothing about a busy or unreachable sidecar should ever take the consumer down, because the sidecar is a separate container that a consumer restart does not fix.+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.++**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.+A consumer restart cannot fix the sidecar in any case: it is a separate container that keeps running.`maxConcurrency` is derived from `SCRUB_WORKERS` rather than set independently, so the sidecar sheds load it cannot execute instead of admitting it into an accept queue.That matters because the consumer's per-request timeout is an inactivity timeout: a queued request sends no bytes, so queueing reads to the consumer as an unresponsive sidecar rather than a busy one, and a fast 503 is the signal it can actually act on.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.tsindex 9fc7ed74a00f..87a20a5fb9b3 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@@ -29,17 +29,11 @@ export interface Config {jobTimeoutMs: number}-// Validated like every other knob: a mistyped IMAGE_SCRUB_CONCURRENCY parsed to NaN leaves-// `inFlight >= maxConcurrency` permanently false, which removes load shedding entirely rather than-// failing loudly.export function loadConfig(): Config {return {port: numFromEnv('IMAGE_SCRUB_PORT', 9010, 1, 65535),metricsPort: numFromEnv('IMAGE_SCRUB_METRICS_PORT', 9011, 1, 65535),- // Derived from the worker count rather than fixed, so the two cannot drift apart. A fixed 8- // against a pod that could execute fewer left the difference sitting in the accept queue,- // where it timed out the consumer instead of being shed.- maxConcurrency: numFromEnv('IMAGE_SCRUB_CONCURRENCY', ADMITTED_PER_WORKER * SCRUB_WORKERS, 1, 256),+ maxConcurrency: ADMITTED_PER_WORKER * SCRUB_WORKERS,maxBodyBytes: numFromEnv('IMAGE_SCRUB_MAX_BODY_BYTES', 20 * 1024 * 1024, 1024, 512 * 1024 * 1024),jobTimeoutMs: numFromEnv('IMAGE_SCRUB_JOB_TIMEOUT_MS', 15_000, 1000, 600_000),}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.tsindex f5fd7b8287c3..40ee016041d1 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.ts@@ -37,9 +37,9 @@ const aborted = new Counter({const duration = new Histogram({name: 'ml_mirror_image_scrub_duration_seconds',help: 'Scrub wall time',- // Out to 60s: under IMAGE_SCRUB_CONCURRENCY-way contention a single scrub's wall time runs to- // seconds, and a quantile whose true value sits in the +Inf bucket reports the highest finite- // edge instead. A ceiling that traffic actually reaches reads as a flat line at that ceiling.+ // Out to 60s: under full admission contention a single scrub's wall time runs to seconds, and a+ // quantile whose true value sits in the +Inf bucket reports the highest finite edge instead. A+ // ceiling that traffic actually reaches reads as a flat line at that ceiling.buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 20, 60],registers: [register],})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.tsindex 3aef4ce7e3d3..74f483071dc6 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts@@ -41,10 +41,15 @@ export function startServer(app.disable('x-powered-by')app.disable('etag')- const shedIfBusy = (_req: Request, res: Response, next: NextFunction): void => {+ const shedIfBusy = (req: Request, res: Response, next: NextFunction): void => {if (inFlight >= maxConcurrency) {ScrubMetrics.incRejected()- res.status(503).send('busy')+ // Drain first: this runs ahead of the body parser, and Node destroys the socket when a+ // response completes with an unread request body. The caller would then see a reset+ // rather than the 503, which is the one status it can tell apart from a real fault, and+ // the shed would be indistinguishable from the sidecar falling over.+ req.resume()+ req.once('end', () => res.status(503).send('busy'))return}inFlight += 1diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.tsindex e9d1ab1b7234..cd9a59d22097 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts@@ -1,4 +1,5 @@import { Message, TopicPartitionOffset } from 'node-rdkafka'+import { register } from 'prom-client'import { hashImageBytes, imageRef } from './content-ref'import { ImageBatcher, OffsetStore } from './image-batcher'@@ -44,6 +45,18 @@ class FakeOffsets implements OffsetStore {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,@@ -501,6 +514,31 @@ describe('ImageBatcher', () => {expect(store.writes).toHaveLength(0)})+ 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+ const batcher = new ImageBatcher(+ new FakeStore() as unknown as ImageShardStore,+ new FakeOffsets(),+ hangingClient,+ { ...options, scrubConcurrency: 2, maxBatchScrubMs: 5 },+ 0+ )++ 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()++ expect(after.capacity - before.capacity).toBe(2)+ expect(after.unattempted - before.unattempted).toBe(18)+ })+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@@ -508,7 +546,7 @@ describe('ImageBatcher', () => {const store = new FakeStore()const offsets = new FakeOffsets()const busyClient = {- scrub: () => Promise.reject(new ScrubUnavailable('scrub request timed out')),+ scrub: () => Promise.reject(new ScrubUnavailable('scrub request timed out', 'timeout')),} as unknown as ScrubClientconst batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, busyClient, options, 0)@@ -527,7 +565,7 @@ describe('ImageBatcher', () => {scrub: (b: Buffer) => {attempts += 1return attempts === 1- ? Promise.reject(new ScrubUnavailable('sidecar responded 503'))+ ? Promise.reject(new ScrubUnavailable('sidecar responded 503', 'busy')): Promise.resolve(b)},} as unknown as ScrubClientdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.tsindex abef2f5f13a1..e88fb2e6b63f 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts@@ -2,6 +2,7 @@ import { LibrdKafkaError, Message, TopicPartitionOffset } from 'node-rdkafka'import { findOffsetsToCommit } 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'import { parseImageRef } from './content-ref'@@ -13,8 +14,21 @@ export interface OffsetStore {offsetsStore(offsets: TopicPartitionOffset[]): void}-/** librdkafka's RD_KAFKA_RESP_ERR__STATE, which offsetsStore raises for a partition we no longer hold. */-const ERR__STATE = -172+/**+ * The librdkafka codes that mean "this partition is not ours to store an offset for".+ *+ * Which one a revoke produces depends on where in the revoke sequence the store lands: __STATE when+ * the partition object still exists but its offset store is stopped, __UNKNOWN_PARTITION when it is+ * gone from the assignment entirely, and the fenced/lost pair when the group has moved on without+ * 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.+ */+const REVOKED_PARTITION_CODES = new Set([+ -172, // ERR__STATE+ -190, // ERR__UNKNOWN_PARTITION+ -142, // ERR__ASSIGNMENT_LOST+ -144, // ERR__FENCED+])/** The batch index is what lets offsets advance across the messages planning skipped. */interface PlannedScrub {@@ -94,7 +108,7 @@ export class ImageBatcher {// A sliding window rather than fixed groups: every completion immediately admits the next// image, so the sidecar never waits on the slowest member of a group before being given more- // work. Grouping used to gate throughput on E[slowest of N] instead of E[mean], which on a+ // work. Grouping would gate throughput on E[slowest of N] instead of E[mean], which on a// spread-out scrub-time distribution leaves a large share of the sidecar's cores idle.//// Admission is what bounds memory: scrubbed outputs can dwarf their inputs (a sub-MB input@@ -108,9 +122,8 @@ export class ImageBatcher {const controller = new AbortController()let scrubBudgetMs = this.options.maxBatchScrubMs// Set by the deadline rather than inferred from the error, because the abort surfaces as- // whatever the concurrency controller rejects with and not as a scrub error at all. Reading- // it back off the error is how the deadline stayed fatal while every other capacity failure- // was made survivable, which would have moved the crash rather than removed it.+ // 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 = falselet spanStart = 0let nextToSubmit = 0@@ -127,6 +140,7 @@ export class ImageBatcher {while (nextToSubmit < planned.length || inFlight.size > 0) {while (+ !deadlineExpired &&nextToSubmit < planned.length &&inFlight.size < this.maxInFlight &&!this.overCapacity(stagedCount, stagedBytes)@@ -134,8 +148,15 @@ 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) {+ break+ }+ // Only reachable over capacity with work left: flush to make room rather than spin.await this.flushOrThrow(nowMs)continue}@@ -163,7 +184,9 @@ export class ImageBatcher {// 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()+ ImageScrubConsumerMetrics.incDropped(+ deadlineExpired ? 'deadline' : (done.error as ScrubUnavailable).reason+ )}if (done.scrubbed) {staged[done.slot] = done.scrubbed@@ -202,6 +225,13 @@ export class ImageBatcher {await this.flushOrThrow(nowMs)}}+ // 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)+ }// A batch whose tail is all skips, or which is nothing but skips, still has to move offsets.this.recordOffsets(messages.slice(spanStart))if (this.shouldFlush(nowMs)) {@@ -312,20 +342,30 @@ export class ImageBatcher {}/**- * librdkafka refuses to store an offset for a partition this consumer no longer holds, raising- * ERR__STATE. A rebalance during a batch is ordinary, and the shard is already on S3 by this- * point, so the only thing lost is the record of how far we got: whoever picks the partition up- * rescrubs from the last committed offset, which is the at-least-once behaviour a restart has- * always had. Letting it propagate exited the process instead, and since a pod exiting triggers- * the next rebalance, the condition kept producing itself.+ * librdkafka refuses to store an offset for a partition this consumer no longer holds. A+ * rebalance during a batch is ordinary, and the shard is already on S3 by this point, so the only+ * thing lost is the record of how far we got: whoever picks the partition up rescrubs from the+ * last committed offset, which is the same at-least-once behaviour a restart produces. Letting it+ * propagate would exit the process, and a pod exiting is itself what triggers the next rebalance.+ *+ * The disconnected client throws a plain Error with no code at all, which is the same situation+ * arriving during shutdown, so it is tolerated on the same grounds.*/private storeOffsetsUnlessRevoked(offsets: TopicPartitionOffset[]): void {try {this.offsetStore.offsetsStore(offsets)} catch (error) {- if ((error as LibrdKafkaError | undefined)?.code !== ERR__STATE) {+ const code = (error as LibrdKafkaError | undefined)?.code+ if (code !== undefined && !REVOKED_PARTITION_CODES.has(code)) {throw error}+ // Logged as well as counted: the counter says how many, and a lane that is quietly+ // rescrubbing the same span every batch needs the partitions to work that out.+ logger.warn('🔁', 'image_scrub_offsets_discarded', {+ error: String(error),+ code,+ partitions: offsets.map((o) => o.partition),+ })ImageScrubConsumerMetrics.incOffsetsDiscarded(offsets.length)}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.tsindex 3bd4f5e03981..4a53b19ea150 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,5 +1,10 @@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'+export class ImageScrubConsumerMetrics {private static readonly scrubbed = new Counter({name: 'ml_mirror_image_scrub_consumer_scrubbed_total',@@ -48,12 +53,14 @@ export class ImageScrubConsumerMetrics {* The lane's data-loss signal, and the one to alert on. Every drop here is an image that reached* the consumer and will never reach the bucket, because the sidecar had no capacity for it inside* the batch's budget. A low background rate is the shape of a lane running near its ceiling; a- * rate approaching `scrubbed` means the sidecar is effectively down, which no longer announces- * itself by crash-looping the pods.+ * 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.*/private static readonly dropped = new Counter({name: 'ml_mirror_image_scrub_consumer_dropped_total',- help: 'Images dropped because the sidecar had no capacity for them (busy, timed out, or the batch scrub budget expired). Never published, so this is lost coverage rather than leaked content',+ 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)',+ labelNames: ['reason'],})private static readonly offsetsDiscarded = new Counter({name: 'ml_mirror_image_scrub_consumer_offsets_discarded_total',@@ -74,8 +81,8 @@ export class ImageScrubConsumerMetrics {public static incSkipped(): void {this.skipped.inc()}- public static incDropped(): void {- this.dropped.inc()+ public static incDropped(reason: DropReason, count = 1): void {+ this.dropped.labels(reason).inc(count)}public static incOffsetsDiscarded(count: number): void {this.offsetsDiscarded.inc(count)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.tsindex f3d2f2a72334..830f46be3792 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.ts@@ -4,20 +4,38 @@ import { promiseRetry } from '~/common/utils/retries'class PermanentScrubReject extends Error {}+/** 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.*- * Separated from every other failure because the two need opposite handling. A verdict on the image- * or a broken sidecar is worth failing the batch over; being busy is not, and treating it that way- * crash-looped the lane. The consumer's per-request timeout is an inactivity timeout, so an image- * merely sitting in the sidecar's accept queue trips it, and the retries queue behind the same jam.- * Every pod then exited on a saturated sidecar, which handed its partitions to the pods that were- * already saturating, so saturation spread instead of easing.+ * 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.*/-export class ScrubUnavailable extends Error {}+export type ScrubUnavailableReason = 'busy' | 'timeout' | 'transport' | 'aborted'-class ScrubAborted extends ScrubUnavailable {}+export class ScrubUnavailable extends Error {+ constructor(+ message: string,+ readonly reason: ScrubUnavailableReason,+ options?: ErrorOptions+ ) {+ super(message, options)+ }+}++class ScrubAborted extends ScrubUnavailable {+ constructor(message: string) {+ super(message, 'aborted')+ }+}export class ScrubClient {private readonly url: URL@@ -35,8 +53,9 @@ export class ScrubClient {** Anything else throws [[ScrubUnavailable]], and only that: every way the sidecar can fail to* return bytes is a fact about this one image plus the sidecar's current load, never a reason to- * bring the consumer down. The caller decides what to do with a single lost image; it used to- * have no choice, because the failure reached the Kafka loop, which exits the process.+ * 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.*/public async scrub(bytes: Buffer, signal?: AbortSignal): Promise<Buffer | null> {try {@@ -48,14 +67,14 @@ export class ScrubClient {const { status, body } = await this.post(bytes, signal)if (status === 200) {if (body.length === 0) {- throw new ScrubUnavailable('sidecar returned an empty 200 body')+ 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}`)+ 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.@@ -73,8 +92,13 @@ export class ScrubClient {}// A transport error: the socket was refused, reset, or destroyed by the request timeout.// Restarting the consumer cannot fix any of them, since the sidecar is a separate- // container that keeps running, so this is one lost image rather than a lost pod.- throw new ScrubUnavailable(String(error instanceof Error ? error.message : error))+ // 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,+ })}}@@ -93,7 +117,7 @@ export class ScrubClient {res.on('error', reject)})- req.setTimeout(this.timeoutMs, () => req.destroy(new Error('scrub request timed out')))+ req.setTimeout(this.timeoutMs, () => req.destroy(new Error(REQUEST_TIMED_OUT)))req.on('error', reject)if (signal) {const onAbort = (): void => {