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): keep a DynamoDB throttle from stopping the ML lanes (#102197)

Robbie323e6101dbe8
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
index bd27b494c1ee..33ff9a0be404 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
@@ -11,6 +11,8 @@ export type MlMirrorConfig = {
AI_RESEARCH_REPLAY_KMS_REQUESTS_PER_SECOND: number
AI_RESEARCH_REPLAY_KEY_CACHE_MAX: number
AI_RESEARCH_REPLAY_KEY_CACHE_LIFETIME_MS: number
+ AI_RESEARCH_REPLAY_ROW_CACHE_MAX: number
+ AI_RESEARCH_REPLAY_ROW_CACHE_LIFETIME_MS: number
AI_RESEARCH_REPLAY_IMAGE_FETCH_V2_DYNAMODB_TABLE: string
AI_RESEARCH_REPLAY_S3_PREFIX: string
/** S3 key prefix under the bucket for the block-metadata Parquet dataset (used by the sink). */
@@ -224,6 +226,9 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {
AI_RESEARCH_REPLAY_KMS_REQUESTS_PER_SECOND: 150,
AI_RESEARCH_REPLAY_KEY_CACHE_MAX: 100_000,
AI_RESEARCH_REPLAY_KEY_CACHE_LIFETIME_MS: 1_800_000,
+ // Sized apart from the KMS cache above because a row is far larger than a key, and this lifetime carries the deletion lease.
+ AI_RESEARCH_REPLAY_ROW_CACHE_MAX: 100_000,
+ AI_RESEARCH_REPLAY_ROW_CACHE_LIFETIME_MS: 300_000,
AI_RESEARCH_REPLAY_IMAGE_FETCH_V2_DYNAMODB_TABLE: '',
AI_RESEARCH_REPLAY_S3_PREFIX: 'rrweb_2',
SESSION_RECORDING_ML_METADATA_PREFIX: 'block-metadata',
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/dynamodb.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/dynamodb.ts
index f403e5761c8c..5ab7021060e9 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/dynamodb.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/dynamodb.ts
@@ -5,14 +5,44 @@ import {
DynamoDBClient,
PutItemCommand,
} from '@aws-sdk/client-dynamodb'
+import { LRUCache } from 'lru-cache'
import pLimit from 'p-limit'
import { MlKeyRequest, MlMirrorMetrics } from '~/ingestion/pipelines/sessionreplay/ml-mirror/metrics'
-import { TableKey, tableKeyString } from './schema'
+import { TableKey, holdsCacheableRow, storedSessionId, tableKeyString } from './schema'
+import { isTransientError } from './transient'
+
+// A shredded key decrypts nothing, so these bounds stop a row being held forever rather than meet a deletion deadline.
+const SESSION_ROW_MAX_LIFETIME_MS = 300_000
+// A team image key is one row per team per month, so it survives eviction and a short lifetime only costs re-reads.
+const IMAGE_ROW_MAX_LIFETIME_MS = 172_800_000
+// A tombstone is terminal: shred only ever sets it, and putIfAbsent cannot overwrite a row whose pk exists, so holding
+// one cannot serve a key that came back. It also spares a deleted session a read and a doomed write on every batch.
+const TOMBSTONE_ROW_LIFETIME_MS = 172_800_000
+// Neither caller passes a deadline, and max.poll.interval.ms is 300s, so the retry loop needs a bound of its own.
+const READ_BUDGET_MS = 30_000
export type DynamoItem = Record<string, AttributeValue>
+// config.ts parses an env value with parseFloat, so a typo arrives as NaN or a fraction. Refusing to start names the
+// setting, where a fallback would run with a lifetime the operator did not choose and never say so.
+function positiveInteger(value: number, setting: string, cap = Number.MAX_SAFE_INTEGER): number {
+ if (!Number.isSafeInteger(value) || value <= 0) {
+ throw new Error(`${setting} must be a positive integer, got ${value}`)
+ }
+ return Math.min(value, cap)
+}
+
+// The SDK returns byte views over Node's shared 8 KiB pool, so holding one keeps the whole slab. The freeze is top level.
+function detachedRow(item: DynamoItem): DynamoItem {
+ const copy: DynamoItem = {}
+ for (const [name, value] of Object.entries(item)) {
+ copy[name] = value.B ? Object.freeze({ ...value, B: Uint8Array.from(value.B) }) : value
+ }
+ return Object.freeze(copy)
+}
+
export function encodeKey(key: TableKey): DynamoItem {
return { pk: { S: key.pk }, sk: { S: key.sk } }
}
@@ -27,40 +57,119 @@ export function decodeKey(item: DynamoItem): TableKey {
export class MlKeyDynamoDB {
private readonly concurrency = pLimit(4)
private readonly writeConcurrency = pLimit(32)
+ private readonly rows: LRUCache<string, DynamoItem>
+ private readonly sessionRowLifetimeMs: number
constructor(
private readonly client: Pick<DynamoDBClient, 'send'>,
readonly tableName: string,
private readonly requestTimeoutMs = 5_000,
- private readonly attempts = 5
- ) {}
+ private readonly attempts = 6,
+ cacheMax = 100_000,
+ cacheLifetimeMs = SESSION_ROW_MAX_LIFETIME_MS
+ ) {
+ this.sessionRowLifetimeMs = positiveInteger(
+ cacheLifetimeMs,
+ 'AI_RESEARCH_REPLAY_ROW_CACHE_LIFETIME_MS',
+ SESSION_ROW_MAX_LIFETIME_MS
+ )
+ this.rows = new LRUCache({
+ max: positiveInteger(cacheMax, 'AI_RESEARCH_REPLAY_ROW_CACHE_MAX'),
+ ttl: this.sessionRowLifetimeMs,
+ // lru-cache otherwise reads the clock once and refreshes it from a timer, so a loop that stays on
+ // microtasks keeps serving a row past the lease. This TTL carries the deletion lease, so it reads exactly.
+ ttlResolution: 0,
+ })
+ }
+
+ // Only a usable key row is stable enough to cache, because putIfAbsent writes it once. A team block row decides
+ // whether a batch may mint new keys, so a stale absent one would write durable keys for a team that asked to be blocked.
+ private cacheable(key: TableKey): boolean {
+ return holdsCacheableRow(key)
+ }
+
+ private hold(key: TableKey, item: DynamoItem): void {
+ if (!this.cacheable(key)) {
+ return
+ }
+ const id = tableKeyString(key)
+ if (item.deleted?.BOOL === true) {
+ this.rows.set(id, detachedRow(item), { ttl: TOMBSTONE_ROW_LIFETIME_MS })
+ } else if (item.wrapped_key?.B) {
+ this.rows.set(id, detachedRow(item), {
+ ttl: storedSessionId(key.sk) ? this.sessionRowLifetimeMs : IMAGE_ROW_MAX_LIFETIME_MS,
+ })
+ } else {
+ // No wrapped key and no tombstone is a row that repair can still fill in.
+ this.rows.delete(id)
+ }
+ }
- public async read(keys: TableKey[], deadline?: AbortSignal): Promise<Map<string, DynamoItem>> {
+ public async read(keys: TableKey[], callerDeadline?: AbortSignal): Promise<Map<string, DynamoItem>> {
+ const deadline = callerDeadline ?? AbortSignal.timeout(READ_BUDGET_MS)
const unique = [...new Map(keys.map((key) => [tableKeyString(key), key])).values()]
const result = new Map<string, DynamoItem>()
+ const missing: TableKey[] = []
+ for (const key of unique) {
+ const id = tableKeyString(key)
+ const cached = this.cacheable(key) ? this.rows.get(id) : undefined
+ if (cached) {
+ MlMirrorMetrics.incrementMlKeyRowCacheLookup('hit')
+ result.set(id, cached)
+ } else {
+ if (this.cacheable(key)) {
+ MlMirrorMetrics.incrementMlKeyRowCacheLookup('miss')
+ }
+ missing.push(key)
+ }
+ }
const chunks: TableKey[][] = []
- for (let offset = 0; offset < unique.length; offset += 100) {
- chunks.push(unique.slice(offset, offset + 100))
+ for (let offset = 0; offset < missing.length; offset += 100) {
+ chunks.push(missing.slice(offset, offset + 100))
}
await Promise.all(
chunks.map((chunk) =>
this.concurrency(async () => {
let pending = chunk.map(encodeKey)
for (let attempt = 0; pending.length && attempt < this.attempts; attempt++) {
- const response = await this.timed('dynamodb_read', () =>
- this.client.send(
- new BatchGetItemCommand({
- RequestItems: { [this.tableName]: { Keys: pending, ConsistentRead: true } },
- }),
- { abortSignal: this.requestSignal(deadline) }
+ // Reads retry here because MlKeyReader and MlSessionKeyStore.prepare have no retry of their own, unlike writes, which MlKeyBatch.commit retries.
+ let response
+ try {
+ response = await this.timed('dynamodb_read', () =>
+ this.client.send(
+ new BatchGetItemCommand({
+ RequestItems: { [this.tableName]: { Keys: pending, ConsistentRead: true } },
+ }),
+ { abortSignal: this.requestSignal(deadline) }
+ )
)
- )
+ } catch (error) {
+ // A spent deadline also aborts the request, and an AbortError counts as transient, so the
+ // deadline is checked separately. Otherwise the loop waits out its attempts past the budget
+ // that keeps a batch under the consumer's stall threshold.
+ if (!isTransientError(error) || deadline.aborted || attempt === this.attempts - 1) {
+ throw error
+ }
+ MlMirrorMetrics.incrementMlKeyReadRetry('transient_error')
+ await this.backoff(attempt, deadline)
+ if (deadline.aborted) {
+ throw new DOMException('ML key manager bulk read deadline expired', 'AbortError')
+ }
+ continue
+ }
for (const item of response.Responses?.[this.tableName] ?? []) {
- result.set(tableKeyString(decodeKey(item)), item)
+ const key = decodeKey(item)
+ const id = tableKeyString(key)
+ result.set(id, item)
+ this.hold(key, item)
}
pending = response.UnprocessedKeys?.[this.tableName]?.Keys ?? []
if (pending.length) {
- await this.backoff(attempt)
+ MlMirrorMetrics.incrementMlKeyReadRetry('unprocessed_keys')
+ await this.backoff(attempt, deadline)
+ if (deadline.aborted) {
+ throw new DOMException('ML key manager bulk read deadline expired', 'AbortError')
+ }
}
}
if (pending.length) {
@@ -69,10 +178,22 @@ export class MlKeyDynamoDB {
})
)
)
+ this.rows.purgeStale()
+ MlMirrorMetrics.setMlKeyRowCacheEntries(this.rows.size)
return result
}
- public async putIfAbsent(key: TableKey, attributes: DynamoItem, deadline?: AbortSignal): Promise<boolean> {
+ public clear(): void {
+ this.rows.clear()
+ MlMirrorMetrics.setMlKeyRowCacheEntries(0)
+ }
+
+ /** Resolves to the row that won when this put lost, or to undefined when this put stored the key. */
+ public async putIfAbsent(
+ key: TableKey,
+ attributes: DynamoItem,
+ deadline?: AbortSignal
+ ): Promise<DynamoItem | undefined> {
return this.writeConcurrency(() =>
this.timed('dynamodb_put_if_absent', async () => {
try {
@@ -81,13 +202,21 @@ export class MlKeyDynamoDB {
TableName: this.tableName,
Item: { ...encodeKey(key), ...attributes },
ConditionExpression: 'attribute_not_exists(pk)',
+ // The refusal carries the row that won, so the loser needs no read to adopt it.
+ ReturnValuesOnConditionCheckFailure: 'ALL_OLD',
}),
{ abortSignal: this.requestSignal(deadline) }
)
- return true
+ // This row now exists with exactly these attributes, so the next batch needs no read for it.
+ this.hold(key, { ...encodeKey(key), ...attributes })
+ return undefined
} catch (error) {
if (error instanceof ConditionalCheckFailedException) {
- return false
+ const winner = error.Item
+ if (winner) {
+ this.hold(key, winner)
+ }
+ return winner ?? {}
}
throw error
}
@@ -120,7 +249,24 @@ export class MlKeyDynamoDB {
return deadline ? AbortSignal.any([deadline, timeout]) : timeout
}
- public async backoff(attempt: number): Promise<void> {
- await new Promise((resolve) => setTimeout(resolve, Math.min(1000, 50 * 2 ** attempt) + Math.random() * 50))
+ // The cap matches MlKeyBatch.commit because an account-wide throttle outlasts a shorter budget.
+ public async backoff(attempt: number, deadline?: AbortSignal): Promise<void> {
+ const delayMs = Math.min(3_000, 50 * 2 ** attempt) + Math.random() * 50
+ if (!deadline) {
+ await new Promise((resolve) => setTimeout(resolve, delayMs))
+ return
+ }
+ if (deadline.aborted) {
+ return
+ }
+ await new Promise<void>((resolve) => {
+ const stop = (): void => {
+ clearTimeout(timer)
+ deadline.removeEventListener('abort', stop)
+ resolve()
+ }
+ const timer = setTimeout(stop, delayMs)
+ deadline.addEventListener('abort', stop, { once: true })
+ })
}
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts
index 0cdf0b4caafa..1de677055375 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts
@@ -72,7 +72,10 @@ class DynamoBoundary {
await Promise.resolve()
if (command.input.ConditionExpression === 'attribute_not_exists(pk)' && this.items.has(id)) {
this.conditionalFailures += 1
- throw new ConditionalCheckFailedException({ $metadata: {}, message: 'The conditional request failed' })
+ throw Object.assign(
+ new ConditionalCheckFailedException({ $metadata: {}, message: 'The conditional request failed' }),
+ command.input.ReturnValuesOnConditionCheckFailure === 'ALL_OLD' ? { Item: this.items.get(id) } : {}
+ )
}
this.items.set(id, item)
return {}
@@ -114,10 +117,14 @@ describe('ML session key batches', () => {
8,
1_000_000_000
)
+ coldCache()
+ })
+
+ function coldCache(): void {
const db = new MlKeyDynamoDB(boundary as unknown as DynamoDBClient, table)
store = new MlSessionKeyStore(db, encryption)
reader = new MlKeyReader(db, encryption)
- })
+ }
afterEach(() => {
jest.useRealTimers()
@@ -188,6 +195,71 @@ describe('ML session key batches', () => {
expect(boundary.writes).toBeLessThanOrEqual(2)
})
+ it.each([
+ ['prepare', 5, true],
+ ['prepare', 6, false],
+ ['reader', 5, true],
+ ['reader', 6, false],
+ ])('%s under %i consecutive read throttles succeeds: %s', async (entryPoint, failures, succeeds) => {
+ const send = boundary.send.bind(boundary)
+ let remaining = failures as number
+ jest.spyOn(boundary, 'send').mockImplementation((command) => {
+ if (command instanceof BatchGetItemCommand && remaining > 0) {
+ remaining -= 1
+ return Promise.reject(transientError('RequestLimitExceeded'))
+ }
+ return send(command)
+ })
+ jest.useFakeTimers()
+ const settled = (
+ entryPoint === 'prepare'
+ ? store.prepare([session])
+ : reader.read([sessionKeyId(session.teamId, session.sessionId)])
+ ).then(
+ () => 'read',
+ () => 'failed'
+ )
+ await jest.runAllTimersAsync()
+ expect(await settled).toBe(succeeds ? 'read' : 'failed')
+ })
+
+ it('sends no further request when the deadline aborts during a retry delay', async () => {
+ const db = new MlKeyDynamoDB(boundary as unknown as DynamoDBClient, table)
+ const budget = new AbortController()
+ let sends = 0
+ jest.spyOn(boundary, 'send').mockImplementation(() => {
+ sends += 1
+ return Promise.reject(transientError('ThrottlingException'))
+ })
+ jest.useFakeTimers()
+ const settled = db.read([sessionKeyId(session.teamId, session.sessionId)], budget.signal).then(
+ () => 'read',
+ () => 'failed'
+ )
+ await jest.advanceTimersByTimeAsync(0)
+ budget.abort()
+ await jest.runAllTimersAsync()
+ expect(await settled).toBe('failed')
+ expect(sends).toBe(1)
+ })
+
+ it('stops a read when the caller deadline aborts instead of waiting out its attempts', async () => {
+ const db = new MlKeyDynamoDB(boundary as unknown as DynamoDBClient, table)
+ let attempts = 0
+ jest.spyOn(boundary, 'send').mockImplementation(() => {
+ attempts += 1
+ return Promise.reject(transientError('AbortError'))
+ })
+ jest.useFakeTimers()
+ const settled = db.read([sessionKeyId(session.teamId, session.sessionId)], AbortSignal.abort()).then(
+ () => 'read',
+ () => 'failed'
+ )
+ await jest.runAllTimersAsync()
+ expect(await settled).toBe('failed')
+ expect(attempts).toBe(1)
+ })
+
it('writes the month index entry before the key and repairs a failed index put', async () => {
const send = boundary.send.bind(boundary)
let remaining = 1
@@ -264,7 +336,7 @@ describe('ML session key batches', () => {
expect(remaining).toBeGreaterThan(0)
})
- it('indexes monthly keys, ignores a month marker, and blocks on a team marker set during a batch', async () => {
+ it('indexes monthly keys, ignores a month marker, and refuses a team marker from the next read', async () => {
const october = { ...session, sessionId: '0199a13b-c000-7000-8000-000000000007' }
const first = await store.prepare([session, october])
await first.commit()
@@ -303,8 +375,10 @@ describe('ML session key batches', () => {
const committing = inFlight.commit()
await jest.runAllTimersAsync()
await committing
- expect(inFlight.get(session.teamId, session.sessionId)).toBeUndefined()
+ // A commit no longer re-reads, so the in-flight batch misses the block that every reader and the next batch see.
+ expect(inFlight.get(session.teamId, session.sessionId)).not.toBeUndefined()
expect((await reader.read(locations)).size).toBe(0)
+ expect((await store.prepare([session])).get(session.teamId, session.sessionId)).toBeUndefined()
})
it('wraps new keys without an organization and stores none on the row', async () => {
@@ -384,6 +458,7 @@ describe('ML session key batches', () => {
const location = tableKeyString(keyId())
const { wrapped_key: _wrapped, ...stored } = boundary.items.get(location)!
boundary.items.set(location, stored)
+ coldCache()
const unusable = jest.spyOn(MlMirrorMetrics, 'incrementMlKeyIdentityMismatch')
const next = await store.prepare([session])
expect(next.get(session.teamId, session.sessionId)).toBeUndefined()
@@ -409,18 +484,119 @@ describe('ML session key batches', () => {
expect(second.get(session.teamId, session.sessionId)!.session.plaintext).not.toEqual(provisional)
})
- it('blocks an existing session deleted during a batch', async () => {
+ it.each([
+ ['a fractional value', 30_000.5],
+ ['an unparsable value', Number.NaN],
+ ['a zero', 0],
+ ])('refuses to start on %s cache setting', (_label, configured) => {
+ expect(
+ () =>
+ new MlKeyDynamoDB(boundary as unknown as DynamoDBClient, table, undefined, undefined, 1000, configured)
+ ).toThrow('AI_RESEARCH_REPLAY_ROW_CACHE_LIFETIME_MS')
+ })
+
+ it.each([
+ ['a lifetime over the cap is clamped', 86_400_000, 300_001, false],
+ ['a lifetime under the cap is kept', 60_000, 60_001, false],
+ ['a team image key outlives the session cap', 86_400_000, 300_001, true],
+ ])('%s', async (_label, configured, elapsedMs, imageKey) => {
+ let fakeNow = 1_000
+ const clock = jest.spyOn(performance, 'now').mockImplementation(() => fakeNow)
+ try {
+ const db = new MlKeyDynamoDB(
+ boundary as unknown as DynamoDBClient,
+ table,
+ undefined,
+ undefined,
+ 1000,
+ configured
+ )
+ const location = imageKey
+ ? imageKeyId(session.teamId, '2025-09')
+ : sessionKeyId(session.teamId, session.sessionId)
+ await (await new MlSessionKeyStore(db, encryption).prepare([session])).commit()
+ const reader = new MlKeyReader(db, encryption)
+ expect((await reader.read([location])).size).toBe(1)
+ boundary.items.set(tableKeyString(location), { ...encodeKey(location), deleted: { BOOL: true } })
+ fakeNow += elapsedMs
+ expect((await reader.read([location])).size).toBe(imageKey ? 1 : 0)
+ } finally {
+ clock.mockRestore()
+ }
+ })
+
+ it('refuses a blocked team on the next batch while its session row is still cached', async () => {
+ await (await store.prepare([session])).commit()
+ const warm = await store.prepare([session])
+ expect(warm.get(session.teamId, session.sessionId)).not.toBeUndefined()
+ const blocked = teamBlockId(session.teamId)
+ boundary.items.set(tableKeyString(blocked), { ...encodeKey(blocked), deleted: { BOOL: true } })
+ const readsBefore = boundary.readSizes.length
+ const next = await store.prepare([session])
+ // Only the team block row reached DynamoDB. The session row was served from the cache and did not hide the block.
+ expect(boundary.readSizes.slice(readsBefore).reduce((total, size) => total + size, 0)).toBe(1)
+ expect(next.get(session.teamId, session.sessionId)).toBeUndefined()
+ // The block is held once seen, so a team that keeps sending stops costing a read per batch.
+ const afterBlockRead = boundary.readSizes.length
+ expect((await store.prepare([session])).get(session.teamId, session.sessionId)).toBeUndefined()
+ expect(boundary.readSizes.slice(afterBlockRead).reduce((total, size) => total + size, 0)).toBe(0)
+ })
+
+ it('holds a session tombstone so a deleted session stops costing a read and a doomed write', async () => {
+ const db = new MlKeyDynamoDB(boundary as unknown as DynamoDBClient, table)
+ const store = new MlSessionKeyStore(db, encryption)
+ const location = sessionKeyId(session.teamId, session.sessionId)
+ await (await store.prepare([session])).commit()
+ boundary.items.set(tableKeyString(location), { ...encodeKey(location), deleted: { BOOL: true } })
+ const cold = new MlSessionKeyStore(new MlKeyDynamoDB(boundary as unknown as DynamoDBClient, table), encryption)
+ const first = await cold.prepare([session])
+ expect(first.get(session.teamId, session.sessionId)).toBeUndefined()
+ const readsBefore = boundary.readSizes.length
+ const writesBefore = boundary.writes
+ const next = await cold.prepare([session])
+ await next.commit()
+ expect(next.get(session.teamId, session.sessionId)).toBeUndefined()
+ // Only the team block row, which is never cached. The tombstone spares the session key row and the image key row.
+ expect(boundary.readSizes.slice(readsBefore).reduce((total, size) => total + size, 0)).toBe(1)
+ expect(boundary.writes).toBe(writesBefore)
+ })
+
+ it('serves a deleted session key until its cached row reaches the lease, then stops', async () => {
+ const lifetimeMs = 60_000
+ let fakeNow = 1_000
+ const clock = jest.spyOn(performance, 'now').mockImplementation(() => fakeNow)
+ try {
+ const db = new MlKeyDynamoDB(
+ boundary as unknown as DynamoDBClient,
+ table,
+ undefined,
+ undefined,
+ 1000,
+ lifetimeMs
+ )
+ const warm = new MlSessionKeyStore(db, encryption)
+ const sameReader = new MlKeyReader(db, encryption)
+ const location = sessionKeyId(session.teamId, session.sessionId)
+ await (await warm.prepare([session])).commit()
+ expect((await sameReader.read([location])).size).toBe(1)
+ boundary.items.set(tableKeyString(location), { ...encodeKey(location), deleted: { BOOL: true } })
+ // The read part way through must not extend the entry, or a session read often enough never observes its deletion.
+ fakeNow += lifetimeMs * 0.6
+ expect((await sameReader.read([location])).size).toBe(1)
+ fakeNow += lifetimeMs * 0.4 + 1
+ expect((await sameReader.read([location])).size).toBe(0)
+ } finally {
+ clock.mockRestore()
+ }
+ })
+
+ it('stops serving a deleted session key to a reader that has not cached it', async () => {
const first = await store.prepare([session])
await first.commit()
- const next = await store.prepare([session])
const blocked = sessionKeyId(session.teamId, session.sessionId)
boundary.items.set(tableKeyString(blocked), { ...encodeKey(blocked), deleted: { BOOL: true } })
- jest.useFakeTimers()
- const committed = next.commit()
- await jest.runAllTimersAsync()
- await committed
- expect(next.get(session.teamId, session.sessionId)).toBeUndefined()
- expect((await reader.read([sessionKeyId(session.teamId, session.sessionId)])).size).toBe(0)
+ coldCache()
+ expect((await reader.read([blocked])).size).toBe(0)
expect((await reader.read([imageKeyId(session.teamId, '2025-09')])).size).toBe(1)
})
@@ -428,13 +604,17 @@ describe('ML session key batches', () => {
const first = await store.prepare([session])
await first.commit()
const original = first.get(session.teamId, session.sessionId)!
+ const readsBefore = boundary.readSizes.length
const resumed = await store.prepare([session])
+ const keysRead = boundary.readSizes.slice(readsBefore).reduce((total, size) => total + size, 0)
await resumed.commit()
const keys = resumed.get(session.teamId, session.sessionId)!
expect(keys.session.plaintext).toEqual(original.session.plaintext)
expect(keys.image.plaintext).toEqual(original.image.plaintext)
expect((await reader.read([sessionKeyId(session.teamId, session.sessionId)])).size).toBe(1)
expect(generated).toBe(2)
+ // Only the team block row, because it decides whether the batch may mint new keys and is never cached.
+ expect(keysRead).toBe(1)
})
it('publishes only after key writes commit and hands delivery acks to the scheduler', async () => {
@@ -527,6 +707,7 @@ describe('ML session key batches', () => {
} as Message
})
boundary.items.delete(tableKeyString(sessionKeyId(deleted.teamId, deleted.sessionId)))
+ coldCache()
const invalidRow = parseJSON(messages[0].value!.toString())
invalidRow.session_id =
malformed === 'oversized-session'
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts
index 009f8ac17eec..7d4a0059e2e3 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts
@@ -15,38 +15,13 @@ import {
tableKeyString,
teamBlockId,
} from './schema'
+import { isTransientError } from './transient'
// Commits retry transient DynamoDB and KMS failures; the budget counts the re-reads as well as the waits and stays under the consumer's loop stall threshold.
const COMMIT_ATTEMPTS = 10
const COMMIT_BUDGET_MS = 45_000
const COMMIT_BACKOFF_BASE_MS = 100
const COMMIT_BACKOFF_CAP_MS = 3_000
-const TRANSIENT_ERRORS = new Set([
- 'ProvisionedThroughputExceededException',
- 'ThrottlingException',
- 'RequestLimitExceeded',
- 'InternalServerError',
- 'ServiceUnavailableException',
- 'TransactionConflictException',
- 'KMSInternalException',
- 'DependencyTimeoutException',
- 'TimeoutError',
- 'AbortError',
-])
-const TRANSIENT_ERROR_CODES = new Set(['ECONNRESET', 'ECONNREFUSED', 'EPIPE', 'ETIMEDOUT', 'EAI_AGAIN'])
-
-function isTransientError(error: unknown): boolean {
- if (!(error instanceof Error)) {
- return false
- }
- const { code, $retryable, $fault } = error as Error & { code?: string; $retryable?: unknown; $fault?: string }
- return (
- TRANSIENT_ERRORS.has(error.name) ||
- TRANSIENT_ERROR_CODES.has(code ?? '') ||
- $retryable !== undefined ||
- $fault === 'server'
- )
-}
function commitRetryDelayMs(attempt: number): number {
return Math.random() * Math.min(COMMIT_BACKOFF_CAP_MS, COMMIT_BACKOFF_BASE_MS * 2 ** attempt)
@@ -183,7 +158,7 @@ export class MlKeyBatch {
// The index entry goes first and is idempotent, so every stored key has an index entry even when the key put fails or a retried put reports the batch's own write as a competitor's. An index entry without a key is harmless: the month sweep leaves a tombstone that a later key put respects.
private async persist(deadline: AbortSignal): Promise<void> {
- const before = [...this.keys.keys()]
+ let dropped = 0
const results = await Promise.allSettled(
[...this.keys].map(async ([id, key]) => {
if (this.state.has(id)) {
@@ -195,7 +170,7 @@ export class MlKeyBatch {
{ key_pk: { S: location.pk }, key_sk: { S: location.sk } },
deadline
)
- const created = await this.db.putIfAbsent(
+ const stored = await this.db.putIfAbsent(
location,
{
wrapped_key: { B: key.wrapped },
@@ -204,9 +179,24 @@ export class MlKeyBatch {
},
deadline
)
- if (created) {
+ if (!stored) {
this.encryption.rememberCommitted(key)
+ return
+ }
+ // A session keys its own partition, so only a rebalance overlap or a team key puts two writers on one row.
+ if (!stored.wrapped_key?.B || stored.deleted?.BOOL === true) {
+ this.keys.delete(id)
+ dropped += 1
+ return
+ }
+ const wrapped = Buffer.from(stored.wrapped_key.B)
+ if (wrapped.equals(key.wrapped)) {
+ this.encryption.rememberCommitted(key)
+ return
}
+ const organizationId = stored.organization_id?.S
+ const identity = { ...key.identity, ...(organizationId ? { organizationId } : {}) }
+ this.keys.set(id, await this.encryption.decrypt(identity, wrapped))
})
)
const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
@@ -214,8 +204,6 @@ export class MlKeyBatch {
if (failure) {
throw failure.reason
}
- await this.read(deadline)
- const dropped = before.filter((id) => !this.keys.has(id)).length
if (dropped) {
logger.info('🔑', 'ml_key_commit_dropped_blocked', { dropped })
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader.ts
index 3d9f82527e41..4c4231fc96c5 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader.ts
@@ -1,6 +1,6 @@
import { MlDataKey, MlKeyEncryption } from './crypto'
import { MlKeyDynamoDB } from './dynamodb'
-import { MlKeyIdentity, TableKey, tableKeyString, teamBlockId } from './schema'
+import { MlKeyIdentity, TableKey, storedSessionId, tableKeyString, teamBlockId } from './schema'
export class MlKeyReader {
constructor(
@@ -19,7 +19,7 @@ export class MlKeyReader {
if (!Number.isSafeInteger(teamId)) {
throw new Error('Invalid ML key record')
}
- const sessionId = item.sk.S?.startsWith('session:') ? item.sk.S.slice('session:'.length) : undefined
+ const sessionId = item.sk.S ? storedSessionId(item.sk.S) : undefined
const organizationId = item.organization_id?.S
identities.set(id, {
teamId,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime.ts
index f94b7e4e80c2..5a1517949775 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime.ts
@@ -14,6 +14,8 @@ export interface MlKeyManagerConfig {
AI_RESEARCH_REPLAY_AWS_REGION: string
AI_RESEARCH_REPLAY_KEY_CACHE_MAX: number
AI_RESEARCH_REPLAY_KEY_CACHE_LIFETIME_MS: number
+ AI_RESEARCH_REPLAY_ROW_CACHE_MAX: number
+ AI_RESEARCH_REPLAY_ROW_CACHE_LIFETIME_MS: number
AI_RESEARCH_REPLAY_KMS_REQUESTS_PER_SECOND: number
SESSION_RECORDING_DYNAMODB_ENDPOINT?: string
}
@@ -23,6 +25,7 @@ export class MlKeyManager {
public readonly reader: MlKeyReader
public readonly controller: MlKeyBatchController
public readonly kafka: MlKafkaTransport
+ private readonly db: MlKeyDynamoDB
private readonly dynamo: DynamoDBClient
private readonly kms: KMSClient
@@ -36,7 +39,14 @@ export class MlKeyManager {
maxAttempts: 3,
})
this.kms = new KMSClient({ region: config.AI_RESEARCH_REPLAY_AWS_REGION, maxAttempts: 3 })
- const db = new MlKeyDynamoDB(this.dynamo, config.AI_RESEARCH_REPLAY_KEY_TABLE)
+ this.db = new MlKeyDynamoDB(
+ this.dynamo,
+ config.AI_RESEARCH_REPLAY_KEY_TABLE,
+ undefined,
+ undefined,
+ config.AI_RESEARCH_REPLAY_ROW_CACHE_MAX,
+ config.AI_RESEARCH_REPLAY_ROW_CACHE_LIFETIME_MS
+ )
this.encryption = new MlKeyEncryption(
this.kms,
config.AI_RESEARCH_REPLAY_KMS_KEY_ARN,
@@ -45,8 +55,8 @@ export class MlKeyManager {
8,
config.AI_RESEARCH_REPLAY_KMS_REQUESTS_PER_SECOND
)
- this.reader = new MlKeyReader(db, this.encryption)
- this.controller = new MlKeyBatchController(new MlSessionKeyStore(db, this.encryption), this.encryption)
+ this.reader = new MlKeyReader(this.db, this.encryption)
+ this.controller = new MlKeyBatchController(new MlSessionKeyStore(this.db, this.encryption), this.encryption)
this.kafka = new MlKafkaTransport(this.reader)
}
@@ -56,6 +66,7 @@ export class MlKeyManager {
public stop(): void {
this.encryption.clear()
+ this.db.clear()
this.dynamo.destroy()
this.kms.destroy()
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema.ts
index 4b5cb3f29dbe..fd1a9198d48b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema.ts
@@ -34,12 +34,16 @@ export function sessionShard(sessionId: string): number {
return Number.parseInt(identityDigest(sessionId).slice(0, 8), 16) % ML_KEY_SHARDS
}
+const SESSION_KEY_PREFIX = 'session:'
+const IMAGE_KEY_PREFIX = 'image:'
+const TEAM_BLOCK_SK = 'deleted'
+
export function sessionKeyId(teamId: number, sessionId: string): TableKey {
- return { pk: `team:${teamId}:shard:${sessionShard(sessionId)}`, sk: `session:${sessionId}` }
+ return { pk: `team:${teamId}:shard:${sessionShard(sessionId)}`, sk: `${SESSION_KEY_PREFIX}${sessionId}` }
}
export function imageKeyId(teamId: number, sessionMonth: string): TableKey {
- return { pk: `team:${teamId}`, sk: `image:${sessionMonth}` }
+ return { pk: `team:${teamId}`, sk: `${IMAGE_KEY_PREFIX}${sessionMonth}` }
}
export function keySessionMonth(identity: MlKeyIdentity): string {
@@ -57,8 +61,18 @@ export function monthKeyIndexId(identity: MlKeyIdentity, key: TableKey): TableKe
return { pk: `month:${keySessionMonth(identity)}:shard:${sessionShard(id)}`, sk: `key:${id}` }
}
+// The only update to a stored key row is the deletion tombstone, so a cache of one is stale only for a deletion, and its lifetime is what bounds how late that tombstone is seen.
+// A team block row joins them because nothing ever clears one. Only a row that exists is ever held, so holding these caches "blocked", never "not blocked".
+export function holdsCacheableRow(key: TableKey): boolean {
+ return key.sk.startsWith(SESSION_KEY_PREFIX) || key.sk.startsWith(IMAGE_KEY_PREFIX) || key.sk === TEAM_BLOCK_SK
+}
+
+export function storedSessionId(sortKey: string): string | undefined {
+ return sortKey.startsWith(SESSION_KEY_PREFIX) ? sortKey.slice(SESSION_KEY_PREFIX.length) : undefined
+}
+
export function teamBlockId(teamId: number): TableKey {
- return { pk: `team:${teamId}`, sk: 'deleted' }
+ return { pk: `team:${teamId}`, sk: TEAM_BLOCK_SK }
}
export function tableKeyString(key: TableKey): string {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/transient.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/transient.ts
new file mode 100644
index 000000000000..1c6cd9b265df
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/transient.ts
@@ -0,0 +1,26 @@
+const TRANSIENT_ERRORS = new Set([
+ 'ProvisionedThroughputExceededException',
+ 'ThrottlingException',
+ 'RequestLimitExceeded',
+ 'InternalServerError',
+ 'ServiceUnavailableException',
+ 'TransactionConflictException',
+ 'KMSInternalException',
+ 'DependencyTimeoutException',
+ 'TimeoutError',
+ 'AbortError',
+])
+const TRANSIENT_ERROR_CODES = new Set(['ECONNRESET', 'ECONNREFUSED', 'EPIPE', 'ETIMEDOUT', 'EAI_AGAIN'])
+
+export function isTransientError(error: unknown): boolean {
+ if (!(error instanceof Error)) {
+ return false
+ }
+ const { code, $retryable, $fault } = error as Error & { code?: string; $retryable?: unknown; $fault?: string }
+ return (
+ TRANSIENT_ERRORS.has(error.name) ||
+ TRANSIENT_ERROR_CODES.has(code ?? '') ||
+ $retryable !== undefined ||
+ $fault === 'server'
+ )
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport.ts
index e7f57d48fb45..8a4d0eb33c92 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport.ts
@@ -95,7 +95,8 @@ export class MlKafkaTransport {
/**
* Classifies a batch by wire version and, when the caller names the session each record belongs to, resolves
* that session's key so the caller can seal its output. A record whose session key is deleted or blocked is
- * dropped, so the caller can count the gap.
+ * dropped, so the caller can count the gap. A blocked team is refused on every read, while a deleted session is
+ * still served while a process holds its cached row, for the row cache lifetime.
*/
public async read(
messages: Message[],
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
index c27706bcc39f..803dd0422536 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
@@ -1,4 +1,4 @@
-import { Counter, Histogram } from 'prom-client'
+import { Counter, Gauge, Histogram } from 'prom-client'
import { MlWireVersion } from './keys/schema'
@@ -136,6 +136,20 @@ export class MlMirrorMetrics {
* observing each one puts the size of the payload on the mirror's hot path.
*/
private static urlBytesSeen = 0
+ private static readonly mlKeyRowCacheLookups = new Counter({
+ name: 'recording_blob_ingestion_v2_ml_key_row_cache_lookups_total',
+ help: 'Lookups of a stored ML key row in the per-process cache, by outcome. A hit skips the DynamoDB read, and skips the KMS decrypt as well while the plaintext cache still holds that key. A hit also does not see a tombstone written since the row was read. Note that dynamodb_read on ml_key_request_duration counts misses only, so read that rate against this one rather than as total key traffic',
+ labelNames: ['outcome'],
+ })
+ private static readonly mlKeyRowCacheEntries = new Gauge({
+ name: 'recording_blob_ingestion_v2_ml_key_row_cache_entries',
+ help: 'Stored ML key rows the per-process cache holds, counted after a read. Expired rows stay counted until a read or an eviction removes them, so this tracks the memory held rather than the rows still usable, and it stands still on an idle lane',
+ })
+ private static readonly mlKeyReadRetries = new Counter({
+ name: 'recording_blob_ingestion_v2_ml_key_read_retries_total',
+ help: 'Retries of an ML key read, by reason. BatchGetItem answers a partial throttle with HTTP 200 and unprocessed keys rather than an exception, so unprocessed_keys is the usual throttle signal and transient_error is the request-level one. Commits log ml_key_commit_retry for the write path; reads have no equivalent log',
+ labelNames: ['reason'],
+ })
private static readonly mlKeyPhaseDuration = new Histogram({
name: 'recording_blob_ingestion_v2_ml_key_phase_duration_ms',
help: 'Wall time of one ML key phase per Kafka batch. The consumer handles one batch at a time, so these phases plus anonymization are the batch wall time; a phase that dominates while pod CPU stays low is the lane waiting on KMS, DynamoDB or Kafka rather than working',
@@ -167,6 +181,18 @@ export class MlMirrorMetrics {
this.mlKeyRequestDuration.labels(request).observe(ms)
}
+ public static incrementMlKeyRowCacheLookup(outcome: 'hit' | 'miss'): void {
+ this.mlKeyRowCacheLookups.labels(outcome).inc()
+ }
+
+ public static setMlKeyRowCacheEntries(entries: number): void {
+ this.mlKeyRowCacheEntries.set(entries)
+ }
+
+ public static incrementMlKeyReadRetry(reason: 'transient_error' | 'unprocessed_keys'): void {
+ this.mlKeyReadRetries.labels(reason).inc()
+ }
+
public static observeMlAnonymizeDuration(impl: MlAnonymizeImpl, ms: number, route: MlAnonymizeRoute = ''): void {
this.mlAnonymizeDuration.labels(impl, route).observe(ms)
}
diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.md
index c93f013bf908..b650f2c99f6d 100644
--- a/products/ai_training/docs/replay-data.md
+++ b/products/ai_training/docs/replay-data.md
@@ -51,16 +51,24 @@ Ingestion processes key state in batches:
1. Bulk-read session keys, team blocks, and image keys.
2. Resolve keys in memory while processing the batch.
3. Write each new key's month index entry, then the key with a conditional put.
-4. Re-read the batch, adopt a competing writer's keys, drop sessions or teams blocked during the batch, then publish replay blocks or image messages.
+4. Adopt the key a competing writer stored, which the refused put returns, then publish replay blocks or image messages.
A conditional put refuses to recreate a shredded session key.
-A team blocked during a batch is dropped by the batch re-read and refused by every reader, and the deletion worker sweeps the team once more after the reader lease, so a key stored after the block is shredded.
+A team blocked during a batch is refused by every reader at once and by the next batch, which reads the block row live, and the deletion worker sweeps the team once more after the reader lease, so a key stored after the block is shredded.
Kafka offsets advance only after the required writes and publication succeed.
Bulk reads use batches of at most 100 keys; each new key is one conditional put, so no commit in the fleet waits on another.
-Reads use strongly consistent `BatchGetItem` requests with bounded retries for unprocessed keys.
-
-KMS plaintext caches reduce repeated decrypt calls.
-A cache hit does not bypass live key and deletion checks.
+Reads use strongly consistent `BatchGetItem` requests with bounded retries for unprocessed keys and for a throttled request.
+A retry stops when the caller's deadline expires.
+
+Ingestion holds a usable session key row and image key row in the process, and a KMS plaintext cache reduces repeated decrypt calls.
+A row with no wrapped key is never held, so a repaired row is seen at once.
+A team block row is held once a read finds one, because nothing clears a block. Only a row that exists is ever held, so the cache holds "blocked" and never "not blocked": a team with no block is read from DynamoDB on every batch, and a block takes effect on the next one.
+A tombstone is held, because a shred only ever sets one and a conditional put cannot overwrite a row that exists, so a deleted session stops costing a read and a refused write on every batch.
+A session key deleted out of band stays usable in a process that already read it, until that entry expires.
+`ROW_CACHE_LIFETIME_MS` therefore sets how soon ingestion observes a session deletion.
+A team image key is one row per team per month, so it is held far longer than a session key: it survives eviction, and a short lifetime only buys re-reads.
+Data written under such a key stays unreadable, because the envelope stores no wrapped key and the stored row is a tombstone.
+Training readers do not use this cache.
Each process limits KMS concurrency and request rate; deployment capacity must account for the sum across replicas.
Readers check live state before each batch and permit key use for at most five minutes from the start of that read.
An expired read must obtain permission again.
@@ -188,7 +196,8 @@ Their HMAC key must remain stable while that data is in use.
New key manager and v2 storage settings use the `AI_RESEARCH_REPLAY_*` prefix:
- `KEY_TABLE`, `KMS_KEY_ARN`, and `AWS_REGION` select the key store and wrapping key.
-- `KEY_CACHE_MAX`, `KEY_CACHE_LIFETIME_MS`, and `KMS_REQUESTS_PER_SECOND` bound ingestion key caching and KMS traffic.
+- `KEY_CACHE_MAX`, `KEY_CACHE_LIFETIME_MS`, and `KMS_REQUESTS_PER_SECOND` bound the KMS plaintext cache and KMS traffic.
+- `ROW_CACHE_MAX` and `ROW_CACHE_LIFETIME_MS` bound the stored key row cache. The lifetime applies to a session key row and is capped; a team image key row is held for up to 48 hours. A value that is not a positive integer stops the consumer at startup and names the setting.
- `IMAGE_FETCH_V2_DYNAMODB_TABLE` selects the fresh v2 frontier.
- `S3_PREFIX` selects v2 replay storage and defaults to `rrweb_2`.