: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): drop the ML key block, read lease and second sweep (#102879)
Robbie0c56698cfeda
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/dynamodb.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/dynamodb.tsindex 030af0326608..96ac027dcde0 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/dynamodb.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/dynamodb.ts@@ -14,13 +14,11 @@ import { MlKeyRequest, MlMirrorMetrics } from '~/ingestion/pipelines/sessionreplimport { 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.+// A shred removes the durable key, so a process that runs on a held row writes data that no reader can open, and a+// lifetime here trades re-reads against how long that lasts. A team row is one row per team per month, so it is held+// longer for far fewer reads. Both kinds cover their tombstones too. See products/ai_training/docs/replay-data.md.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+const TEAM_ROW_LIFETIME_MS = 3_600_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@@ -83,8 +81,7 @@ export class MlKeyDynamoDB {})}- // 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.+ // Only a usable key row is stable enough to cache, because putIfAbsent writes it once.private cacheable(key: TableKey): boolean {return holdsCacheableRow(key)}@@ -94,16 +91,15 @@ export class MlKeyDynamoDB {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 || (item.sealed_key?.B && item.key_nonce?.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.+ const usable = item.deleted?.BOOL === true || item.wrapped_key?.B || (item.sealed_key?.B && item.key_nonce?.B)+ if (!usable) {+ // No key and no tombstone is a row that repair can still fill in.this.rows.delete(id)+ return}+ this.rows.set(id, detachedRow(item), {+ ttl: storedSessionId(key.sk) ? this.sessionRowLifetimeMs : TEAM_ROW_LIFETIME_MS,+ })}public async read(keys: TableKey[], callerDeadline?: AbortSignal): Promise<Map<string, DynamoItem>> {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.tsindex b047a78790ff..8c31cfa215a4 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@@ -26,15 +26,7 @@ import { MlDataKey, MlKeyEncryption } from './crypto'import { DynamoItem, MlKeyDynamoDB, encodeKey } from './dynamodb'import { MlSessionKeyStore } from './key-store'import { MlKeyReader } from './reader'-import {- MlSessionIdentity,- TableKey,- imageKeyId,- monthKeyIndexId,- sessionKeyId,- tableKeyString,- teamBlockId,-} from './schema'+import { MlSessionIdentity, TableKey, imageKeyId, monthKeyIndexId, sessionKeyId, tableKeyString } from './schema'import { MlKafkaTransport, mlKafkaRecord } from './transport'const session: MlSessionIdentity = {@@ -220,15 +212,13 @@ describe('ML session key batches', () => {it('reads every row a batch needs in one pass', async () => {const readsBefore = boundary.readSizes.lengthawait store.prepare([session])- // The team block, the session key and the team image key are known up front, so they go in one request.+ // The session key and the team image key are known up front, so they go in one request.expect(boundary.readSizes.length - readsBefore).toBe(1)expect(new Set(boundary.readKeys.at(-1))).toEqual(new Set(- [- teamBlockId(session.teamId),- sessionKeyId(session.teamId, session.sessionId),- imageKeyId(session.teamId, '2025-09'),- ].map(tableKeyString)+ [sessionKeyId(session.teamId, session.sessionId), imageKeyId(session.teamId, '2025-09')].map(+ tableKeyString+ )))})@@ -430,7 +420,7 @@ describe('ML session key batches', () => {expect(remaining).toBeGreaterThan(0)})- it('indexes monthly keys, ignores a month marker, and refuses a team marker from the next read', async () => {+ it('indexes monthly keys and ignores a month marker', async () => {const october = { ...session, sessionId: '0199a13b-c000-7000-8000-000000000007' }const first = await store.prepare([session, october])await first.commit()@@ -461,18 +451,6 @@ describe('ML session key batches', () => {await committingDespiteMonthexpect(ignoringMonth.get(session.teamId, session.sessionId)).not.toBeUndefined()expect((await reader.read(locations)).size).toBe(4)- jest.useRealTimers()- const inFlight = await store.prepare([session])- const blocked = teamBlockId(session.teamId)- boundary.items.set(tableKeyString(blocked), { ...encodeKey(blocked), deleted: { BOOL: true } })- jest.useFakeTimers()- const committing = inFlight.commit()- await jest.runAllTimersAsync()- await committing- // 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 () => {@@ -644,16 +622,6 @@ describe('ML session key batches', () => {expect(mismatch.mock.calls).toEqual([['month_key_unavailable', 1]])})- it('counts no month key failure for a blocked team, so the metric stays a corruption signal', async () => {- await (await store.prepare([session])).commit()- const block = teamBlockId(session.teamId)- boundary.items.set(tableKeyString(block), { ...encodeKey(block), deleted: { BOOL: true } })- coldCache()- const mismatch = jest.spyOn(MlMirrorMetrics, 'incrementMlKeyIdentityMismatch')- expect((await reader.read([sessionKeyId(session.teamId, session.sessionId)])).size).toBe(0)- expect(mismatch).not.toHaveBeenCalled()- })-it('fails the read when KMS throttles a month key, so the caller retries instead of dropping', async () => {await (await store.prepare([session])).commit()coldCache()@@ -742,7 +710,7 @@ describe('ML session key batches', () => {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],+ ['a team image key is held past the session lifetime', 86_400_000, 300_001, true],])('%s', async (_label, configured, elapsedMs, imageKey) => {let fakeNow = 1_000const clock = jest.spyOn(performance, 'now').mockImplementation(() => fakeNow)@@ -769,21 +737,19 @@ describe('ML session key batches', () => {}})- it('refuses a blocked team on the next batch while its session row is still cached', async () => {+ it('stops a team month for good once its month key is shredded, so no block row is needed', 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 monthLocation = tableKeyString(imageKeyId(session.teamId, '2025-09'))+ const { wrapped_key: _shredded, ...tombstone } = boundary.items.get(monthLocation)!+ const shreddedRow = { ...tombstone, deleted: { BOOL: true } }+ boundary.items.set(monthLocation, shreddedRow)+ coldCache()+ const writesBefore = boundary.writesconst 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)+ await next.commit()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)+ expect(boundary.items.get(monthLocation)).toEqual(shreddedRow)+ expect(boundary.writes).toBe(writesBefore)})it('holds a session tombstone so a deleted session stops costing a read and a doomed write', async () => {@@ -800,8 +766,8 @@ describe('ML session key batches', () => {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)+ // The tombstone spares the session key row and the image key row, and no row is read at all.+ expect(boundary.readSizes.slice(readsBefore).reduce((total, size) => total + size, 0)).toBe(0)expect(boundary.writes).toBe(writesBefore)})@@ -857,8 +823,8 @@ describe('ML session key batches', () => {expect(keys.image.plaintext).toEqual(original.image.plaintext)expect((await reader.read([sessionKeyId(session.teamId, session.sessionId)])).size).toBe(1)expect(generated).toBe(1)- // Only the team block row, because it decides whether the batch may mint new keys and is never cached.- expect(keysRead).toBe(1)+ // Both rows come from the cache, so a batch that repeats a session reads nothing.+ expect(keysRead).toBe(0)})it('publishes only after key writes commit and hands delivery acks to the scheduler', async () => {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.tsindex c222f256ccb0..05038869e02f 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,7 +15,6 @@ import {monthKeyIndexId,sessionKeyId,tableKeyString,- teamBlockId,} from './schema'import { isTransientError } from './transient'@@ -84,7 +83,6 @@ export class MlKeyBatch {this.keys.clear()// The image key is the session's start month, so every row this batch needs is known before the first read.const initial = this.identities.flatMap((identity) => [- teamBlockId(identity.teamId),sessionKeyId(identity.teamId, identity.sessionId),imageKeyId(identity.teamId, sessionStartMonth(identity.sessionId)),])@@ -92,10 +90,7 @@ export class MlKeyBatch {const keyIdentities = new Map<string, MlKeyIdentity>()for (const identity of this.identities) {const id = tableKeyString(sessionKeyId(identity.teamId, identity.sessionId))- if (- this.state.has(tableKeyString(teamBlockId(identity.teamId))) ||- this.state.get(id)?.deleted?.BOOL === true- ) {+ if (this.state.get(id)?.deleted?.BOOL === true) {continue}for (const sessionId of [identity.sessionId, undefined]) {@@ -129,6 +124,7 @@ export class MlKeyBatch {}this.keys.set(id, stored)} else {+ // A shredded team image key stops its team month for good, which is why no team block row exists. See products/ai_training/docs/replay-data.md.if (identity.sessionId && !this.monthKeyFor(identity)) {this.reportUnusable(id, 'month_key_unavailable')returndiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader.tsindex d51938541bd2..5afb547dddf0 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader.ts@@ -3,15 +3,7 @@ import { MlMirrorMetrics } from '~/ingestion/pipelines/sessionreplay/ml-mirror/mimport { MlDataKey, MlKeyEncryption, openSessionKey } from './crypto'import { DynamoItem, MlKeyDynamoDB } from './dynamodb'-import {- MlKeyIdentity,- TableKey,- imageKeyId,- keySessionMonth,- storedSessionId,- tableKeyString,- teamBlockId,-} from './schema'+import { MlKeyIdentity, TableKey, imageKeyId, keySessionMonth, storedSessionId, tableKeyString } from './schema'import { isTransientError } from './transient'export class MlKeyReader {@@ -66,18 +58,14 @@ export class MlKeyReader {monthKeyOf.set(id, monthId)monthKeys.set(monthId, imageKeyId(identity.teamId, keySessionMonth(identity)))}- const state = await this.db.read([- ...[...identities.values()].map((identity) => teamBlockId(identity.teamId)),- ...monthKeys.values(),- ])- const blocked = (teamId: number): boolean => state.has(tableKeyString(teamBlockId(teamId)))+ const state = await this.db.read([...monthKeys.values()])const months = new Map<string, MlDataKey>()const refused: { id: string; error: string }[] = []- // A deleted month key and a blocked team are answers, not failures, so neither counts against the month key.let unavailable = 0await Promise.all([...monthKeys.keys()].map(async (id) => {const item = state.get(id)+ // A tombstoned month key is an answer, not a failure, so it does not count as unavailable. It also ends the month, because no reader can open the session keys that are sealed under it. See products/ai_training/docs/replay-data.md.if (item?.deleted?.BOOL === true) {return}@@ -86,11 +74,10 @@ export class MlKeyReader {return}try {- const identity = this.identityOf(item)- if (blocked(identity.teamId)) {- return- }- months.set(id, await this.encryption.decrypt(identity, Buffer.from(item.wrapped_key.B)))+ months.set(+ id,+ await this.encryption.decrypt(this.identityOf(item), Buffer.from(item.wrapped_key.B))+ )} catch (error) {// A throttled KMS must fail the read so the caller retries. A month key that can never open must not stall every session in the batch.if (isTransientError(error)) {@@ -110,9 +97,6 @@ export class MlKeyReader {const result = new Map<string, MlDataKey>()await Promise.all([...identities].map(async ([id, identity]) => {- if (blocked(identity.teamId)) {- return- }const item = stored.get(id)!if (item.sealed_key?.B && item.key_nonce?.B) {const monthId = monthKeyOf.get(id)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema.tsindex fd1a9198d48b..9324a4227b18 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema.ts@@ -36,7 +36,6 @@ export function sessionShard(sessionId: string): number {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_KEY_PREFIX}${sessionId}` }@@ -62,19 +61,14 @@ export function monthKeyIndexId(identity: MlKeyIdentity, key: TableKey): TableKe}// 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+ return key.sk.startsWith(SESSION_KEY_PREFIX) || key.sk.startsWith(IMAGE_KEY_PREFIX)}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: TEAM_BLOCK_SK }-}-export function tableKeyString(key: TableKey): string {return JSON.stringify([key.pk, key.sk])}diff --git a/products/ai_training/backend/management/commands/delete_ai_training_month.py b/products/ai_training/backend/management/commands/delete_ai_training_month.pyindex d83b805ca494..baa59cf5e02e 100644--- a/products/ai_training/backend/management/commands/delete_ai_training_month.py+++ b/products/ai_training/backend/management/commands/delete_ai_training_month.py@@ -4,7 +4,7 @@ from typing import Anyfrom django.core.management.base import BaseCommand, CommandErrorfrom products.ai_training.backend.config import key_table_name-from products.ai_training.backend.privacy.store import KEY_READ_LEASE_SECONDS, AITrainingPrivacyStore+from products.ai_training.backend.privacy.store import AITrainingPrivacyStoreclass Command(BaseCommand):@@ -20,6 +20,4 @@ class Command(BaseCommand):count = AITrainingPrivacyStore.from_settings().delete_month(options["session_month"])except ValueError as error:raise CommandError(str(error)) from error- self.stdout.write(- f"Removed {count} indexed keys. Existing read leases expire within {KEY_READ_LEASE_SECONDS} seconds."- )+ self.stdout.write(f"Removed {count} indexed keys. A reader that already cached a key can still use it.")diff --git a/products/ai_training/backend/privacy/store.py b/products/ai_training/backend/privacy/store.pyindex cb7804d844b4..3766b030f439 100644--- a/products/ai_training/backend/privacy/store.py+++ b/products/ai_training/backend/privacy/store.py@@ -19,8 +19,6 @@ from products.ai_training.backend.models import AITrainingDeletionRequestlogger = structlog.get_logger(__name__)KEY_SHARDS = 32-# Readers may use a key for this long after they read it, so deletion completes only after the lease has run out.-KEY_READ_LEASE_SECONDS = 300# 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.@@ -83,11 +81,6 @@ class AITrainingPrivacyStore:)return cls(cast(PrivacyDynamoClient, client), key_table_name())- def block(self, team_id: int) -> None:- self.client.put_item(- TableName=self.table_name, Item={**item_key(f"team:{team_id}", "deleted"), "deleted": {"BOOL": True}}- )-def delete_month(self, session_month: str) -> int: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")@@ -143,12 +136,20 @@ class AITrainingPrivacyStore:])+ # A sweep reaches only an image key that already exists, so a team that keeps sending would open a month the sweep never saw. Ingestion admits a session up to ML_SESSION_MAX_AGE_DAYS old, which is inside one month, so these three are every month a later session can still open. An update creates the row, so each one closes whether or not it holds a key.+ def shred_reachable_months(self, team_id: int) -> None:+ now = timezone.now()+ current = f"{now:%Y-%m}"+ previous = f"{datetime(now.year, now.month, 1, tzinfo=UTC) - timedelta(days=1):%Y-%m}"+ months = (previous, current, f"{month_end(current):%Y-%m}")+ self.shred([item_key(f"team:{team_id}", f"image:{month}") for month in months])+def initialize(self, request: AITrainingDeletionRequest) -> list[DeletionWork]:if request.team_id is None:raise ValueError("AI training deletion request has no team")team_id = request.team_idif request.kind == "team":- self.block(team_id)+ self.shred_reachable_months(team_id)return [{"op": "team", "team_id": team_id, "shard": -1}]if request.kind == "session":self.shred([session_key(team_id, value) for value in request.identifiers])@@ -182,18 +183,8 @@ class AITrainingPrivacyStore:return Falsework = self.advance(work[0]) + work[1:]self.save_cursor(request, work=work)- now = timezone.now()- complete_after = request.cursor.get("complete_after")- if complete_after is None:- self.save_cursor(request, work=[], complete_after=now.timestamp() + KEY_READ_LEASE_SECONDS)- return False- if 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 = now+ # A key that a batch stores after the sweep passes its shard is sealed under a month key this deletion already tombstoned, so a second sweep finds nothing that is readable. The sweep removes rows to save cost. See products/ai_training/docs/replay-data.md.+ request.completed_at = timezone.now()request.identifiers = []request.save(update_fields=["completed_at", "identifiers"])return True@@ -226,9 +217,6 @@ class AITrainingPrivacyStore:logger.exception("ai_training_deletion_request_failed", request_id=str(request.pk), kind=request.kind)request.leased_until = timezone.now() + timedelta(minutes=5)else:- request.leased_until = max(- timezone.now(),- datetime.fromtimestamp(request.cursor.get("complete_after", 0), tz=timezone.get_current_timezone()),- )+ request.leased_until = timezone.now()request.save(update_fields=["leased_until"])return completeddiff --git a/products/ai_training/backend/tests/test_privacy_store.py b/products/ai_training/backend/tests/test_privacy_store.pyindex 33e0848cbb35..3adcb96f316b 100644--- a/products/ai_training/backend/tests/test_privacy_store.py+++ b/products/ai_training/backend/tests/test_privacy_store.py@@ -1,10 +1,9 @@import time-from datetime import datetime, timedelta+from datetime import datetimefrom unittest.mock import MagicMock, patchfrom django.test import SimpleTestCase-from django.utils import timezonefrom parameterized import parameterized@@ -99,19 +98,37 @@ class TestAITrainingPrivacyStore(SimpleTestCase):)client.query.assert_not_called()- 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)+ def test_team_deletion_closes_every_month_a_later_session_could_still_open(self) -> 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)+ "products.ai_training.backend.privacy.store.timezone.now",+ return_value=datetime.fromisoformat("2025-12-31T23:59:00+00:00"),):- self.assertTrue(store.apply(request, time.monotonic() + 1))+ store.initialize(MagicMock(kind="team", team_id=7, identifiers=[]))+ updates = client.transact_write_items.call_args.kwargs["TransactItems"]+ self.assertEqual(+ [update["Update"]["Key"] for update in updates],+ [+ item_key("team:7", "image:2025-11"),+ item_key("team:7", "image:2025-12"),+ item_key("team:7", "image:2026-01"),+ ],+ )++ def test_team_deletion_completes_in_one_pass_and_shreds_every_shard_it_sweeps(self) -> None:+ request = MagicMock(kind="team", team_id=7, identifiers=[], cursor={}, completed_at=None)+ late_write = session_key(7, "01a09f92-e780-7000-8000-000000000003")+ client = MagicMock()+ client.query.side_effect = [{"Items": []}, {"Items": [late_write]}, *({"Items": []} for _ in range(31))]+ store = AITrainingPrivacyStore(client, "table")+ self.assertTrue(store.apply(request, time.monotonic() + 1))self.assertEqual(client.query.call_count, 33)+ shredded = [+ update["Update"]["Key"]+ for call in client.transact_write_items.call_args_list+ for update in call.kwargs["TransactItems"]+ ]+ self.assertIn(late_write, shredded)+ self.assertIsNotNone(request.completed_at)self.assertEqual(request.identifiers, [])diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.mdindex 857169af7a01..e337d60c4a8b 100644--- a/products/ai_training/docs/replay-data.md+++ b/products/ai_training/docs/replay-data.md@@ -60,13 +60,20 @@ The `seal` block in `nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keysIngestion processes key state in batches:-1. Bulk-read session keys, team blocks, and image keys in one pass. A session's start month names its image key, so the batch knows every row before it reads.+1. Bulk-read session keys and image keys in one pass. A session's start month names its image key, so the batch knows every row before it reads.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. 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 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.+A shredded team image key stops its team month for good, and this is the reason the table holds no team block row.+The shred sets the tombstone and removes the key material in one update.+A batch that meets a tombstoned image row does not add that month key to its keys, so it never writes the row again, and a conditional put would refuse it in any case because the row exists.+A session in that month then finds no month key, so the batch mints no session key and stores none, and it counts the session as `month_key_unavailable`.+Every reader drops the same sessions, because the seal only opens under a month key that no longer exists.+The deletion worker sweeps the team once, and that sweep removes rows to save cost. A key stored after the sweep passes a shard is sealed under a month key the deletion already tombstoned, so a second sweep finds nothing that is readable.+A team deletion also closes the previous month, the current one and the next one, because a sweep reaches only an image key that already exists. Ingestion admits a session up to `ML_SESSION_MAX_AGE_DAYS` old, so those three are every month a later session can still open.+Consent stops collection after that, not deletion: a team that keeps its opt-in and keeps sending opens a later month again.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, and the month index entries it needs go in together, at most 25 to a request.Batches overlap, so a session first seen in one batch and also present in the next costs a second conditional put, which loses and settles on the stored key.@@ -80,13 +87,12 @@ The record step writes to the recorder that is current at commit time, not the oIngestion 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 sealed session key keeps that same bound, because its seal lives on the session row and nothing else holds it.The team image key stays cached far longer, but it opens no session on its own.-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.+A team image key is held for an hour, because it is one row per team per month and a longer lifetime costs far fewer reads. A shred removes the durable key, so a process that runs on a held row of either kind writes data that no reader can open.Data written under such a key stays unreadable, because the envelope stores no key, and the stored row is a tombstone with no wrapped key, no seal, and no nonce.Training readers do not use this cache.Each process limits KMS concurrency and request rate; deployment capacity must account for the sum across replicas.@@ -111,11 +117,11 @@ Consent changes do not enqueue deletion requests.The outbox survives removal of the source team or organization.Its team IDs refer to the original environment, without resolving a child environment to its parent.-| Scope | Effect |-| ------- | ---------------------------------------------------------------------------------------- |-| Session | Remove its wrapped key, its seal, and its nonce, then permanently block that session ID. |-| Person | Resolve its session IDs through replay, then apply session deletion to each result. |-| Team | Permanently block the team and remove its session and image keys. |+| Scope | Effect |+| ------- | ----------------------------------------------------------------------------------------- |+| Session | Remove its wrapped key, its seal, and its nonce, then permanently block that session ID. |+| Person | Resolve its session IDs through replay, then apply session deletion to each result. |+| Team | Remove its session keys and its image keys, and close the current month and the next one. |The person lookup matches any available replay row for the requested IDs, then deduplicates and paginates sessions.It does not filter out recordings marked deleted or past their replay retention date while their index rows remain.@@ -147,7 +153,7 @@ Neither side reads a shared block item for the month, because every commit in thThe command uses strongly consistent queries and bounded writes.Rerun the command after an interrupted run; it safely repeats completed pages.Rerun it once for any month that an earlier version of the command deleted, because readers no longer honor the month block that version wrote.-Existing read leases expire within five minutes.+A reader that already cached a key can still use it.The matching monthly S3 folders can then be removed from each dataset.Deleting a month does not affect another month's image keys.@@ -206,7 +212,7 @@ Retries and dead-letter replay preserve this header and the record bytes.Consumers drop records that still use the sealed envelope shape from before cleartext records, and count them in `recording_blob_ingestion_v2_ml_legacy_envelopes_dropped_total`.Headerless queued messages mean v1.Unknown versions are rejected, and so is an image reference whose version does not match the header.-The metadata sink resolves each row's session key from the row's own team and session identifiers before it seals the row for Parquet; a row whose key is deleted or blocked is dropped.+The metadata sink resolves each row's session key from the row's own team and session identifiers before it seals the row for Parquet; a row whose key is deleted is dropped.Legacy image references and paths remain available for v1 sessions.Their HMAC key must remain stable while that data is in use.