: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(ai-research): retry transient s3 failures in the image-scrub lane (#97341)
Robbie6f60328a1dee
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.tsindex b81f194d7a87..1d57d6e31c12 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.ts@@ -11,18 +11,65 @@ describe('ImageShardStore', () => {sourceOffset: 9,}- it('aborts a shard write that exceeds the timeout so the flush throws and replays', async () => {- const s3 = {- send: (_cmd: unknown, opts: { abortSignal: AbortSignal }) =>+ const s3Failure = (status?: number) =>+ Object.assign(+ new Error('s3 rejected the write'),+ status === undefined ? {} : { $metadata: { httpStatusCode: status } }+ )+ const noSleep = () => Promise.resolve()++ it('retries a shard write that exceeds the timeout, then gives up so the flush replays', async () => {+ const send = jest.fn(+ (_cmd: unknown, opts: { abortSignal: AbortSignal }) =>new Promise((_resolve, reject) => {opts.abortSignal.addEventListener('abort', () => reject(new Error('aborted')))- }),- } as unknown as S3Client- const store = new ImageShardStore(s3, 'bucket', 'prefix', 5)+ })+ )+ const store = new ImageShardStore({ send } as unknown as S3Client, 'bucket', 'prefix', 5, 'node', noSleep)- await expect(store.writeShard([inlineImage])).rejects.toThrow()+ await expect(store.writeShard([inlineImage])).rejects.toThrow('aborted')++ expect(send).toHaveBeenCalledTimes(3)})+ it.each([[500], [502], [503], [429], [undefined]])(+ 'retries a shard write rejected with status %s, so one bad response does not restart the consumer',+ async (status) => {+ const send = jest.fn().mockRejectedValueOnce(s3Failure(status)).mockResolvedValue({})+ const store = new ImageShardStore(+ { send } as unknown as S3Client,+ 'bucket',+ 'prefix',+ 1_000,+ 'node',+ noSleep+ )++ await expect(store.writeShard([inlineImage])).resolves.toMatchObject({ bytes: 3 })++ expect(send).toHaveBeenCalledTimes(3)+ }+ )++ it.each([[400], [403], [404]])(+ 'fails a shard write rejected with status %s without retrying, so a refusal does not spend the poll budget',+ async (status) => {+ const send = jest.fn().mockRejectedValue(s3Failure(status))+ const store = new ImageShardStore(+ { send } as unknown as S3Client,+ 'bucket',+ 'prefix',+ 1_000,+ 'node',+ noSleep+ )++ await expect(store.writeShard([inlineImage])).rejects.toThrow('s3 rejected the write')++ expect(send).toHaveBeenCalledTimes(1)+ }+ )+it('deletes the orphaned shard when the index write fails', async () => {const deleted: string[] = []const s3 = {@@ -32,7 +79,9 @@ describe('ImageShardStore', () => {return Promise.resolve()}return command.input.Key?.endsWith('.parquet')- ? Promise.reject(new Error('index write failed'))+ ? Promise.reject(+ Object.assign(new Error('index write failed'), { $metadata: { httpStatusCode: 403 } })+ ): Promise.resolve()},} as unknown as S3Clientdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.tsindex 80fe323c7e39..d6e4484627fa 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.ts@@ -2,6 +2,7 @@ import { DeleteObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/clientimport { ParquetSchema } from '@dsnp/parquetjs'import { randomUUID } from 'node:crypto'+import { logger } from '~/common/utils/logger'import { parquetRecordsToBuffer } from '~/ingestion/pipelines/sessionreplay/shared/parquet'export interface ScrubbedImage {@@ -31,6 +32,17 @@ const INDEX_FORMAT_VERSION = 1const URL_SOURCE_PARTITION_METADATA = 'source-partition'const URL_SOURCE_OFFSET_METADATA = 'source-offset'const URL_WRITE_MAX_ATTEMPTS = 8+const S3_WRITE_MAX_ATTEMPTS = 3+/**+ * A ceiling on the time one object may spend in retries.+ *+ * Each attempt is already capped by writeTimeoutMs, so repeated timeouts across both objects of a+ * shard write would otherwise approach the 300 second max.poll.interval.ms that governs the whole+ * batch. The budget ends the retries before a slow flush can cost the pod its partitions.+ */+const S3_WRITE_RETRY_BUDGET_MS = 45_000+const S3_WRITE_RETRY_BASE_MS = 100+const S3_WRITE_RETRY_MAX_BACKOFF_MS = 2_000const INDEX_SCHEMA = new ParquetSchema({format_version: { type: 'INT64', compression: 'SNAPPY' },@@ -64,19 +76,60 @@ export class ImageShardStore {private readonly bucket: string,private readonly prefix: string,private readonly writeTimeoutMs: number,- nodeId?: string+ nodeId?: string,+ // unref'd, so a backoff that is still pending cannot hold the event loop open through shutdown.+ private readonly sleep: (ms: number) => Promise<void> = (ms) =>+ new Promise((resolve) => setTimeout(resolve, ms).unref())) {this.nodeId = nodeId || process.env.HOSTNAME || randomUUID().slice(0, 8)}- // S3 client has no request timeout; a hung write would stall the poll loop past Kafka's max.poll.interval.ms and evict us.+ /**+ * One S3 request, bounded by a timeout and repeated while the failure could still clear.+ *+ * The S3 client has no request timeout of its own, so a hung write would stall the poll loop+ * past Kafka's max.poll.interval.ms and evict the pod. The timeout aborts the request instead,+ * and the abort is retriable because it says nothing about whether S3 would accept the object.+ *+ * Every key this class writes is either unique to one call or created under IfNoneMatch, so a+ * repeated request writes the same bytes to the same key, or reports the conflict that+ * writeUrlImage already reads as a result. Retrying is therefore safe for all three commands.+ */private async send(command: PutObjectCommand | DeleteObjectCommand): Promise<void> {- const controller = new AbortController()- const timer = setTimeout(() => controller.abort(), this.writeTimeoutMs)- try {- await this.s3.send(command, { abortSignal: controller.signal })- } finally {- clearTimeout(timer)+ const startedAtMs = performance.now()+ for (let attempt = 1; ; attempt++) {+ const controller = new AbortController()+ let timedOut = false+ let failure: unknown+ const timer = setTimeout(() => {+ timedOut = true+ controller.abort()+ }, this.writeTimeoutMs)+ try {+ await this.s3.send(command, { abortSignal: controller.signal })+ return+ } catch (error) {+ failure = error+ } finally {+ clearTimeout(timer)+ }+ if (+ attempt >= S3_WRITE_MAX_ATTEMPTS ||+ performance.now() - startedAtMs >= S3_WRITE_RETRY_BUDGET_MS ||+ !(timedOut || isTransientS3Failure(failure))+ ) {+ throw failure+ }+ // The status is the one thing the shutdown path cannot report, and it is what separates+ // an overloaded bucket from a request S3 refused.+ logger.warn('🔁', 'image_scrub_s3_write_retry', {+ key: command.input.Key,+ attempt,+ timedOut,+ status: s3HttpStatus(failure),+ errorName: s3ErrorName(failure),+ })+ await this.sleep(retryBackoffMs(attempt))}}@@ -183,3 +236,24 @@ function isPreconditionFailed(error: unknown): boolean {function isConditionalRequestConflict(error: unknown): boolean {return s3HttpStatus(error) === 409 || s3ErrorName(error) === 'ConditionalRequestConflict'}++/**+ * Whether repeating the request could produce a different answer.+ *+ * A 5xx or a 429 is S3 declining to serve the request now. An error that carries no HTTP status+ * never reached a response at all, which covers a dropped socket, a DNS failure, and an error body+ * the SDK could not match to a known shape. The two conditional outcomes are excluded because+ * writeUrlImage reads them as results rather than as failures.+ */+function isTransientS3Failure(error: unknown): boolean {+ if (isPreconditionFailed(error) || isConditionalRequestConflict(error)) {+ return false+ }+ const status = s3HttpStatus(error)+ return status === undefined || status >= 500 || status === 429+}++/** Full jitter, so the pods that one S3 slowdown hits together do not retry in lockstep. */+function retryBackoffMs(attempt: number): number {+ return Math.round(Math.random() * Math.min(S3_WRITE_RETRY_MAX_BACKOFF_MS, S3_WRITE_RETRY_BASE_MS * 2 ** attempt))+}