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 ml key commit conflicts with a jittered backoff (#101089)

Robbie9e2cfc2347db
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.test.ts
index 0cf91b62b060..2c6245448d90 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.test.ts
@@ -1,4 +1,9 @@
-import { BatchGetItemCommand, DynamoDBClient, TransactWriteItemsCommand } from '@aws-sdk/client-dynamodb'
+import {
+ BatchGetItemCommand,
+ DynamoDBClient,
+ TransactWriteItemsCommand,
+ TransactionCanceledException,
+} from '@aws-sdk/client-dynamodb'
import { GenerateDataKeyCommand, KMSClient } from '@aws-sdk/client-kms'
import { S3Client } from '@aws-sdk/client-s3'
import { Message } from 'node-rdkafka'
@@ -153,6 +158,66 @@ describe('ML session key batches', () => {
expect(boundary.transactionConflicts).toBe(0)
})
+ it.each([
+ ['survives', 7, true],
+ ['gives up after', 10, false],
+ ])('%s %i consecutive transaction conflicts on commit', async (_label, conflicts, succeeds) => {
+ const send = boundary.send.bind(boundary)
+ let remaining = conflicts
+ jest.spyOn(boundary, 'send').mockImplementation((command) => {
+ if (command instanceof TransactWriteItemsCommand && remaining > 0) {
+ remaining -= 1
+ return Promise.reject(
+ new TransactionCanceledException({
+ $metadata: {},
+ message: 'Transaction cancelled',
+ CancellationReasons: [{ Code: 'TransactionConflict' }],
+ })
+ )
+ }
+ return send(command)
+ })
+ const batch = await store.prepare([session])
+ jest.useFakeTimers()
+ const settled = batch.commit().then(
+ () => 'committed',
+ () => 'failed'
+ )
+ await jest.runAllTimersAsync()
+ expect(await settled).toBe(succeeds ? 'committed' : 'failed')
+ expect(boundary.items.has(tableKeyString(sessionKeyId(session.teamId, session.sessionId)))).toBe(succeeds)
+ })
+
+ it('gives up when the commit budget is spent before the attempts are', async () => {
+ const send = boundary.send.bind(boundary)
+ let remaining = 7
+ let slowReads = false
+ jest.spyOn(boundary, 'send').mockImplementation(async (command) => {
+ if (command instanceof TransactWriteItemsCommand && remaining > 0) {
+ remaining -= 1
+ throw new TransactionCanceledException({
+ $metadata: {},
+ message: 'Transaction cancelled',
+ CancellationReasons: [{ Code: 'TransactionConflict' }],
+ })
+ }
+ if (command instanceof BatchGetItemCommand && slowReads) {
+ await new Promise((resolve) => setTimeout(resolve, 20_000))
+ }
+ return send(command)
+ })
+ const batch = await store.prepare([session])
+ slowReads = true
+ jest.useFakeTimers()
+ const settled = batch.commit().then(
+ () => 'committed',
+ () => 'failed'
+ )
+ await jest.runAllTimersAsync()
+ expect(await settled).toBe('failed')
+ expect(remaining).toBeGreaterThan(0)
+ })
+
it('indexes monthly keys atomically and blocks a month during a competing batch', async () => {
const october = { ...session, sessionId: '0199a13b-c000-7000-8000-000000000007' }
const first = await store.prepare([session, october])
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.ts
index 22e4ece23946..e8051a0345ed 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.ts
@@ -1,5 +1,6 @@
-import { TransactWriteItem } from '@aws-sdk/client-dynamodb'
+import { TransactWriteItem, TransactionCanceledException } from '@aws-sdk/client-dynamodb'
+import { logger } from '~/common/utils/logger'
import { sessionStartMonth } from '~/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format'
import { MlDataKey, MlKeyEncryption } from './crypto'
@@ -17,6 +18,25 @@ import {
teamBlockId,
} from './schema'
+// The month and team block markers are single items that every commit in the fleet checks, so DynamoDB cancels concurrent commits as TransactionConflict under normal load. The budget counts the re-reads as well as the waits and stays under the consumer's 60 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
+
+function commitRetryDelayMs(attempt: number): number {
+ return Math.random() * Math.min(COMMIT_BACKOFF_CAP_MS, COMMIT_BACKOFF_BASE_MS * 2 ** attempt)
+}
+
+function cancellationCodes(error: unknown): string[] {
+ if (!(error instanceof TransactionCanceledException)) {
+ return []
+ }
+ return (error.CancellationReasons ?? []).flatMap((reason) =>
+ reason.Code && reason.Code !== 'None' ? [reason.Code] : []
+ )
+}
+
export interface MlSessionKeys {
session: MlDataKey
image: MlDataKey
@@ -229,7 +249,8 @@ export class MlKeyBatch {
if (this.committed) {
throw new Error('ML batch already committed')
}
- for (let attempt = 0; attempt < 5; attempt++) {
+ const startedAt = Date.now()
+ for (let attempt = 0; attempt < COMMIT_ATTEMPTS; attempt++) {
try {
await this.persist()
for (const key of this.keys.values()) {
@@ -238,10 +259,16 @@ export class MlKeyBatch {
this.committed = true
return
} catch (error) {
- if (attempt === 4) {
+ const delayMs = commitRetryDelayMs(attempt)
+ if (attempt === COMMIT_ATTEMPTS - 1 || Date.now() - startedAt + delayMs > COMMIT_BUDGET_MS) {
throw error
}
- await this.db.backoff(attempt)
+ logger.warn('🔑', 'ml_key_commit_retry', {
+ attempt: attempt + 1,
+ codes: cancellationCodes(error),
+ error: String(error),
+ })
+ await new Promise((resolve) => setTimeout(resolve, delayMs))
await this.read()
}
}