:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ai-research): commit ML keys with conditional puts instead of transactions (#101167)
Robbie6b85175838e4
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/dynamodb.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/dynamodb.tsindex a068d6cc3ad4..900e97ec3f3f 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/dynamodb.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/dynamodb.ts@@ -1,9 +1,9 @@import {AttributeValue,BatchGetItemCommand,+ ConditionalCheckFailedException,DynamoDBClient,- TransactWriteItem,- TransactWriteItemsCommand,+ PutItemCommand,} from '@aws-sdk/client-dynamodb'import pLimit from 'p-limit'@@ -24,6 +24,7 @@ export function decodeKey(item: DynamoItem): TableKey {export class MlPrivacyDynamoDB {private readonly concurrency = pLimit(4)+ private readonly writeConcurrency = pLimit(32)constructor(private readonly client: Pick<DynamoDBClient, 'send'>,@@ -32,7 +33,7 @@ export class MlPrivacyDynamoDB {private readonly attempts = 5) {}- public async read(keys: TableKey[]): Promise<Map<string, DynamoItem>> {+ public async read(keys: TableKey[], deadline?: AbortSignal): Promise<Map<string, DynamoItem>> {const unique = [...new Map(keys.map((key) => [tableKeyString(key), key])).values()]const result = new Map<string, DynamoItem>()const chunks: TableKey[][] = []@@ -48,7 +49,7 @@ export class MlPrivacyDynamoDB {new BatchGetItemCommand({RequestItems: { [this.tableName]: { Keys: pending, ConsistentRead: true } },}),- { abortSignal: AbortSignal.timeout(this.requestTimeoutMs) }+ { abortSignal: this.requestSignal(deadline) })for (const item of response.Responses?.[this.tableName] ?? []) {result.set(tableKeyString(decodeKey(item)), item)@@ -67,33 +68,44 @@ export class MlPrivacyDynamoDB {return result}- public async write(transactions: TransactWriteItem[][]): Promise<void> {- await Promise.all(- transactions.map((items) =>- this.concurrency(async () => {- if (!items.length || items.length > 100) {- throw new Error('Invalid ML privacy transaction size')- }- await this.client.send(new TransactWriteItemsCommand({ TransactItems: items }), {- abortSignal: AbortSignal.timeout(this.requestTimeoutMs),- })- })+ public async putIfAbsent(key: TableKey, attributes: DynamoItem, deadline?: AbortSignal): Promise<boolean> {+ return this.writeConcurrency(async () => {+ try {+ await this.client.send(+ new PutItemCommand({+ TableName: this.tableName,+ Item: { ...encodeKey(key), ...attributes },+ ConditionExpression: 'attribute_not_exists(pk)',+ }),+ { abortSignal: this.requestSignal(deadline) }+ )+ return true+ } catch (error) {+ if (error instanceof ConditionalCheckFailedException) {+ return false+ }+ throw error+ }+ })+ }++ public async put(key: TableKey, attributes: DynamoItem, deadline?: AbortSignal): Promise<void> {+ await this.writeConcurrency(() =>+ this.client.send(+ new PutItemCommand({ TableName: this.tableName, Item: { ...encodeKey(key), ...attributes } }),+ {+ abortSignal: this.requestSignal(deadline),+ }))}- public async backoff(attempt: number): Promise<void> {- await new Promise((resolve) => setTimeout(resolve, Math.min(1000, 50 * 2 ** attempt) + Math.random() * 50))+ private requestSignal(deadline?: AbortSignal): AbortSignal {+ const timeout = AbortSignal.timeout(this.requestTimeoutMs)+ return deadline ? AbortSignal.any([deadline, timeout]) : timeout}- public check(key: TableKey, condition: string, values?: DynamoItem): TransactWriteItem {- return {- ConditionCheck: {- TableName: this.tableName,- Key: encodeKey(key),- ConditionExpression: condition,- ...(values ? { ExpressionAttributeValues: values } : {}),- },- }+ public async backoff(attempt: number): Promise<void> {+ await new Promise((resolve) => setTimeout(resolve, Math.min(1000, 50 * 2 ** attempt) + Math.random() * 50))}}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.tsindex 56c6795a2d36..2004f9eb8ca8 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,8 +1,8 @@import {BatchGetItemCommand,+ ConditionalCheckFailedException,DynamoDBClient,- TransactWriteItemsCommand,- TransactionCanceledException,+ PutItemCommand,} from '@aws-sdk/client-dynamodb'import { GenerateDataKeyCommand, KMSClient } from '@aws-sdk/client-kms'import { S3Client } from '@aws-sdk/client-s3'@@ -31,14 +31,17 @@ const session: MlSessionIdentity = {}const table = 'ml-privacy-test'+function transientError(name: string): Error {+ return Object.assign(new Error(name), { name })+}+class DynamoBoundary {public readonly items = new Map<string, DynamoItem>()public readSizes: number[] = []- public writeSizes: number[] = []- public transactionConflicts = 0- private readonly pendingWrites = new Set<string>()+ public writes = 0+ public conditionalFailures = 0- public async send(command: BatchGetItemCommand | TransactWriteItemsCommand): Promise<object> {+ public async send(command: BatchGetItemCommand | PutItemCommand): Promise<object> {if (command instanceof BatchGetItemCommand) {const keys = command.input.RequestItems![table].Keys!if (keys.some((key) => Buffer.byteLength(key.sk.S!) > 1024)) {@@ -54,44 +57,16 @@ class DynamoBoundary {},})}- const actions = command.input.TransactItems!- const writes = actions.flatMap((action) =>- action.Put ? [JSON.stringify([action.Put.Item!.pk.S, action.Put.Item!.sk.S])] : []- )- if (writes.some((key) => this.pendingWrites.has(key))) {- this.transactionConflicts += 1- throw new Error('Conflicting transaction write')- }- writes.forEach((key) => this.pendingWrites.add(key))- try {- await Promise.resolve()- this.writeSizes.push(actions.length)- for (const action of actions) {- const operation = action.ConditionCheck ?? action.Put!- const key = 'Item' in operation ? operation.Item! : operation.Key!- const current = this.items.get(JSON.stringify([key.pk.S, key.sk.S]))- const condition = operation.ConditionExpression- const valid =- !condition ||- (condition === 'attribute_not_exists(pk)'- ? !current- : condition === 'attribute_exists(wrapped_key) AND attribute_not_exists(deleted)'- ? current?.wrapped_key?.B && !current?.deleted- : false)- if (!valid) {- throw new Error('Conditional transaction failed')- }- }- for (const action of actions) {- if (action.Put) {- const item = action.Put.Item!- this.items.set(JSON.stringify([item.pk.S, item.sk.S]), item)- }- }- return {}- } finally {- writes.forEach((key) => this.pendingWrites.delete(key))+ const item = command.input.Item!+ const id = JSON.stringify([item.pk.S, item.sk.S])+ this.writes += 1+ 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' })}+ this.items.set(id, item)+ return {}}}@@ -138,11 +113,11 @@ describe('ML session key batches', () => {await batch.commit()expect(boundary.items.size).toBe(4)expect(Math.max(...boundary.readSizes)).toBeLessThanOrEqual(100)- expect(Math.max(...boundary.writeSizes)).toBeLessThanOrEqual(100)+ expect(boundary.writes).toBe(4)expect((await reader.read([sessionKeyId(session.teamId, session.sessionId)])).size).toBe(1)})- it('commits concurrent new sessions in bounded transactions', async () => {+ it('commits concurrent new sessions without conditional failures', async () => {await (await store.prepare([session])).commit()const identities = Array.from({ length: 120 }, (_, index) => ({...session,@@ -155,25 +130,23 @@ describe('ML session key batches', () => {await committedconst keys = await reader.read(identities.map((identity) => sessionKeyId(identity.teamId, identity.sessionId)))expect(keys.size).toBe(identities.length)- expect(boundary.transactionConflicts).toBe(0)+ expect(boundary.conditionalFailures).toBe(0)})it.each([['survives', 7, true],['gives up after', 10, false],- ])('%s %i consecutive transaction conflicts on commit', async (_label, conflicts, succeeds) => {+ ])('%s %i consecutive write failures on commit', async (_label, failures, succeeds) => {const send = boundary.send.bind(boundary)- let remaining = conflicts+ let remaining = failuresjest.spyOn(boundary, 'send').mockImplementation((command) => {- if (command instanceof TransactWriteItemsCommand && remaining > 0) {+ if (+ command instanceof PutItemCommand &&+ command.input.Item!.sk.S!.startsWith('session:') &&+ remaining > 0+ ) {remaining -= 1- return Promise.reject(- new TransactionCanceledException({- $metadata: {},- message: 'Transaction cancelled',- CancellationReasons: [{ Code: 'TransactionConflict' }],- })- )+ return Promise.reject(transientError('ProvisionedThroughputExceededException'))}return send(command)})@@ -188,18 +161,74 @@ describe('ML session key batches', () => {expect(boundary.items.has(tableKeyString(sessionKeyId(session.teamId, session.sessionId)))).toBe(succeeds)})+ it('fails fast on a non-retryable write error', async () => {+ const send = boundary.send.bind(boundary)+ jest.spyOn(boundary, 'send').mockImplementation((command) =>+ command instanceof PutItemCommand ? Promise.reject(transientError('ValidationException')) : send(command)+ )+ const batch = await store.prepare([session])+ await expect(batch.commit()).rejects.toThrow('ValidationException')+ expect(boundary.writes).toBeLessThanOrEqual(2)+ })++ 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+ jest.spyOn(boundary, 'send').mockImplementation((command) => {+ if (command instanceof PutItemCommand && command.input.Item!.pk.S!.startsWith('month:') && remaining > 0) {+ remaining -= 1+ return Promise.reject(transientError('ProvisionedThroughputExceededException'))+ }+ return send(command)+ })+ const batch = await store.prepare([session])+ jest.useFakeTimers()+ const committing = batch.commit()+ await jest.runAllTimersAsync()+ await committing+ const location = sessionKeyId(session.teamId, session.sessionId)+ expect(boundary.items.has(tableKeyString(location))).toBe(true)+ expect(boundary.items.has(tableKeyString(monthKeyIndexId({ ...session }, location)))).toBe(true)+ })++ it('keeps its own key when a retried put reports it as already stored', async () => {+ const send = boundary.send.bind(boundary)+ let lostResponses = 1+ jest.spyOn(boundary, 'send').mockImplementation(async (command) => {+ const result = await send(command)+ if (+ command instanceof PutItemCommand &&+ command.input.Item!.sk.S!.startsWith('session:') &&+ lostResponses > 0+ ) {+ lostResponses -= 1+ throw Object.assign(new Error('socket hang up'), { code: 'ECONNRESET' })+ }+ return result+ })+ const batch = await store.prepare([session])+ const candidate = batch.get(session.teamId, session.sessionId)!.session.plaintext+ jest.useFakeTimers()+ const committing = batch.commit()+ await jest.runAllTimersAsync()+ await committing+ expect(batch.get(session.teamId, session.sessionId)!.session.plaintext).toEqual(candidate)+ const location = sessionKeyId(session.teamId, session.sessionId)+ expect(boundary.items.has(tableKeyString(monthKeyIndexId({ ...session }, location)))).toBe(true)+ })+it('gives up when the commit budget is spent before the attempts are', async () => {const send = boundary.send.bind(boundary)let remaining = 7let slowReads = falsejest.spyOn(boundary, 'send').mockImplementation(async (command) => {- if (command instanceof TransactWriteItemsCommand && remaining > 0) {+ if (+ command instanceof PutItemCommand &&+ command.input.Item!.sk.S!.startsWith('session:') &&+ remaining > 0+ ) {remaining -= 1- throw new TransactionCanceledException({- $metadata: {},- message: 'Transaction cancelled',- CancellationReasons: [{ Code: 'TransactionConflict' }],- })+ throw transientError('ProvisionedThroughputExceededException')}if (command instanceof BatchGetItemCommand && slowReads) {await new Promise((resolve) => setTimeout(resolve, 20_000))@@ -218,7 +247,7 @@ describe('ML session key batches', () => {expect(remaining).toBeGreaterThan(0)})- it('indexes monthly keys atomically, ignores a month marker, and blocks on a team marker', async () => {+ it('indexes monthly keys, ignores a month marker, and blocks on a team marker set during a batch', async () => {const october = { ...session, sessionId: '0199a13b-c000-7000-8000-000000000007' }const first = await store.prepare([session, october])await first.commit()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.tsindex 47ba3c936e98..529a64683cff 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,10 +1,8 @@-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'-import { DynamoItem, MlPrivacyDynamoDB, encodeKey } from './dynamodb'+import { DynamoItem, MlPrivacyDynamoDB } from './dynamodb'import {MlKeyIdentity,MlSessionIdentity,@@ -17,25 +15,42 @@ import {teamBlockId,} from './schema'-// Every commit for a team checks the same team block marker, so DynamoDB cancels concurrent commits for one team 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.+// Commits retry transient DynamoDB and KMS failures; 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 = 10const COMMIT_BUDGET_MS = 45_000const COMMIT_BACKOFF_BASE_MS = 100const 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)}-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: MlDataKeyimage: MlDataKey@@ -47,47 +62,6 @@ function storedKeyId(identity: MlKeyIdentity): TableKey {: imageKeyId(identity.teamId, keySessionMonth(identity))}-function actionId(action: TransactWriteItem): string {- const operation = action.ConditionCheck ?? action.Put ?? action.Update ?? action.Delete- if (!operation) {- throw new Error('Empty ML privacy transaction action')- }- const key = 'Item' in operation ? operation.Item : 'Key' in operation ? operation.Key : undefined- if (!key?.pk?.S || !key.sk?.S) {- throw new Error('Missing ML privacy transaction key')- }- return JSON.stringify([key.pk.S, key.sk.S])-}--export function groupTransactions(units: TransactWriteItem[][]): TransactWriteItem[][] {- const transactions: TransactWriteItem[][] = []- let current = new Map<string, TransactWriteItem>()- for (const unit of units) {- const next = new Map(current)- for (const action of unit) {- const id = actionId(action)- const existing = next.get(id)- if (existing && JSON.stringify(existing) !== JSON.stringify(action)) {- throw new Error('Conflicting ML privacy transaction actions')- }- next.set(id, action)- }- if (next.size > 100 || Buffer.byteLength(JSON.stringify([...next.values()])) > 3_500_000) {- if (!current.size) {- throw new Error('ML privacy transaction unit exceeds limits')- }- transactions.push([...current.values()])- current = new Map(unit.map((action) => [actionId(action), action]))- } else {- current = next- }- }- if (current.size) {- transactions.push([...current.values()])- }- return transactions-}-export class MlSessionKeyStore {constructor(private readonly db: MlPrivacyDynamoDB,@@ -121,13 +95,13 @@ export class MlKeyBatch {private readonly identities: MlSessionIdentity[]) {}- public async read(): Promise<void> {+ public async read(deadline?: AbortSignal): Promise<void> {this.keys.clear()const initial = this.identities.flatMap((identity) => [teamBlockId(identity.teamId),sessionKeyId(identity.teamId, identity.sessionId),])- this.state = await this.db.read(initial)+ this.state = await this.db.read(initial, deadline)const keyIdentities = new Map<string, MlKeyIdentity>()for (const identity of this.identities) {const id = tableKeyString(sessionKeyId(identity.teamId, identity.sessionId))@@ -147,7 +121,7 @@ export class MlKeyBatch {}}const remaining = [...keyIdentities.values()].filter((identity) => !identity.sessionId).map(storedKeyId)- for (const [id, item] of await this.db.read(remaining)) {+ for (const [id, item] of await this.db.read(remaining, deadline)) {this.state.set(id, item)}await Promise.all(@@ -183,61 +157,45 @@ export class MlKeyBatch {return image ? { session, image } : undefined}- // The pipeline drops sessions older than the month deletion grace period, so a commit fences on the team marker alone; a month marker would be one item every commit in the fleet contends on.- private guards(identity: MlKeyIdentity): TransactWriteItem[] {- return [this.db.check(teamBlockId(identity.teamId), 'attribute_not_exists(pk)')]- }-- private put(key: TableKey, attributes: DynamoItem, condition?: string): TransactWriteItem {- return {- Put: {- TableName: this.db.tableName,- Item: { ...encodeKey(key), ...attributes },- ...(condition ? { ConditionExpression: condition } : {}),- },- }- }-- private async persist(): Promise<void> {- const creations: TransactWriteItem[][] = []- for (const [id, key] of this.keys) {- if (this.state.has(id)) {- continue- }- creations.push([- ...this.guards(key.identity),- this.put(- storedKeyId(key.identity),+ // 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()]+ const results = await Promise.allSettled(+ [...this.keys].map(async ([id, key]) => {+ if (this.state.has(id)) {+ return+ }+ const location = storedKeyId(key.identity)+ await this.db.put(+ monthKeyIndexId(key.identity, location),+ { key_pk: { S: location.pk }, key_sk: { S: location.sk } },+ deadline+ )+ const created = await this.db.putIfAbsent(+ location,{wrapped_key: { B: key.wrapped },organization_id: { S: key.identity.organizationId },team_id: { N: String(key.identity.teamId) },session_month: { S: keySessionMonth(key.identity) },},- 'attribute_not_exists(pk)'- ),- this.put(monthKeyIndexId(key.identity, storedKeyId(key.identity)), {- key_pk: { S: storedKeyId(key.identity).pk },- key_sk: { S: storedKeyId(key.identity).sk },- }),- ])+ deadline+ )+ if (created) {+ this.encryption.rememberCommitted(key)+ }+ })+ )+ const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected')+ const failure = failures.find(({ reason }) => !isTransientError(reason)) ?? failures[0]+ if (failure) {+ throw failure.reason}- await this.db.write(groupTransactions(creations))- const validations: TransactWriteItem[][] = []- for (const identity of this.identities) {- const key = this.get(identity.teamId, identity.sessionId)?.session- if (!key) {- continue- }- validations.push([- ...this.guards(key.identity),- this.db.check(- sessionKeyId(identity.teamId, identity.sessionId),- 'attribute_exists(wrapped_key) AND attribute_not_exists(deleted)'- ),- ])+ await this.read(deadline)+ const dropped = before.filter((id) => !this.keys.has(id)).length+ if (dropped) {+ logger.info('🔑', 'ml_key_commit_dropped_blocked', { dropped })}- await this.db.write(groupTransactions(validations))}public async commit(): Promise<void> {@@ -245,26 +203,29 @@ export class MlKeyBatch {throw new Error('ML batch already committed')}const startedAt = Date.now()+ const deadline = AbortSignal.timeout(COMMIT_BUDGET_MS)for (let attempt = 0; attempt < COMMIT_ATTEMPTS; attempt++) {try {- await this.persist()- for (const key of this.keys.values()) {- this.encryption.rememberCommitted(key)- }+ await this.persist(deadline)this.committed = truereturn} catch (error) {const delayMs = commitRetryDelayMs(attempt)- if (attempt === COMMIT_ATTEMPTS - 1 || Date.now() - startedAt + delayMs > COMMIT_BUDGET_MS) {+ if (+ !isTransientError(error) ||+ deadline.aborted ||+ attempt === COMMIT_ATTEMPTS - 1 ||+ Date.now() - startedAt + delayMs > COMMIT_BUDGET_MS+ ) {throw error}logger.warn('🔑', 'ml_key_commit_retry', {attempt: attempt + 1,- codes: cancellationCodes(error),+ errorName: error instanceof Error ? error.name : undefined,error: String(error),})await new Promise((resolve) => setTimeout(resolve, delayMs))- await this.read()+ await this.read(deadline)}}}diff --git a/products/ai_training/backend/privacy/store.py b/products/ai_training/backend/privacy/store.pyindex e4b4c3b7ef63..e40d5a8534c7 100644--- a/products/ai_training/backend/privacy/store.py+++ b/products/ai_training/backend/privacy/store.py@@ -22,6 +22,8 @@ logger = structlog.get_logger(__name__)KEY_SHARDS = 32# Equals ML_SESSION_MAX_AGE_DAYS in nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format.ts: ingestion drops sessions that started earlier than that, so no key for a month can appear after the month end plus this period.MONTH_DELETE_GRACE_DAYS = 14+# A batch admitted just inside the grace period still commits within its 45 s budget, so deletion stays behind that too.+MONTH_DELETE_IN_FLIGHT_MARGIN = timedelta(hours=1)DynamoItem = dict[str, dict[str, str | bool | bytes]]@@ -87,13 +89,15 @@ class AITrainingPrivacyStore:if re.fullmatch(r"[0-9]{4}-(0[1-9]|1[0-2])", session_month) is None:raise ValueError("Session month must use YYYY-MM")try:- deletable_from = month_end(session_month) + timedelta(days=MONTH_DELETE_GRACE_DAYS)+ deletable_from = (+ month_end(session_month) + timedelta(days=MONTH_DELETE_GRACE_DAYS) + MONTH_DELETE_IN_FLIGHT_MARGIN+ )except ValueError as error:raise ValueError("Session month must use YYYY-MM") from errorif timezone.now() < deletable_from:raise ValueError(- f"Session month {session_month} can be deleted from {deletable_from:%Y-%m-%d}, "- f"{MONTH_DELETE_GRACE_DAYS} days after the month ends"+ f"Session month {session_month} can be deleted from {deletable_from:%Y-%m-%d %H:%M} UTC, "+ f"{MONTH_DELETE_GRACE_DAYS} days and one hour after the month ends")count = 0for shard in range(KEY_SHARDS):@@ -169,27 +173,32 @@ class AITrainingPrivacyStore:work = request.cursor.get("work")if work is None:work = self.initialize(request)- request.cursor = {"work": work}- request.save(update_fields=["cursor"])+ self.save_cursor(request, work=work)while work:if time.monotonic() >= deadline:return Falsework = self.advance(work[0]) + work[1:]- request.cursor = {"work": work}- request.save(update_fields=["cursor"])+ self.save_cursor(request, work=work)now = timezone.now()complete_after = request.cursor.get("complete_after")if complete_after is None:- request.cursor = {"work": [], "complete_after": now.timestamp() + KEY_READ_LEASE_SECONDS}- request.save(update_fields=["cursor"])+ self.save_cursor(request, work=[], complete_after=now.timestamp() + KEY_READ_LEASE_SECONDS)return Falseif now.timestamp() < complete_after:return False+ # Key creation checks the team block only when it reads the batch, so a batch that read before the block can still store a key within its commit budget; the lease outlasts that budget, so one more sweep after it catches every straggler.+ if request.kind == "team" and not request.cursor.get("reswept"):+ self.save_cursor(request, work=[{"op": "team", "team_id": request.team_id, "shard": -1}], reswept=True)+ return self.apply(request, deadline)request.completed_at = nowrequest.identifiers = []request.save(update_fields=["completed_at", "identifiers"])return True+ def save_cursor(self, request: AITrainingDeletionRequest, **fields: object) -> None:+ request.cursor = {**request.cursor, **fields}+ request.save(update_fields=["cursor"])+def drain(self, limit: int = 100, budget_seconds: int = 240) -> int:deadline = time.monotonic() + budget_secondscompleted = 0diff --git a/products/ai_training/backend/tests/test_privacy_store.py b/products/ai_training/backend/tests/test_privacy_store.pyindex c2be6b21469b..940f26f5a150 100644--- a/products/ai_training/backend/tests/test_privacy_store.py+++ b/products/ai_training/backend/tests/test_privacy_store.py@@ -64,13 +64,15 @@ class TestAITrainingPrivacyStore(SimpleTestCase):@parameterized.expand([- ("2025-09", "2025-10-14T23:59:59+00:00", False),- ("2025-09", "2025-10-15T00:00:00+00:00", True),- ("2025-12", "2026-01-14T23:59:59+00:00", False),- ("2025-12", "2026-01-15T00:00:00+00:00", True),+ ("2025-09", "2025-10-15T00:59:59+00:00", False),+ ("2025-09", "2025-10-15T01:00:00+00:00", True),+ ("2025-12", "2026-01-15T00:59:59+00:00", False),+ ("2025-12", "2026-01-15T01:00:00+00:00", True),])- def test_month_deletion_opens_fourteen_days_after_the_month_ends(self, month: str, now: str, allowed: bool) -> None:+ def test_month_deletion_opens_fourteen_days_and_one_hour_after_the_month_ends(+ self, month: str, now: str, allowed: bool+ ) -> None:client = MagicMock()client.query.return_value = {"Items": []}store = AITrainingPrivacyStore(client, "table")@@ -96,15 +98,19 @@ class TestAITrainingPrivacyStore(SimpleTestCase):)client.query.assert_not_called()- def test_completion_waits_for_reader_leases_without_sleeping_in_the_worker(self) -> None:- request = MagicMock(kind="team", cursor={"work": []}, completed_at=None)- store = AITrainingPrivacyStore(MagicMock(), "table")+ def test_completion_waits_for_reader_leases_then_sweeps_the_team_once_more(self) -> None:+ request = MagicMock(kind="team", team_id=7, cursor={"work": []}, completed_at=None)+ client = MagicMock()+ client.query.return_value = {"Items": []}+ store = AITrainingPrivacyStore(client, "table")now = timezone.now()with patch("products.ai_training.backend.privacy.store.timezone.now", return_value=now):self.assertFalse(store.apply(request, time.monotonic() + 1))self.assertIsNone(request.completed_at)+ client.query.assert_not_called()with patch("products.ai_training.backend.privacy.store.timezone.now", return_value=now + timedelta(seconds=301)):self.assertTrue(store.apply(request, time.monotonic() + 1))+ self.assertEqual(client.query.call_count, 33)self.assertEqual(request.identifiers, [])diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.mdindex e26d66b6c5db..3da9e460139e 100644--- a/products/ai_training/docs/replay-data.md+++ b/products/ai_training/docs/replay-data.md@@ -46,12 +46,13 @@ Ingestion processes privacy state in batches:1. Bulk-read session keys, team blocks, and image keys.2. Resolve keys in memory while processing the batch.-3. Commit bounded DynamoDB transactions before publishing replay blocks or image messages.-4. On a competing write, bulk-read the winning state and retry with its keys.+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.-Conditional writes prevent a deletion from being undone by an in-flight batch.+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.Kafka offsets advance only after the required writes and publication succeed.-DynamoDB transactions have at most 100 actions and stay below the request size limit.+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.@@ -102,12 +103,14 @@ Legacy dataset retirement needs a separate storage operation before claiming del## Monthly key deletion-Key creation writes a month index entry in the same DynamoDB transaction as the wrapped key.+Key creation writes the month index entry with a plain put, then the wrapped key with a conditional put.+The index entry comes first, so every stored key has an index entry.+An index entry without a key is harmless: the month sweep leaves a tombstone that a later key put respects.The index uses 32 partitions named `month:<YYYY-MM>:shard:<0..31>` and stores key locations, without copying wrapped keys.Session keys and image keys appear in this index.Run `python manage.py delete_ai_training_month YYYY-MM` to remove the keys of that UTC session month.-The mirror drops a session whose ID started more than 14 days in the past or more than 1 day in the future, and the command accepts a month from 14 days after the month ends, so a key cannot arrive after its index shard was swept.+The mirror drops a session whose ID started more than 14 days in the past or more than 1 day in the future, and the command accepts a month from 14 days and one hour after the month ends, so a batch admitted just inside the limit cannot commit a key after its index shard was swept.Neither side reads a shared block item for the month, because every commit in the fleet would contend on that one DynamoDB item.The command uses strongly consistent queries and bounded writes.Rerun the command after an interrupted run; it safely repeats completed pages.