: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(session-replay): count scrub requests in poison budget (#89192)
Robbieae7d0a72ef7f
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 b92894b8ebeb..114d53176eec 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@@ -53,7 +53,9 @@ A batch cannot finish while one of its images is in flight, and a pod cannot polRequiring 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.+When no peer is available to vouch at all, the time spent on considered rejections and their backoffs opens the gate on its own.+Request time counts because a wedged worker consumes most of the Kafka lease before each backoff starts.+Busy, timeout, and transport intervals do not consume this budget because they do not identify a bad image.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.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.tsindex 015f4568f1db..acb3bf48d36f 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@@ -786,6 +786,8 @@ describe('ImageBatcher', () => {lastError: 'sidecar responded 500',attempts: 12,waitedMs: 60_000,+ elapsedMs: 120_000,+ rejectedMs: 120_000,})): Promise.resolve(b),@@ -815,6 +817,8 @@ describe('ImageBatcher', () => {lastError: 'sidecar responded 500',attempts: 12,waitedMs: 60_000,+ elapsedMs: 120_000,+ rejectedMs: 120_000,})),} as unknown as ScrubClient@@ -844,6 +848,8 @@ describe('ImageBatcher', () => {lastError: 'sidecar responded 500',attempts: 12,waitedMs: 60_000,+ elapsedMs: 120_000,+ rejectedMs: 120_000,})),} as unknown as ScrubClient@@ -922,6 +928,8 @@ describe('ImageBatcher', () => {lastError: 'sidecar responded 500',attempts: 12,waitedMs: 60_000,+ elapsedMs: 120_000,+ rejectedMs: 120_000,})),} as unknown as ScrubClientdiff --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.tsindex b1bfbd3f23be..f645539b9229 100644--- 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@@ -1,15 +1,16 @@import { Server, createServer } from 'node:http'import { AddressInfo } from 'node:net'-import { ScrubAborted, ScrubClient, ScrubContractError, ScrubPoisoned } from './scrub-client'+import { POISON_MAX_REJECTED_MS, ScrubAborted, ScrubClient, ScrubContractError, ScrubPoisoned } from './scrub-client'-type Reply = { status: number; body?: string }+type Reply = { status: number; body?: string; durationMs?: number }describe('ScrubClient', () => {let server: Serverlet replies: Reply[]let requests: numberlet replyFor: ((body: string) => Reply | undefined) | undefined+ let nowMs: number// 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@@ -18,6 +19,7 @@ describe('ScrubClient', () => {replies = []requests = 0replyFor = undefined+ nowMs = 0server = createServer((req, res) => {requests += 1const chunks: Buffer[] = []@@ -28,6 +30,7 @@ describe('ScrubClient', () => {// "failing while others succeed" rule means anything.const reply = replyFor?.(Buffer.concat(chunks).toString()) ??replies.shift() ?? { status: 200, body: 'scrubbed' }+ nowMs += reply.durationMs ?? 0res.writeHead(reply.status).end(reply.body ?? '')})})@@ -44,8 +47,12 @@ describe('ScrubClient', () => {1000,deadLetters,// Backoff is asserted separately; sleeping for real would only make this slow and flaky.- () => Promise.resolve(),- () => 1+ (ms) => {+ nowMs += ms+ return Promise.resolve()+ },+ () => 1,+ () => nowMs)it.each([@@ -111,15 +118,26 @@ describe('ScrubClient', () => {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 () => {+ it('counts rejected request time when no peers can 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: '' }))+ replies = Array.from({ length: 5000 }, () => ({ status: 500, body: '', durationMs: 15_000 }))- await expect(client(true).scrub(Buffer.from('image'), undefined, 'ref-1')).rejects.toThrow(ScrubPoisoned)+ let poisoned: unknown+ try {+ await client(true).scrub(Buffer.from('image'), undefined, 'ref-1')+ } catch (error) {+ poisoned = error+ }++ expect(poisoned).toBeInstanceOf(ScrubPoisoned)+ const detail = (poisoned as ScrubPoisoned).detail+ expect(detail.rejectedMs).toBeGreaterThanOrEqual(POISON_MAX_REJECTED_MS)+ expect(detail.rejectedMs).toBeLessThan(POISON_MAX_REJECTED_MS + 15_000)+ expect(detail.elapsedMs).toBe(detail.rejectedMs)})/**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 45a4b9fe0ef5..6159f9241c44 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@@ -28,7 +28,14 @@ export class ScrubContractError extends Error {}export class ScrubPoisoned extends Error {constructor(message: string,- readonly detail: { reason: ScrubWaitReason; lastError: string; attempts: number; waitedMs: number }+ readonly detail: {+ reason: ScrubWaitReason+ lastError: string+ attempts: number+ waitedMs: number+ elapsedMs: number+ rejectedMs: number+ }) {super(message)}@@ -66,7 +73,7 @@ const POISON_MIN_FAILURES = 12export const POISON_MIN_OTHER_SUCCESSES = 3/**- * Accumulated backoff after which a sidecar that keeps answering is taken at its word.+ * Time spent on rejected requests and their backoffs before a sidecar 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@@ -77,14 +84,15 @@ export const POISON_MIN_OTHER_SUCCESSES = 3* 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.+ * and the images would circle the fleet. Request time counts because a wedged worker consumes most+ * of the lease before each backoff starts. Busy, timeout, and transport intervals stay outside this+ * budget because they do not blame the image.** 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+export const POISON_MAX_REJECTED_MS = 120_000const BACKOFF_BASE_MS = 100/**@@ -168,7 +176,8 @@ export class ScrubClient {// 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+ private readonly random: () => number = Math.random,+ private readonly now: () => number = () => performance.now()) {this.url = new URL('/scrub', baseUrl)}@@ -187,7 +196,9 @@ export class ScrubClient {* The caller hanging up raises [[ScrubAborted]], which belongs to shutdown rather than to load.*/public async scrub(bytes: Buffer, signal?: AbortSignal, ref?: string): Promise<Buffer | null> {+ const startedAtMs = this.now()let waitedMs = 0+ let rejectedMs = 0let stuckReports = 0let blamableFailures = 0const successesAtStart = this.successes@@ -197,6 +208,7 @@ export class ScrubClient {}let reason: ScrubWaitReasonlet detail: string+ const attemptStartedAtMs = this.now()try {const { status, body } = await this.post(bytes, signal)if (status === 200 && body.length > 0) {@@ -235,19 +247,21 @@ export class ScrubClient {// sidecar being unreachable, which is true of every image at once.if (reason === 'rejected') {blamableFailures += 1+ rejectedMs += this.now() - attemptStartedAtMs}const sidecarProvenHealthy = this.successes - successesAtStart >= POISON_MIN_OTHER_SUCCESSES- const waitedTooLong = waitedMs >= POISON_MAX_WAITED_MS+ const rejectedTooLong = reason === 'rejected' && rejectedMs >= POISON_MAX_REJECTED_MSif (this.deadLetters &&- blamableFailures >= POISON_MIN_FAILURES &&- (sidecarProvenHealthy || waitedTooLong)+ ((blamableFailures >= POISON_MIN_FAILURES && sidecarProvenHealthy) || rejectedTooLong)) {throw new ScrubPoisoned(`sidecar cannot process this image: ${detail}`, {reason,lastError: detail,attempts: attempt + 1,waitedMs,+ elapsedMs: this.now() - startedAtMs,+ rejectedMs,})}const delayMs = backoffMs(attempt, reason, this.random)@@ -266,10 +280,15 @@ export class ScrubClient {detail,attempts: attempt + 1,waitedMs,+ elapsedMs: this.now() - startedAtMs,bytes: bytes.length,})}+ const waitStartedAtMs = this.now()await this.waitOrAbort(delayMs, signal)+ if (reason === 'rejected') {+ rejectedMs += this.now() - waitStartedAtMs+ }}}