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(ai-research): retry timed-out image fetch crawl-history commands (#106117)

Robbie8b2b9a269340
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
index 34f3e0870696..6b3b76056efc 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
@@ -54,7 +54,7 @@ One source-domain record can redirect to several target registrable domains. Suc
DynamoDB stores URL outcomes and configuration entries. Reads use 100-item batches and writes use 25-item batches. Large configuration bodies use immutable generation-specific chunks that publish before their manifest.
-The client retries unprocessed keys and items with bounded concurrency and time. An incomplete chunk generation is a logged cache miss that the next configuration fetch repairs. A malformed base item fails the Kafka batch.
+The client retries unprocessed keys and items with bounded concurrency and time. It retries a batch command that reaches the command timeout in the same way, because a batch get or batch write of the same items is idempotent. An incomplete chunk generation is a logged cache miss that the next configuration fetch repairs. A malformed base item fails the Kafka batch.
For a successful fetch, the producer publishes the image before DynamoDB records completion. Kafka offsets commit only after both operations succeed.
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.test.ts
index fb6ffae7b4a7..3d027e997733 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.test.ts
@@ -41,6 +41,14 @@ function requestedWrites(
return command.input.RequestItems?.[TABLE] ?? []
}
+function hangUntilAborted(_command: unknown, { abortSignal }: { abortSignal: AbortSignal }): Promise<never> {
+ return new Promise((_resolve, reject) =>
+ abortSignal.addEventListener('abort', () =>
+ reject(Object.assign(new Error('Request aborted'), { name: 'AbortError' }))
+ )
+ )
+}
+
describe('DynamoDBCrawlHistory', () => {
it('reads each distinct key in batches of at most 100', async () => {
const send = jest.fn((command: BatchGetItemCommand) => {
@@ -260,6 +268,57 @@ describe('DynamoDBCrawlHistory', () => {
jest.useRealTimers()
})
+ it.each([
+ {
+ operation: 'read',
+ run: (history: DynamoDBCrawlHistory) => history.read(['slow']),
+ retried: { Responses: { [TABLE]: [stored(urlItem('slow'))] } },
+ requestedKeys: (command: BatchGetItemCommand | BatchWriteItemCommand) =>
+ requestedReadKeys(command as BatchGetItemCommand),
+ },
+ {
+ operation: 'write',
+ run: (history: DynamoDBCrawlHistory) => history.write([urlItem('slow')]),
+ retried: {},
+ requestedKeys: (command: BatchGetItemCommand | BatchWriteItemCommand) =>
+ requestedWrites(command as BatchWriteItemCommand).map((request) => request.PutRequest?.Item?.key?.S),
+ },
+ ])('retries a $operation command that times out', async ({ run, retried, requestedKeys }) => {
+ jest.useFakeTimers()
+ jest.spyOn(Math, 'random').mockReturnValue(0)
+ const send = jest.fn().mockImplementationOnce(hangUntilAborted).mockResolvedValueOnce(retried)
+
+ const outcome = run(build(send)).then(
+ () => 'completed',
+ (error: unknown) => String(error)
+ )
+ await jest.runAllTimersAsync()
+
+ expect(await outcome).toBe('completed')
+ expect(send).toHaveBeenCalledTimes(2)
+ expect(requestedKeys(send.mock.calls[1][0])).toEqual(['slow'])
+ jest.useRealTimers()
+ })
+
+ it.each([
+ { operation: 'read', run: (history: DynamoDBCrawlHistory) => history.read(['slow']) },
+ { operation: 'write', run: (history: DynamoDBCrawlHistory) => history.write([urlItem('slow')]) },
+ ])('fails a $operation after every attempt times out', async ({ run }) => {
+ jest.useFakeTimers()
+ jest.spyOn(Math, 'random').mockReturnValue(0)
+ const send = jest.fn(hangUntilAborted)
+
+ const outcome = run(build(send)).then(
+ () => 'completed',
+ (error: unknown) => String(error)
+ )
+ await jest.runAllTimersAsync()
+
+ expect(await outcome).toBe('Error: DynamoDB crawl-history command timed out after 1000ms')
+ expect(send).toHaveBeenCalledTimes(5)
+ jest.useRealTimers()
+ })
+
it('throws after unprocessed write retries are exhausted', async () => {
jest.useFakeTimers()
jest.spyOn(Math, 'random').mockReturnValue(0)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.ts
index adf728c809b1..109112ab2232 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.ts
@@ -44,6 +44,8 @@ interface ItemWritePlan {
export type DynamoDBCrawlHistoryClient = Pick<DynamoDBClient, 'send'>
+class CommandTimeoutError extends Error {}
+
function chunk<T>(items: T[], size: number): T[][] {
const chunks: T[][] = []
for (let index = 0; index < items.length; index += size) {
@@ -325,21 +327,27 @@ export class DynamoDBCrawlHistory implements CrawlHistoryStore {
let pending = batch
for (let attempt = 1; pending.length > 0; attempt++) {
this.requireBudget(startedAt)
- const response = await this.sendBatchGet(
- new BatchGetItemCommand({
- RequestItems: {
- [this.tableName]: {
- Keys: pending.map((key) => ({ [KEY_ATTRIBUTE]: { S: key } })),
- ProjectionExpression: '#key, #expiresAt, #value',
- ExpressionAttributeNames: {
- '#key': KEY_ATTRIBUTE,
- '#expiresAt': EXPIRES_AT_ATTRIBUTE,
- '#value': VALUE_ATTRIBUTE,
+ let response: BatchGetItemCommandOutput
+ try {
+ response = await this.sendBatchGet(
+ new BatchGetItemCommand({
+ RequestItems: {
+ [this.tableName]: {
+ Keys: pending.map((key) => ({ [KEY_ATTRIBUTE]: { S: key } })),
+ ProjectionExpression: '#key, #expiresAt, #value',
+ ExpressionAttributeNames: {
+ '#key': KEY_ATTRIBUTE,
+ '#expiresAt': EXPIRES_AT_ATTRIBUTE,
+ '#value': VALUE_ATTRIBUTE,
+ },
},
},
- },
- })
- )
+ })
+ )
+ } catch (error) {
+ await this.backoffAfterCommandTimeout(error, attempt)
+ continue
+ }
for (const item of response.Responses?.[this.tableName] ?? []) {
result.push(item)
}
@@ -376,9 +384,15 @@ export class DynamoDBCrawlHistory implements CrawlHistoryStore {
let pending = batch
for (let attempt = 1; pending.length > 0; attempt++) {
this.requireBudget(startedAt)
- const response = await this.sendBatchWrite(
- new BatchWriteItemCommand({ RequestItems: { [this.tableName]: pending } })
- )
+ let response: BatchWriteItemCommandOutput
+ try {
+ response = await this.sendBatchWrite(
+ new BatchWriteItemCommand({ RequestItems: { [this.tableName]: pending } })
+ )
+ } catch (error) {
+ await this.backoffAfterCommandTimeout(error, attempt)
+ continue
+ }
pending = response.UnprocessedItems?.[this.tableName] ?? []
if (pending.length > 0) {
if (attempt >= UNPROCESSED_MAX_ATTEMPTS) {
@@ -407,6 +421,14 @@ export class DynamoDBCrawlHistory implements CrawlHistoryStore {
}
}
+ /** A batch get or batch write of the same items is idempotent, so a timed-out command is retried like unprocessed items; any other failure, or a timeout on the last attempt, is rethrown. */
+ private async backoffAfterCommandTimeout(error: unknown, attempt: number): Promise<void> {
+ if (!(error instanceof CommandTimeoutError) || attempt >= UNPROCESSED_MAX_ATTEMPTS) {
+ throw error
+ }
+ await this.backoffBeforeRetry(attempt)
+ }
+
private async backoffBeforeRetry(attempt: number): Promise<void> {
const maximumDelayMs = UNPROCESSED_INITIAL_BACKOFF_MS * 2 ** (attempt - 1)
const delayMs = Math.floor(maximumDelayMs / 2 + Math.random() * (maximumDelayMs / 2))
@@ -427,6 +449,16 @@ export class DynamoDBCrawlHistory implements CrawlHistoryStore {
timer.unref()
try {
return await send(abortController.signal)
+ } catch (error) {
+ if (abortController.signal.aborted) {
+ throw new CommandTimeoutError(
+ `DynamoDB crawl-history command timed out after ${this.commandTimeoutMs}ms`,
+ {
+ cause: error,
+ }
+ )
+ }
+ throw error
} finally {
clearTimeout(timer)
}