: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
feat(ai-research): add DynamoDB crawl history backend (#85870)
Robbief065313dc2d4
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.mdindex 54f8fc0eb3eb..246d784c16a4 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md@@ -15,7 +15,7 @@ code is written against. Where the code and this file disagree, one of them is a| Frontier | The topic `session_replay_image_fetch`. It holds the URLs waiting to be fetched. || Back queue | The URLs of one registrable domain. The topic key is the domain, so a partition holds whole back queues. || Pass | The fetching for one Kafka poll batch. Every back queue in the batch runs at the same time, and wall time bounds the pass rather than work. |-| Crawl history | The Redis record of the URLs this lane has finished with, whatever the outcome. It answers the URL-seen test. |+| Crawl history | The shared record of URLs this lane has finished with, whatever the outcome. A table setting selects DynamoDB; otherwise the lane uses Redis. || Host budget | The token bucket, connection limit, and circuit breaker for one registrable domain. The rate moves by AIMD: a failure halves it, and success raises it slowly. || Hop | One trip a URL makes back through Kafka. The lane spends a hop when it puts a URL back: a retry, a redirect that left the domain, or a URL that arrived before its wait ended. A redirect the lane follows in place costs no hop. || Hop budget | The number of hops one URL may make before the lane gives up. |@@ -25,6 +25,12 @@ A redirect to another domain is a new candidate URL. It goes back through the frbeing fetched in place, because the budget that governs it belongs to whichever consumer owns thatdomain's partition.+The lane reads the crawl history after parsing and in-batch deduplication. It makes fetch decisions+from the result, then writes completed URLs at the end of the Kafka batch. The DynamoDB backend uses+batch operations with service limits of 100 reads and 25 writes. An expired row counts as absent+before DynamoDB removes it. Before Kafka consumption starts, the lane writes and consistently reads+a short-lived probe record so that a missing table or IAM permission stops the pod.+## Limits| Constant | Scope | Value |diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.tsindex 1500bbfc0841..82932d05111d 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts@@ -9,8 +9,8 @@ const MAX_URL_LENGTH = 2048/*** A record holds one domain from one message, and the collector caps a message at 512, so a- * well-formed record stays under this. The headroom is small on purpose, because the Redis round- * trips of a batch scale with this value and run one after another inside one batch budget.+ * well-formed record stays under this. The headroom is small on purpose, because crawl-history+ * request fan-out and the in-memory candidate set both scale with this value.*/const MAX_URLS_PER_RECORD = 640diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history.test.tsindex 5832caf22d34..39b145e10aa9 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history.test.ts@@ -2,6 +2,7 @@ import { CrawlHistory, CrawlHistoryRedis, CrawlHistoryRedisPool } from './crawl-/** Above one round trip's key limit, so every test crosses a chunk boundary. */const KEYS = Array.from({ length: 600 }, (_value, index) => `k${index}`)+const NOW_MS = 1_700_000_000_000type ExecResult = [Error | null, unknown][] | null@@ -51,7 +52,7 @@ describe('CrawlHistory', () => {const present = new Set(['k0', 'k255', 'k256', 'k599'])const client = new FakeClient({ mget: (keys) => keys.map((key) => (present.has(key) ? '{}' : null)) })- const result = await build(client).read(KEYS)+ const result = await build(client).read(KEYS, NOW_MS)expect([...result.known].sort((a, b) => a - b)).toEqual([0, 255, 256, 599])expect(result.failed.size).toBe(0)@@ -67,7 +68,7 @@ describe('CrawlHistory', () => {},})- const result = await build(client).read(KEYS)+ const result = await build(client).read(KEYS, NOW_MS)// The caller drops these rather than fetches them, so it needs which keys, not how many.expect(result.failed.size).toBe(256)@@ -104,7 +105,7 @@ describe('CrawlHistory', () => {},})- const result = await build(client, 30).read(KEYS)+ const result = await build(client, 30).read(KEYS, NOW_MS)expect(result.failed.size).toBeGreaterThan(0)})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history.tsindex cac19004df0a..354f795c1b1f 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history.ts@@ -49,7 +49,7 @@ export type CrawlHistoryRedisPool = Pick<Pool<CrawlHistoryRedis>, 'acquire' | 'r/** What the consumer needs of the store, so its tests exercise the real contract rather than a cast. */export interface CrawlHistoryStore {- read(keys: string[]): Promise<CrawlHistoryReadResult>+ read(keys: string[], nowMs: number): Promise<CrawlHistoryReadResult>record(keys: string[], nowMs: number, ttlSeconds: number): Promise<{ failed: Set<number> }>}@@ -70,7 +70,7 @@ export class CrawlHistory implements CrawlHistoryStore {private readonly batchBudgetMs: number) {}- public async read(keys: string[]): Promise<CrawlHistoryReadResult> {+ public async read(keys: string[], _nowMs: number): Promise<CrawlHistoryReadResult> {const known = new Set<number>()const failed = new Set<number>()await this.forEachChunk(keys, {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.integration.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.integration.test.tsnew file mode 100644index 000000000000..01114f268cc0--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.integration.test.ts@@ -0,0 +1,58 @@+import {+ CreateTableCommand,+ DeleteTableCommand,+ DynamoDBClient,+ GetItemCommand,+ waitUntilTableExists,+} from '@aws-sdk/client-dynamodb'++import { DynamoDBCrawlHistory } from './dynamodb-crawl-history'++const DYNAMODB_ENDPOINT = 'http://127.0.0.1:18010'+const TABLE_NAME = `ai-research-image-fetch-crawl-history-test-${process.pid}-${Date.now()}`+const NOW_MS = 1_700_000_000_000+const NOW_SECONDS = Math.floor(NOW_MS / 1000)+const TTL_SECONDS = 30 * 24 * 60 * 60+const KEYS = Array.from({ length: 205 }, (_value, index) => `key-${index}`)++describe('DynamoDBCrawlHistory integration', () => {+ const client = new DynamoDBClient({+ endpoint: DYNAMODB_ENDPOINT,+ region: 'us-east-1',+ credentials: { accessKeyId: 'test', secretAccessKey: 'test' },+ maxAttempts: 1,+ })++ beforeAll(async () => {+ await client.send(+ new CreateTableCommand({+ TableName: TABLE_NAME,+ AttributeDefinitions: [{ AttributeName: 'key', AttributeType: 'S' }],+ KeySchema: [{ AttributeName: 'key', KeyType: 'HASH' }],+ BillingMode: 'PAY_PER_REQUEST',+ })+ )+ await waitUntilTableExists({ client, maxWaitTime: 10, minDelay: 1 }, { TableName: TABLE_NAME })+ })++ afterAll(async () => {+ await client.send(new DeleteTableCommand({ TableName: TABLE_NAME }))+ client.destroy()+ })++ it('records and reads a full ingestion batch through DynamoDB', async () => {+ const crawlHistory = new DynamoDBCrawlHistory(client, TABLE_NAME, 5_000, 30_000)++ await crawlHistory.validateAccess(NOW_MS)+ const writeResult = await crawlHistory.record(KEYS, NOW_MS, TTL_SECONDS)+ const readResult = await crawlHistory.read([...KEYS, 'missing'], NOW_MS)+ const storedItem = await client.send(+ new GetItemCommand({ TableName: TABLE_NAME, Key: { key: { S: KEYS[0] } }, ConsistentRead: true })+ )++ expect(writeResult.failed).toEqual(new Set())+ expect(readResult.failed).toEqual(new Set())+ expect(readResult.known).toEqual(new Set(KEYS.map((_key, index) => index)))+ expect(storedItem.Item?.expires_at?.N).toBe(String(NOW_SECONDS + TTL_SECONDS))+ })+})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.tsnew file mode 100644index 000000000000..3ac453d2a366--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.test.ts@@ -0,0 +1,211 @@+import { BatchGetItemCommand, BatchWriteItemCommand } from '@aws-sdk/client-dynamodb'++import { DynamoDBCrawlHistory, DynamoDBCrawlHistoryClient } from './dynamodb-crawl-history'++const TABLE = 'ai-research-image-fetch-crawl-history'+const NOW_MS = 1_700_000_000_000+const NOW_SECONDS = Math.floor(NOW_MS / 1000)+const KEYS = Array.from({ length: 205 }, (_value, index) => `k${index}`)++function dynamoClient(send: jest.Mock): DynamoDBCrawlHistoryClient {+ return { send }+}++function requestedReadKeys(command: BatchGetItemCommand): string[] {+ return (command.input.RequestItems?.[TABLE].Keys ?? []).flatMap((key) => (key.key?.S ? [key.key.S] : []))+}++function requestedWriteKeys(command: BatchWriteItemCommand): string[] {+ return (command.input.RequestItems?.[TABLE] ?? []).flatMap((request) =>+ request.PutRequest?.Item?.key?.S ? [request.PutRequest.Item.key.S] : []+ )+}++describe('DynamoDBCrawlHistory', () => {+ const build = (send: jest.Mock): DynamoDBCrawlHistory =>+ new DynamoDBCrawlHistory(dynamoClient(send), TABLE, 1_000, 60_000)++ it('validates batch write and consistent read access', async () => {+ const send = jest.fn((command: BatchGetItemCommand | BatchWriteItemCommand) =>+ command instanceof BatchWriteItemCommand+ ? Promise.resolve({})+ : Promise.resolve({ Responses: { [TABLE]: [{ key: { S: 'imgfetch:access-probe' } }] } })+ )++ await build(send).validateAccess(NOW_MS)++ expect(send).toHaveBeenCalledTimes(2)+ expect(send.mock.calls[0][0]).toBeInstanceOf(BatchWriteItemCommand)+ const readCommand = send.mock.calls[1][0] as BatchGetItemCommand+ expect(readCommand).toBeInstanceOf(BatchGetItemCommand)+ expect(readCommand.input.RequestItems?.[TABLE].ConsistentRead).toBe(true)+ })++ it.each([+ {+ name: 'an unprocessed write',+ responses: [+ {+ UnprocessedItems: {+ [TABLE]: [{ PutRequest: { Item: { key: { S: 'imgfetch:access-probe' } } } }],+ },+ },+ ],+ },+ {+ name: 'an unprocessed read',+ responses: [{}, { UnprocessedKeys: { [TABLE]: { Keys: [{ key: { S: 'imgfetch:access-probe' } }] } } }],+ },+ {+ name: 'a missing probe record',+ responses: [{}, { Responses: { [TABLE]: [] } }],+ },+ ])('rejects $name during access validation', async ({ responses }) => {+ const send = jest.fn()+ responses.forEach((response) => send.mockResolvedValueOnce(response))++ await expect(build(send).validateAccess(NOW_MS)).rejects.toThrow('access probe')+ })++ it('reads the whole candidate set with DynamoDB batch operations', async () => {+ const active = new Set(['k0', 'k99', 'k100', 'k204'])+ const send = jest.fn((command: BatchGetItemCommand) => {+ const items = requestedReadKeys(command)+ .filter((key) => active.has(key) || key === 'k1')+ .map((key) => ({+ key: { S: key },+ expires_at: { N: String(key === 'k1' ? NOW_SECONDS : NOW_SECONDS + 1) },+ }))+ return Promise.resolve({ Responses: { [TABLE]: items } })+ })++ const result = await build(send).read(KEYS, NOW_MS)++ expect([...result.known].sort((left, right) => left - right)).toEqual([0, 99, 100, 204])+ expect(result.failed.size).toBe(0)+ const commands = send.mock.calls.map(([command]) => command as BatchGetItemCommand)+ expect(commands).toHaveLength(3)+ expect(commands.every((command) => requestedReadKeys(command).length <= 100)).toBe(true)+ })++ it('runs read batches with bounded concurrency', async () => {+ const manyKeys = Array.from({ length: 1_601 }, (_value, index) => `key-${index}`)+ let holdInitialRequests = true+ const releaseInitialRequests: Array<() => void> = []+ const send = jest.fn(() => {+ if (!holdInitialRequests) {+ return Promise.resolve({ Responses: { [TABLE]: [] } })+ }+ return new Promise((resolve) => releaseInitialRequests.push(() => resolve({ Responses: { [TABLE]: [] } })))+ })++ const readPromise = build(send).read(manyKeys, NOW_MS)+ await Promise.resolve()++ expect(send.mock.calls.length).toBeGreaterThan(1)+ expect(send.mock.calls.length).toBeLessThan(Math.ceil(manyKeys.length / 100))++ holdInitialRequests = false+ releaseInitialRequests.forEach((release) => release())+ await readPromise++ expect(send).toHaveBeenCalledTimes(Math.ceil(manyKeys.length / 100))+ })++ it('treats expired rows as absent before DynamoDB deletes them', async () => {+ const send = jest.fn(() =>+ Promise.resolve({+ Responses: {+ [TABLE]: [{ key: { S: 'expired' }, expires_at: { N: String(NOW_SECONDS - 1) } }],+ },+ })+ )++ const result = await build(send).read(['expired'], NOW_MS)++ expect(result.known.size).toBe(0)+ expect(result.failed.size).toBe(0)+ })++ it('reports only the keys whose batched read failed', async () => {+ const send = jest.fn((command: BatchGetItemCommand) => {+ const requested = requestedReadKeys(command)+ return requested.includes('k100')+ ? Promise.reject(new Error('dynamodb unavailable'))+ : Promise.resolve({ Responses: { [TABLE]: [] } })+ })++ const result = await build(send).read(KEYS, NOW_MS)++ expect(result.failed.size).toBe(100)+ expect(result.failed.has(100)).toBe(true)+ expect(result.failed.has(99)).toBe(false)+ })++ it('retries unprocessed read keys as a batch', async () => {+ const send = jest+ .fn()+ .mockResolvedValueOnce({+ UnprocessedKeys: { [TABLE]: { Keys: [{ key: { S: 'retry' } }] } },+ })+ .mockResolvedValueOnce({+ Responses: {+ [TABLE]: [{ key: { S: 'retry' }, expires_at: { N: String(NOW_SECONDS + 1) } }],+ },+ })++ const result = await build(send).read(['retry'], NOW_MS)++ expect(result.known).toEqual(new Set([0]))+ expect(result.failed.size).toBe(0)+ expect(send).toHaveBeenCalledTimes(2)+ })++ it.each([+ {+ name: 'read',+ response: { UnprocessedKeys: { [TABLE]: { Keys: [{ key: { S: 'retry' } }] } } },+ run: (crawlHistory: DynamoDBCrawlHistory) => crawlHistory.read(['retry'], NOW_MS),+ },+ {+ name: 'write',+ response: {+ UnprocessedItems: {+ [TABLE]: [{ PutRequest: { Item: { key: { S: 'retry' } } } }],+ },+ },+ run: (crawlHistory: DynamoDBCrawlHistory) => crawlHistory.record(['retry'], NOW_MS, 60),+ },+ ])('reports a failed key when unprocessed $name retries are exhausted', async ({ response, run }) => {+ jest.useFakeTimers()+ try {+ const send = jest.fn().mockResolvedValue(response)+ const resultPromise = run(build(send))++ await jest.runAllTimersAsync()+ const result = await resultPromise++ expect(result.failed).toEqual(new Set([0]))+ expect(send).toHaveBeenCalledTimes(5)+ } finally {+ jest.useRealTimers()+ }+ })++ it('flushes every new row with bounded batch writes and one expiry', async () => {+ const send = jest.fn((_command: BatchWriteItemCommand) => Promise.resolve({}))++ const result = await build(send).record(KEYS, NOW_MS, 30 * 24 * 60 * 60)++ expect(result.failed.size).toBe(0)+ const commands = send.mock.calls.map(([command]) => command as BatchWriteItemCommand)+ expect(commands).toHaveLength(9)+ expect(commands.every((command) => requestedWriteKeys(command).length <= 25)).toBe(true)+ expect(commands.flatMap(requestedWriteKeys).sort()).toEqual([...KEYS].sort())+ for (const command of commands) {+ for (const request of command.input.RequestItems?.[TABLE] ?? []) {+ expect(request.PutRequest?.Item?.expires_at?.N).toBe(String(NOW_SECONDS + 30 * 24 * 60 * 60))+ }+ }+ })+})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.tsnew file mode 100644index 000000000000..3d716a540577--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.ts@@ -0,0 +1,266 @@+import {+ BatchGetItemCommand,+ BatchGetItemCommandOutput,+ BatchWriteItemCommand,+ BatchWriteItemCommandOutput,+ DynamoDBClient,+ WriteRequest,+} from '@aws-sdk/client-dynamodb'++import { CrawlHistoryReadResult, CrawlHistoryStore } from './crawl-history'++const KEY_ATTRIBUTE = 'key'+const EXPIRES_AT_ATTRIBUTE = 'expires_at'+const BATCH_GET_SIZE = 100+const BATCH_WRITE_SIZE = 25+const MAX_CONCURRENT_BATCH_REQUESTS = 8+const UNPROCESSED_MAX_ATTEMPTS = 5+const UNPROCESSED_INITIAL_BACKOFF_MS = 50+const ACCESS_PROBE_KEY = 'imgfetch:access-probe'+const ACCESS_PROBE_TTL_SECONDS = 5 * 60++export type DynamoDBCrawlHistoryClient = Pick<DynamoDBClient, 'send'>++function chunk<T>(items: T[], size: number): T[][] {+ const chunks: T[][] = []+ for (let index = 0; index < items.length; index += size) {+ chunks.push(items.slice(index, index + size))+ }+ return chunks+}++function indexKeys(keys: string[]): Map<string, number[]> {+ const indexesByKey = new Map<string, number[]>()+ keys.forEach((key, index) => {+ const indexes = indexesByKey.get(key) ?? []+ indexes.push(index)+ indexesByKey.set(key, indexes)+ })+ return indexesByKey+}++function addIndexes(target: Set<number>, keys: string[], indexesByKey: Map<string, number[]>): void {+ for (const key of keys) {+ for (const index of indexesByKey.get(key) ?? []) {+ target.add(index)+ }+ }+}++function keysFromWriteRequests(requests: WriteRequest[]): string[] {+ return requests.flatMap((request) => {+ const key = request.PutRequest?.Item?.[KEY_ATTRIBUTE]?.S+ return key ? [key] : []+ })+}++export class DynamoDBCrawlHistory implements CrawlHistoryStore {+ constructor(+ private readonly client: DynamoDBCrawlHistoryClient,+ private readonly tableName: string,+ private readonly commandTimeoutMs: number,+ private readonly batchBudgetMs: number+ ) {}++ public async validateAccess(nowMs: number): Promise<void> {+ const expiresAt = Math.floor(nowMs / 1000) + ACCESS_PROBE_TTL_SECONDS+ const writeResponse = await this.sendBatchWrite(+ new BatchWriteItemCommand({+ RequestItems: {+ [this.tableName]: [+ {+ PutRequest: {+ Item: {+ [KEY_ATTRIBUTE]: { S: ACCESS_PROBE_KEY },+ [EXPIRES_AT_ATTRIBUTE]: { N: String(expiresAt) },+ },+ },+ },+ ],+ },+ })+ )+ if ((writeResponse.UnprocessedItems?.[this.tableName] ?? []).length > 0) {+ throw new Error('DynamoDB crawl-history access probe write was not processed')+ }++ const readResponse = await this.sendBatchGet(+ new BatchGetItemCommand({+ RequestItems: {+ [this.tableName]: {+ Keys: [{ [KEY_ATTRIBUTE]: { S: ACCESS_PROBE_KEY } }],+ ProjectionExpression: '#key',+ ExpressionAttributeNames: { '#key': KEY_ATTRIBUTE },+ ConsistentRead: true,+ },+ },+ })+ )+ const readWasUnprocessed = (readResponse.UnprocessedKeys?.[this.tableName]?.Keys ?? []).length > 0+ const probeWasRead = (readResponse.Responses?.[this.tableName] ?? []).some(+ (item) => item[KEY_ATTRIBUTE]?.S === ACCESS_PROBE_KEY+ )+ if (readWasUnprocessed || !probeWasRead) {+ throw new Error('DynamoDB crawl-history access probe read was not processed')+ }+ }++ public async read(keys: string[], nowMs: number): Promise<CrawlHistoryReadResult> {+ const known = new Set<number>()+ const failed = new Set<number>()+ const indexesByKey = indexKeys(keys)+ const uniqueKeys = [...indexesByKey.keys()]+ const startedAt = process.hrtime.bigint()+ const nowSeconds = Math.floor(nowMs / 1000)++ await this.runChunks(chunk(uniqueKeys, BATCH_GET_SIZE), async (batch) => {+ let pending = batch+ for (let attempt = 1; attempt <= UNPROCESSED_MAX_ATTEMPTS; attempt++) {+ if (this.batchBudgetSpent(startedAt)) {+ addIndexes(failed, pending, indexesByKey)+ return+ }++ let response: BatchGetItemCommandOutput+ try {+ response = await this.sendBatchGet(+ new BatchGetItemCommand({+ RequestItems: {+ [this.tableName]: {+ Keys: pending.map((key) => ({ [KEY_ATTRIBUTE]: { S: key } })),+ ProjectionExpression: '#key, #expiresAt',+ ExpressionAttributeNames: {+ '#key': KEY_ATTRIBUTE,+ '#expiresAt': EXPIRES_AT_ATTRIBUTE,+ },+ },+ },+ })+ )+ } catch {+ addIndexes(failed, pending, indexesByKey)+ return+ }++ for (const item of response.Responses?.[this.tableName] ?? []) {+ const key = item[KEY_ATTRIBUTE]?.S+ const expiresAt = Number(item[EXPIRES_AT_ATTRIBUTE]?.N)+ if (!key || !Number.isFinite(expiresAt)) {+ if (key) {+ addIndexes(failed, [key], indexesByKey)+ }+ continue+ }+ if (expiresAt > nowSeconds) {+ addIndexes(known, [key], indexesByKey)+ }+ }++ pending = (response.UnprocessedKeys?.[this.tableName]?.Keys ?? []).flatMap((key) => {+ const value = key[KEY_ATTRIBUTE]?.S+ return value ? [value] : []+ })+ if (pending.length === 0) {+ return+ }+ if (attempt === UNPROCESSED_MAX_ATTEMPTS) {+ addIndexes(failed, pending, indexesByKey)+ return+ }+ await this.backoffBeforeRetry(attempt)+ }+ })++ return { known, failed }+ }++ public async record(keys: string[], nowMs: number, ttlSeconds: number): Promise<{ failed: Set<number> }> {+ const failed = new Set<number>()+ const indexesByKey = indexKeys(keys)+ const expiresAt = Math.floor(nowMs / 1000) + ttlSeconds+ const requests = [...indexesByKey.keys()].map(+ (key): WriteRequest => ({+ PutRequest: {+ Item: {+ [KEY_ATTRIBUTE]: { S: key },+ [EXPIRES_AT_ATTRIBUTE]: { N: String(expiresAt) },+ },+ },+ })+ )+ const startedAt = process.hrtime.bigint()++ await this.runChunks(chunk(requests, BATCH_WRITE_SIZE), async (batch) => {+ let pending = batch+ for (let attempt = 1; attempt <= UNPROCESSED_MAX_ATTEMPTS; attempt++) {+ if (this.batchBudgetSpent(startedAt)) {+ addIndexes(failed, keysFromWriteRequests(pending), indexesByKey)+ return+ }++ let response: BatchWriteItemCommandOutput+ try {+ response = await this.sendBatchWrite(+ new BatchWriteItemCommand({ RequestItems: { [this.tableName]: pending } })+ )+ } catch {+ addIndexes(failed, keysFromWriteRequests(pending), indexesByKey)+ return+ }++ pending = response.UnprocessedItems?.[this.tableName] ?? []+ if (pending.length === 0) {+ return+ }+ if (attempt === UNPROCESSED_MAX_ATTEMPTS) {+ addIndexes(failed, keysFromWriteRequests(pending), indexesByKey)+ return+ }+ await this.backoffBeforeRetry(attempt)+ }+ })++ return { failed }+ }++ private async runChunks<T>(chunks: T[][], run: (batch: T[]) => Promise<void>): Promise<void> {+ let nextChunk = 0+ const worker = async (): Promise<void> => {+ while (nextChunk < chunks.length) {+ const batch = chunks[nextChunk++]+ await run(batch)+ }+ }+ const workerCount = Math.min(chunks.length, MAX_CONCURRENT_BATCH_REQUESTS)+ await Promise.all(Array.from({ length: workerCount }, worker))+ }++ private batchBudgetSpent(startedAt: bigint): boolean {+ return Number(process.hrtime.bigint() - startedAt) / 1e6 > this.batchBudgetMs+ }++ 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))+ await new Promise<void>((resolve) => setTimeout(resolve, delayMs))+ }++ private sendBatchGet(command: BatchGetItemCommand): Promise<BatchGetItemCommandOutput> {+ return this.withTimeout((abortSignal) => this.client.send(command, { abortSignal }))+ }++ private sendBatchWrite(command: BatchWriteItemCommand): Promise<BatchWriteItemCommandOutput> {+ return this.withTimeout((abortSignal) => this.client.send(command, { abortSignal }))+ }++ private async withTimeout<T>(send: (abortSignal: AbortSignal) => Promise<T>): Promise<T> {+ const abortController = new AbortController()+ const timer = setTimeout(() => abortController.abort(), this.commandTimeoutMs)+ timer.unref()+ try {+ return await send(abortController.signal)+ } finally {+ clearTimeout(timer)+ }+ }+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.tsindex 600cc2eea173..197a3abfe548 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts@@ -32,7 +32,7 @@ export class ImageFetchConsumerMetrics {help: 'URLs that passed every check and would have been fetched. In dry run no request is sent, so this is the offered rate rather than the sent rate',})/**- * `batch` and `pod` cost only memory, and `store` costs a Redis read, so the split is the+ * `batch` and `pod` cost only memory, and `store` costs a shared-store read, so the split is the* measurement rather than the total. A high `store` share against a full pod cache says the pod* cache is too small. A low one says the pod cache already holds the working set.*/diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.tsindex 5284fdbfd7c4..2f70a271505d 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts@@ -21,13 +21,13 @@ class FakeCrawlHistory implements CrawlHistoryStore {public readonly stored = new Map<string, number>()public readFailure: Error | null = nullpublic writeFailure: Error | null = null- /** Keys whose individual write reports a per-command failure, as ioredis does inside a pipeline. */+ /** Keys whose individual write reports a failure. */public partialWriteFailures = new Set<string>()/** Keys whose read did not complete, so the store can say nothing about them. */public partialReadFailures = new Set<string>()public reads = 0- read(keys: string[]): Promise<CrawlHistoryReadResult> {+ read(keys: string[], _nowMs: number): Promise<CrawlHistoryReadResult> {this.reads++if (this.readFailure) {return Promise.reject(this.readFailure)@@ -133,8 +133,8 @@ describe('UrlFetchConsumer', () => {it.each([NaN, 0, -1, 1.5, 7, 3599])('refuses to start with a seen TTL of %p', (seenTtlSeconds) => {// The TTL arrives from env, where a typo parses to NaN and a unit suffix truncates: "7d"- // parses to 7, and a 7-second TTL empties the ledger as fast as it fills. SET with a NaN- // expiry fails per command, so every ledger write would fail while the lane looks healthy.+ // parses to 7, and a 7-second TTL empties the ledger as fast as it fills. A NaN expiry makes+ // every ledger write fail while the lane looks healthy.expect(() =>new UrlFetchConsumer(crawlHistory, publisher, {@@ -322,7 +322,7 @@ describe('UrlFetchConsumer', () => {it('commits a batch the store could not answer for, rather than replaying it forever', async () => {// A store that answers nothing answers nothing for the next batch too, so a replay stops// the lane instead of saving the URL. Nothing is recorded, so the mirror offers it again.- crawlHistory.readFailure = new Error('redis down')+ crawlHistory.readFailure = new Error('store down')await expect(consumer.handleBatch([record([url('a')])], NOW)).resolves.toBeUndefined()@@ -332,7 +332,7 @@ describe('UrlFetchConsumer', () => {it('commits a batch whose store write failed, because the URL was fetched', async () => {// A missing crawl history entry costs one duplicate fetch later, which requirement 22// allows. A replay would cost the same duplicate and stall the partition too.- crawlHistory.writeFailure = new Error('redis down')+ crawlHistory.writeFailure = new Error('store down')await expect(consumer.handleBatch([record([url('a')])], NOW)).resolves.toBeUndefined()})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.tsindex cbc870657d79..d0ca7998e4f1 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts@@ -14,7 +14,7 @@ export interface UrlFetchConsumerOptions {/** The lane drops a URL older than this, so a backlog sheds work instead of fetching stale URLs. */maxAgeMs: numberdedupMaxRefs: number- /** TTL on each crawl history entry, which is both the recrawl interval and the ledger's Redis footprint. */+ /** TTL on each crawl history entry, which sets the recrawl interval. */seenTtlSeconds: number/** While true, no request leaves this process. Everything else still runs, including the crawl history write. */dryRun: boolean@@ -23,8 +23,8 @@ export interface UrlFetchConsumerOptions {/*** The image fetch lane.*- * The consumer handles a bad record and an unreachable Redis instead of throwing. This lane shares a- * partition with every site whose URLs key to it, and a throw here stops the consumer, replays the+ * The consumer handles a bad record and an unavailable crawl history instead of throwing. This lane+ * shares a partition with every site whose URLs key to it, and a throw here stops the consumer, replays the* same batch, and holds that partition against all of them.*/export class UrlFetchConsumer {@@ -46,8 +46,7 @@ export class UrlFetchConsumer {`SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS must be a positive number, got ${options.maxAgeMs}`)}- // A NaN TTL would not disable expiry: SET with EX NaN fails per command, so every ledger- // write fails and the lane stops recording while looking healthy. The hour floor catches+ // A NaN TTL makes every ledger write fail while the lane appears healthy. The hour floor catches// unit suffixes, which the env parser truncates rather than rejects: "7d" parses to 7, and// a 7-second TTL empties the ledger as fast as it fills, so nothing dedups.if (!Number.isInteger(options.seenTtlSeconds) || options.seenTtlSeconds < 60 * 60) {@@ -119,7 +118,7 @@ export class UrlFetchConsumer {}}- const fetchable = await this.removeAlreadySeen(candidates)+ const fetchable = await this.removeAlreadySeen(candidates, nowMs)if (fetchable.length > 0) {ImageFetchConsumerMetrics.incFetchable(fetchable.length)}@@ -206,14 +205,14 @@ export class UrlFetchConsumer {* batch, because our own store is down. It counts as unaccounted instead, which holds the batch* rather than loses it. Requirement 21.*/- private async removeAlreadySeen(candidates: FetchCandidate[]): Promise<FetchCandidate[]> {+ private async removeAlreadySeen(candidates: FetchCandidate[], nowMs: number): Promise<FetchCandidate[]> {if (candidates.length === 0) {return []}const keys = candidates.map((candidate) => crawlHistoryKey(candidate.pseudoTeam, candidate.urlHash))let resulttry {- result = await this.crawlHistory.read(keys)+ result = await this.crawlHistory.read(keys, nowMs)} catch (error) {ImageFetchConsumerMetrics.incStoreError('read', keys.length)logger.warn('🌐', 'ml_image_fetch_crawl_history_read_failed', { count: keys.length, error: String(error) })diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.tsindex 003a814e74d6..850aa90aebe8 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts@@ -85,7 +85,7 @@ export type MlMirrorConfig = {SESSION_RECORDING_ML_IMAGE_FETCH_BATCH_SIZE: number/** A URL older than this is dropped, so a lane with a backlog sheds work rather than fetching stale work. */SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS: number- /** Capacity of the per-pod seen-ref cache that sits in front of the Redis ledger. */+ /** Capacity of the per-pod seen-ref cache that sits in front of the shared crawl history. */SESSION_RECORDING_ML_IMAGE_FETCH_DEDUP_MAX_REFS: number/*** TTL on each crawl history entry, so it is both the recrawl interval and the ledger's Redis@@ -100,6 +100,12 @@ export type MlMirrorConfig = {SESSION_RECORDING_ML_IMAGE_FETCH_SEEN_TTL_SECONDS: number/** Bounds one round trip to the crawl history, including waiting for a pooled connection, so a Redis stall cannot hold the poll loop. */SESSION_RECORDING_ML_IMAGE_FETCH_REDIS_TIMEOUT_MS: number+ /** An empty table name keeps the Redis crawl-history backend active. */+ AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TABLE: string+ /** Bounds one DynamoDB request so an unavailable store cannot hold the poll loop. */+ AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TIMEOUT_MS: number+ /** TTL on each DynamoDB crawl-history entry, which sets the recrawl interval. */+ AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS: number/*** What one registrable domain receives from one pod.@@ -253,6 +259,9 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {SESSION_RECORDING_ML_IMAGE_FETCH_DEDUP_MAX_REFS: 500_000,SESSION_RECORDING_ML_IMAGE_FETCH_SEEN_TTL_SECONDS: 7 * 24 * 60 * 60,SESSION_RECORDING_ML_IMAGE_FETCH_REDIS_TIMEOUT_MS: 5_000,+ AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TABLE: '',+ AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TIMEOUT_MS: 5_000,+ AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS: 30 * 24 * 60 * 60,SESSION_RECORDING_ML_IMAGE_FETCH_REQUESTS_PER_SECOND: 1,SESSION_RECORDING_ML_IMAGE_FETCH_BURST: 5,SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_DOMAIN: 6,diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.tsindex 43bccf84b4db..9dfd991ad9d7 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts@@ -1,3 +1,6 @@+import { DynamoDBClient } from '@aws-sdk/client-dynamodb'+import { NodeHttpHandler } from '@smithy/node-http-handler'+import { initializePrometheusLabels } from '~/common/api/router'import {KAFKA_SESSION_REPLAY_IMAGE_FETCH,@@ -11,7 +14,11 @@ import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'import { createRedisPoolFromConfig } from '~/common/utils/db/redis'import { logger } from '~/common/utils/logger'import { SessionReplayProducerName } from '~/ingestion/pipelines/sessionreplay/config'-import { CrawlHistory } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history'+import {+ CrawlHistory,+ CrawlHistoryStore,+} from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history'+import { DynamoDBCrawlHistory } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history'import { FetchRunner } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner'import { FrontierPublisher } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher'import { HostBudget } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget'@@ -127,6 +134,7 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {readonly lifecycle: ServerLifecycleprivate config: IngestionSessionReplayMlMirrorServerConfigprivate crawlHistoryPool?: RedisPool+ private crawlHistoryClient?: DynamoDBClientprivate producerRegistry?: KafkaProducerRegistry<SessionReplayProducerName>constructor(config: Partial<IngestionSessionReplayMlMirrorServerConfig> = {}) {@@ -159,23 +167,46 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {)}- // The ml-mirror's instance, and deliberately not the cluster that serves the primary replay- // lane, because this store holds one key per distinct image URL and its eviction pressure- // must not be able to reach the lane that gates replay ingestion.- const connection = resolveMlMirrorRedisConnection(this.config)- if (!connection) {- throw new Error('SESSION_RECORDING_ML_REDIS_HOST must be set for the image-fetch consumer')+ let crawlHistory: CrawlHistoryStore+ let crawlHistoryTtlSeconds: number+ const tableName = this.config.AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TABLE+ if (tableName) {+ const dynamoDBTimeoutMs = this.config.AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TIMEOUT_MS+ if (!Number.isFinite(dynamoDBTimeoutMs) || dynamoDBTimeoutMs <= 0) {+ throw new Error(+ `AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TIMEOUT_MS must be a positive number, got ${dynamoDBTimeoutMs}`+ )+ }+ this.crawlHistoryClient = new DynamoDBClient({+ region: this.config.SESSION_RECORDING_V2_S3_REGION || 'us-east-1',+ endpoint: this.config.SESSION_RECORDING_DYNAMODB_ENDPOINT,+ maxAttempts: 5,+ requestHandler: new NodeHttpHandler(),+ })+ const dynamoDBCrawlHistory = new DynamoDBCrawlHistory(+ this.crawlHistoryClient,+ tableName,+ dynamoDBTimeoutMs,+ STORE_BATCH_BUDGET_MS+ )+ await dynamoDBCrawlHistory.validateAccess(Date.now())+ crawlHistory = dynamoDBCrawlHistory+ crawlHistoryTtlSeconds = this.config.AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS+ } else {+ const connection = resolveMlMirrorRedisConnection(this.config)+ if (!connection) {+ throw new Error('SESSION_RECORDING_ML_REDIS_HOST must be set for the image-fetch consumer')+ }+ const redisTimeoutMs = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_REDIS_TIMEOUT_MS+ this.crawlHistoryPool = createRedisPoolFromConfig({+ connection: { ...connection, options: { ...connection.options, commandTimeout: redisTimeoutMs } },+ poolMinSize: this.config.REDIS_POOL_MIN_SIZE,+ poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,+ acquireTimeoutMillis: redisTimeoutMs,+ })+ crawlHistory = new CrawlHistory(this.crawlHistoryPool, redisTimeoutMs, STORE_BATCH_BUDGET_MS)+ crawlHistoryTtlSeconds = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_SEEN_TTL_SECONDS}- const redisTimeoutMs = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_REDIS_TIMEOUT_MS- this.crawlHistoryPool = createRedisPoolFromConfig({- // The lane's own command timeout rather than the mirror's 200ms, because one round trip- // here carries a whole chunk of keys rather than one per-session command.- connection: { ...connection, options: { ...connection.options, commandTimeout: redisTimeoutMs } },- poolMinSize: this.config.REDIS_POOL_MIN_SIZE,- poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,- acquireTimeoutMillis: redisTimeoutMs,- })- const crawlHistory = new CrawlHistory(this.crawlHistoryPool, redisTimeoutMs, STORE_BATCH_BUDGET_MS)// Built even in dry run, so the wiring is exercised by every start rather than only by the// one that clears the flag.@@ -190,7 +221,7 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {{maxAgeMs: this.config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS,dedupMaxRefs: this.config.SESSION_RECORDING_ML_IMAGE_FETCH_DEDUP_MAX_REFS,- seenTtlSeconds: this.config.SESSION_RECORDING_ML_IMAGE_FETCH_SEEN_TTL_SECONDS,+ seenTtlSeconds: crawlHistoryTtlSeconds,dryRun,},dryRun ? undefined : buildFetchRunner(this.config, publisher)@@ -214,7 +245,10 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {return {kafkaProducers: [],redisPools: this.crawlHistoryPool ? [this.crawlHistoryPool] : [],- additionalCleanup: () => this.producerRegistry?.disconnectAll(),+ additionalCleanup: async () => {+ this.crawlHistoryClient?.destroy()+ await this.producerRegistry?.disconnectAll()+ },}}}