: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): seal ML session keys under their team month key (#102414)
Robbiea90e0bf5d6f0
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto.test.tsindex 36c2e4b55dff..c2c36a2c23d9 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto.test.ts@@ -1,7 +1,11 @@+import { createDecipheriv } from 'node:crypto'+import { parseJSON } from '~/common/utils/json-parse'-import { MlDataKey, encryptEnvelope } from './crypto'+import { MlDataKey, TAG_BYTES, canonicalJson, encryptEnvelope, openSessionKey, sealSessionKey } from './crypto'+import vector from './encryption-vector.json'import { TrainingEncryptionVector, decryptEnvelope } from './envelope-testing'+import { wrappingContext } from './schema'import { validateImageOwner } from './transport'const key: MlDataKey = {@@ -77,3 +81,49 @@ describe('ML payload encryption', () => {).toBeLessThan(40 * 1024 * 1024 + 64 * 1024)})})++describe('sealing a session key under its team month key', () => {+ const teamMonthKey = Buffer.alloc(32, 9)+ const identity = { teamId: 7, sessionId: '01994569-4380-7000-8000-000000000007' }+ const sessionKey = Buffer.alloc(32, 4)++ it('opens what it seals', () => {+ const sealed = sealSessionKey(teamMonthKey, identity, sessionKey)+ expect(openSessionKey(teamMonthKey, identity, sealed)).toEqual(sessionKey)+ })++ it('uses a fresh nonce for each seal', () => {+ const first = sealSessionKey(teamMonthKey, identity, sessionKey)+ const second = sealSessionKey(teamMonthKey, identity, sessionKey)+ expect(first.nonce).not.toEqual(second.nonce)+ expect(first.sealed).not.toEqual(second.sealed)+ })++ it.each([+ ['another team month key', Buffer.alloc(32, 8), identity],+ ['another session', teamMonthKey, { teamId: 7, sessionId: '01994569-4380-7000-8000-000000000008' }],+ ['another team', teamMonthKey, { teamId: 8, sessionId: identity.sessionId }],+ ])('refuses to open under %s', (_label, key, other) => {+ const sealed = sealSessionKey(teamMonthKey, identity, sessionKey)+ expect(() => openSessionKey(key, other, sealed)).toThrow()+ })++ it('opens the pinned seal, so a reader in another language can check its own bytes', () => {+ const opened = openSessionKey(Buffer.from(vector.seal.teamMonthKey, 'base64'), vector.seal.identity, {+ sealed: Buffer.from(vector.seal.sealedKey, 'base64'),+ nonce: Buffer.from(vector.seal.nonce, 'base64'),+ })+ expect(opened.toString('base64')).toBe(vector.seal.sessionKey)+ })++ it('does not seal with the stored key itself, which still seals image data', () => {+ const sealed = sealSessionKey(teamMonthKey, identity, sessionKey)+ const asStoredKey = createDecipheriv('aes-256-gcm', teamMonthKey, sealed.nonce, { authTagLength: TAG_BYTES })+ asStoredKey.setAAD(Buffer.from(canonicalJson(wrappingContext(identity))))+ asStoredKey.setAuthTag(sealed.sealed.subarray(sealed.sealed.length - TAG_BYTES))+ expect(() => {+ asStoredKey.update(sealed.sealed.subarray(0, sealed.sealed.length - TAG_BYTES))+ asStoredKey.final()+ }).toThrow()+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto.tsindex b518d5881a84..0dc9673d93f9 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto.ts@@ -1,6 +1,6 @@import { DecryptCommand, GenerateDataKeyCommand, KMSClient } from '@aws-sdk/client-kms'import { LRUCache } from 'lru-cache'-import { createCipheriv, randomBytes } from 'node:crypto'+import { createCipheriv, createDecipheriv, hkdfSync, randomBytes } from 'node:crypto'import pLimit from 'p-limit'import { MlKeyRequest, MlMirrorMetrics } from '~/ingestion/pipelines/sessionreplay/ml-mirror/metrics'@@ -38,6 +38,41 @@ export function canonicalJson(value: unknown): string {return JSON.stringify(value)}+export interface MlSealedKey {+ sealed: Buffer+ nonce: Buffer+}++// HKDF makes this key from the stored key, which also seals image data. One key with two jobs lets a flaw in one job+// reach the other.+const SESSION_WRAP_INFO = Buffer.from('ml-session-key-wrap')++function sessionWrappingKey(teamMonthKey: Buffer): Buffer {+ return Buffer.from(hkdfSync('sha256', teamMonthKey, Buffer.alloc(0), SESSION_WRAP_INFO, 32))+}++/** The seal authenticates the identity, so a sealed key cannot move to another session or another team. */+export function sealSessionKey(teamMonthKey: Buffer, identity: MlKeyIdentity, plaintext: Buffer): MlSealedKey {+ const nonce = randomBytes(NONCE_BYTES)+ const cipher = createCipheriv('aes-256-gcm', sessionWrappingKey(teamMonthKey), nonce, { authTagLength: TAG_BYTES })+ cipher.setAAD(Buffer.from(canonicalJson(wrappingContext(identity))))+ return { sealed: Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]), nonce }+}++export function openSessionKey(teamMonthKey: Buffer, identity: MlKeyIdentity, sealed: MlSealedKey): Buffer {+ if (sealed.sealed.length <= TAG_BYTES) {+ throw new Error('ML sealed session key is too short')+ }+ const body = sealed.sealed.subarray(0, sealed.sealed.length - TAG_BYTES)+ const tag = sealed.sealed.subarray(sealed.sealed.length - TAG_BYTES)+ const decipher = createDecipheriv('aes-256-gcm', sessionWrappingKey(teamMonthKey), sealed.nonce, {+ authTagLength: TAG_BYTES,+ })+ decipher.setAAD(Buffer.from(canonicalJson(wrappingContext(identity))))+ decipher.setAuthTag(tag)+ return Buffer.concat([decipher.update(body), decipher.final()])+}+export class MlKeyEncryption {private readonly cache: LRUCache<string, Buffer>private readonly pending = new Map<string, Promise<Buffer>>()@@ -96,6 +131,9 @@ export class MlKeyEncryption {}public rememberCommitted(key: MlDataKey): void {+ if (!key.wrapped.length) {+ return+ }this.cache.set(this.cacheId(key.identity, key.wrapped), key.plaintext)}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/dynamodb.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/dynamodb.tsindex 637283fc6643..030af0326608 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/dynamodb.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/dynamodb.ts@@ -96,7 +96,7 @@ export class MlKeyDynamoDB {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) {+ } 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,})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/encryption-vector.json b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/encryption-vector.jsonindex b70cb215eaff..167a37c6d2fd 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/encryption-vector.json+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/encryption-vector.json@@ -16,5 +16,15 @@},"nonce": "AwMDAwMDAwMDAwMD","ciphertext": "VofNdzJNKisZYCoynzKNY51Zko7W/PgZW6enwYKcLNfQw1APuYhuzy8mpJ3qd2oMKRc="+ },+ "seal": {+ "teamMonthKey": "CQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk=",+ "identity": {+ "teamId": 7,+ "sessionId": "01994569-4380-7000-8000-000000000007"+ },+ "sessionKey": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ=",+ "nonce": "eeEJEciFIDqBWFNk",+ "sealedKey": "vxp6SKFXDX5P4p/OXPmke/ahZKBw1+rUcA5OsFanqN665rxNb8kUZPLXQoafeWnv"}}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 f2ce10288990..c487f980b114 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@@ -158,7 +158,8 @@ describe('ML session key batches', () => {it('deduplicates repeated sessions and stores only keys and month indexes', async () => {const identities = Array.from({ length: 120 }, () => ({ ...session }))const batch = await store.prepare(identities)- expect(generated).toBe(2)+ // KMS makes the team month key. The lane makes each session key locally and seals it under that key.+ expect(generated).toBe(1)await batch.commit()expect(boundary.items.size).toBe(4)expect(Math.max(...boundary.readSizes)).toBeLessThanOrEqual(100)@@ -184,8 +185,8 @@ describe('ML session key batches', () => {expect(boundary.items.has(tableKeyString(monthKeyIndexId({ ...session }, location)))).toBe(true)// Two index rows and two keys. A retry that re-sent the whole batch would store an index row twice.expect(boundary.writes).toBe(4)- // One batch write, one retry carrying the single deferred row, and a put for each key.- expect(boundary.writeRequests).toBe(4)+ // Each phase makes one batch write, the retry carries the deferred row, and each key takes one put.+ expect(boundary.writeRequests).toBe(5)}})@@ -202,8 +203,9 @@ describe('ML session key batches', () => {// 60 session keys and one team image key. Each is one conditional put, and their 61 index entries pack into// three batches of at most 25, so 122 requests become 64.expect(boundary.writes).toBe(122)- expect(boundary.writeRequests).toBe(64)- expect([...boundary.writeBatchSizes].sort((a, b) => b - a)).toEqual([25, 25, 11])+ // The team month key commits before the keys it seals, so that phase adds one request.+ expect(boundary.writeRequests).toBe(65)+ expect([...boundary.writeBatchSizes].sort((a, b) => b - a)).toEqual([25, 25, 10, 1])})it('reads every row a batch needs in one pass', async () => {@@ -236,6 +238,8 @@ describe('ML session key batches', () => {const keys = await reader.read(identities.map((identity) => sessionKeyId(identity.teamId, identity.sessionId)))expect(keys.size).toBe(identities.length)expect(boundary.conditionalFailures).toBe(0)+ // These 120 sessions share one team month, so KMS made one key.+ expect(generated).toBe(1)})it.each([@@ -468,12 +472,14 @@ describe('ML session key batches', () => {const generates = kmsSend.mock.calls.map(([command]) => command).filter((c) => c instanceof GenerateDataKeyCommand)- expect(generates).toHaveLength(2)+ expect(generates).toHaveLength(1)for (const command of generates) {expect(command.input.EncryptionContext).not.toHaveProperty('organization_id')}const stored = boundary.items.get(tableKeyString(sessionKeyId(session.teamId, session.sessionId)))!expect(stored).not.toHaveProperty('organization_id')+ expect(stored).toHaveProperty('sealed_key')+ expect(stored).not.toHaveProperty('wrapped_key')})it('unwraps a key stored under the organization it was wrapped with', async () => {@@ -529,15 +535,23 @@ describe('ML session key batches', () => {})it.each([- ['session', () => sessionKeyId(session.teamId, session.sessionId)],- ['monthly image', () => imageKeyId(session.teamId, '2025-09')],+ // A session key opens under its month key only, so an unusable month key makes its sessions unusable too.+ ['session', () => sessionKeyId(session.teamId, session.sessionId), [['wrapped_key_missing', 1]]],+ [+ 'monthly image',+ () => imageKeyId(session.teamId, '2025-09'),+ [+ ['month_key_unavailable', 1],+ ['wrapped_key_missing', 1],+ ],+ ],])(- 'drops the sessions behind a stored %s key that has no wrapped key and no tombstone, reporting it once',- async (_kind, keyId) => {+ 'drops the sessions behind a stored %s key that has no wrapped key and no tombstone, naming why',+ async (_kind, keyId, reported) => {const first = await store.prepare([session])await first.commit()const location = tableKeyString(keyId())- const { wrapped_key: _wrapped, ...stored } = boundary.items.get(location)!+ const { wrapped_key: _wrapped, sealed_key: _sealed, ...stored } = boundary.items.get(location)!boundary.items.set(location, stored)coldCache()const unusable = jest.spyOn(MlMirrorMetrics, 'incrementMlKeyIdentityMismatch')@@ -545,11 +559,129 @@ describe('ML session key batches', () => {expect(next.get(session.teamId, session.sessionId)).toBeUndefined()await next.commit()expect(boundary.items.get(location)).toEqual(stored)- expect(unusable).toHaveBeenCalledTimes(1)- expect(unusable).toHaveBeenCalledWith('wrapped_key_missing', 1)+ expect(unusable.mock.calls.sort()).toEqual(reported)})+ it('leaves the team month key out of the scheme counter, so v2 can reach zero', async () => {+ const scheme = jest.spyOn(MlMirrorMetrics, 'incrementMlKeyScheme')+ await (await store.prepare([session])).commit()+ coldCache()+ await store.prepare([session])+ expect(scheme.mock.calls.map(([value]) => value)).toEqual(['v3'])+ })++ it('counts a session key that KMS wrapped as v2', async () => {+ const sessionKey = await encryption.generate({ teamId: session.teamId, sessionId: session.sessionId })+ const location = sessionKeyId(session.teamId, session.sessionId)+ boundary.items.set(tableKeyString(location), {+ ...encodeKey(location),+ wrapped_key: { B: sessionKey.wrapped },+ team_id: { N: String(session.teamId) },+ session_month: { S: '2025-09' },+ })+ const scheme = jest.spyOn(MlMirrorMetrics, 'incrementMlKeyScheme')+ await store.prepare([session])+ expect(scheme.mock.calls.map(([value]) => value)).toEqual(['v2'])+ })++ it('drops the sessions of a month key that lost its put to a tombstone, and still commits', async () => {+ const batch = await store.prepare([session])+ const monthLocation = imageKeyId(session.teamId, '2025-09')+ boundary.items.set(tableKeyString(monthLocation), { ...encodeKey(monthLocation), deleted: { BOOL: true } })+ await expect(batch.commit()).resolves.toBeUndefined()+ expect(batch.get(session.teamId, session.sessionId)).toBeUndefined()+ expect(boundary.items.has(tableKeyString(sessionKeyId(session.teamId, session.sessionId)))).toBe(false)+ })++ it('leaves the team month key out of the reader scheme counter, so v2 can reach zero', async () => {+ await (await store.prepare([session])).commit()+ coldCache()+ const scheme = jest.spyOn(MlMirrorMetrics, 'incrementMlKeyScheme')+ await reader.read([imageKeyId(session.teamId, '2025-09')])+ expect(scheme).not.toHaveBeenCalled()+ await reader.read([sessionKeyId(session.teamId, session.sessionId)])+ expect(scheme.mock.calls.map(([value]) => value)).toEqual(['v3'])+ })++ it('drops the sessions of a month key that KMS refuses, and still serves the rest of the batch', async () => {+ const other = { ...session, sessionId: '01994569-4380-7000-8000-00000000000a' }+ await (await store.prepare([session, other])).commit()+ coldCache()+ const monthLocation = tableKeyString(imageKeyId(session.teamId, '2025-09'))+ const stored = boundary.items.get(monthLocation)!+ boundary.items.set(monthLocation, { ...stored, wrapped_key: { B: Buffer.from('not-a-kms-blob') } })+ const legacy = sessionKeyId(other.teamId, '01994569-4380-7000-8000-00000000000b')+ const legacyKey = await encryption.generate({+ teamId: other.teamId,+ sessionId: legacy.sk.slice('session:'.length),+ })+ boundary.items.set(tableKeyString(legacy), {+ ...encodeKey(legacy),+ wrapped_key: { B: legacyKey.wrapped },+ team_id: { N: String(other.teamId) },+ session_month: { S: '2025-09' },+ })+ const mismatch = jest.spyOn(MlMirrorMetrics, 'incrementMlKeyIdentityMismatch')+ const keys = await reader.read([+ sessionKeyId(session.teamId, session.sessionId),+ sessionKeyId(other.teamId, other.sessionId),+ legacy,+ ])+ expect(keys.has(tableKeyString(sessionKeyId(session.teamId, session.sessionId)))).toBe(false)+ expect(keys.has(tableKeyString(sessionKeyId(other.teamId, other.sessionId)))).toBe(false)+ expect(keys.has(tableKeyString(legacy))).toBe(true)+ // One refused month key counts once, however many sessions needed it, so the writer and the reader mean the same thing.+ 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()+ encryption.clear()+ kmsSend.mockImplementation(() => Promise.reject(transientError('ThrottlingException')))+ await expect(reader.read([sessionKeyId(session.teamId, session.sessionId)])).rejects.toThrow(+ 'ThrottlingException'+ )+ })++ it('counts an unusable row once however often the batch re-reads it', async () => {+ await (await store.prepare([session])).commit()+ const location = tableKeyString(sessionKeyId(session.teamId, session.sessionId))+ const { sealed_key: _sealed, ...stripped } = boundary.items.get(location)!+ boundary.items.set(location, stripped)+ coldCache()+ const mismatch = jest.spyOn(MlMirrorMetrics, 'incrementMlKeyIdentityMismatch')+ const batch = await store.prepare([session])+ await batch.read()+ await batch.read()+ expect(mismatch.mock.calls).toEqual([['wrapped_key_missing', 1]])+ })++ it('drops a session whose seal does not open, and still serves the rest of the batch', async () => {+ const other = { ...session, sessionId: '01994569-4380-7000-8000-000000000009' }+ await (await store.prepare([session, other])).commit()+ const location = sessionKeyId(session.teamId, session.sessionId)+ const stored = boundary.items.get(tableKeyString(location))!+ boundary.items.set(tableKeyString(location), { ...stored, sealed_key: { B: Buffer.alloc(48, 9) } })+ coldCache()+ const mismatch = jest.spyOn(MlMirrorMetrics, 'incrementMlKeyIdentityMismatch')+ const next = await store.prepare([session, other])+ expect(next.get(session.teamId, session.sessionId)).toBeUndefined()+ expect(next.get(other.teamId, other.sessionId)).not.toBeUndefined()+ expect(mismatch).toHaveBeenCalledWith('seal_unopenable', 1)+ })+it('adopts a competing writer key when the refusal omits the stored row', async () => {const send = boundary.send.bind(boundary)jest.spyOn(boundary, 'send').mockImplementation((command) => {@@ -715,7 +847,7 @@ describe('ML session key batches', () => {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)+ 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)})@@ -737,7 +869,7 @@ describe('ML session key batches', () => {for (let index = 0; index < 20; index++) {await controller.defer(input, (value) => {expect(- boundary.items.get(tableKeyString(sessionKeyId(identity.teamId, identity.sessionId)))?.wrapped_key+ boundary.items.get(tableKeyString(sessionKeyId(identity.teamId, identity.sessionId)))?.sealed_key).not.toBeUndefined()started += 1return Promise.resolve(ok(value, [delivery]))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 741682b32caa..b84a964f56c4 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@@ -1,8 +1,10 @@+import { randomBytes } from 'node:crypto'+import { logger } from '~/common/utils/logger'-import { MlMirrorMetrics } from '~/ingestion/pipelines/sessionreplay/ml-mirror/metrics'+import { MlKeyIdentityMismatchReason, MlMirrorMetrics } from '~/ingestion/pipelines/sessionreplay/ml-mirror/metrics'import { sessionStartMonth } from '~/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format'-import { MlDataKey, MlKeyEncryption } from './crypto'+import { MlDataKey, MlKeyEncryption, openSessionKey, sealSessionKey } from './crypto'import { DynamoItem, MlKeyDynamoDB } from './dynamodb'import {MlKeyIdentity,@@ -105,37 +107,46 @@ export class MlKeyBatch {}}const unusable: MlStoredKeyMismatch[] = []- await Promise.all(- [...keyIdentities].map(async ([id, identity]) => {- const item = this.state.get(id)- if (item?.deleted?.BOOL === true) {- return- }- if (item) {- if (!item.wrapped_key?.B) {- if (!this.reportedUnusable.has(id)) {- this.reportedUnusable.add(id)- unusable.push({ id, teamId: identity.teamId })- }+ // A session key opens under its team month key, so the month keys resolve first.+ for (const group of [+ [...keyIdentities].filter(([, identity]) => !identity.sessionId),+ [...keyIdentities].filter(([, identity]) => identity.sessionId),+ ]) {+ await Promise.all(+ group.map(async ([id, identity]) => {+ const item = this.state.get(id)+ if (item?.deleted?.BOOL === true) {return}- // A key wrapped while the organization was part of the KMS context only unwraps under that organization, which the row still names.- const organizationId = item.organization_id?.S- const storedIdentity = { ...identity, ...(organizationId ? { organizationId } : {}) }- this.keys.set(id, await this.encryption.decrypt(storedIdentity, Buffer.from(item.wrapped_key.B)))- } else {- let candidate = this.candidates.get(id)- if (!candidate) {- candidate = await this.encryption.generate(identity)- this.candidates.set(id, candidate)+ if (item) {+ const stored = await this.openStored(identity, item)+ if (typeof stored === 'string') {+ const rowNeedsRepair = stored !== 'month_key_unavailable'+ if (this.reportUnusable(id, stored) && rowNeedsRepair) {+ unusable.push({ id, teamId: identity.teamId })+ }+ return+ }+ this.keys.set(id, stored)+ } else {+ if (identity.sessionId && !this.monthKeyFor(identity)) {+ this.reportUnusable(id, 'month_key_unavailable')+ return+ }+ let candidate = this.candidates.get(id)+ if (!candidate) {+ candidate = identity.sessionId+ ? { identity, plaintext: randomBytes(32), wrapped: Buffer.alloc(0) }+ : await this.encryption.generate(identity)+ this.candidates.set(id, candidate)+ }+ this.keys.set(id, candidate)}- this.keys.set(id, candidate)- }- })- )- // A row with no wrapped key and no tombstone cannot serve this batch; its sessions are dropped like blocked ones so one bad row cannot stop the lane, and the log names it so the data can be repaired.+ })+ )+ }+ // A row that gives no key cannot serve this batch; its sessions are dropped like blocked ones so one bad row cannot stop the lane, and the log names it so the data can be repaired.if (unusable.length) {- MlMirrorMetrics.incrementMlKeyIdentityMismatch('wrapped_key_missing', unusable.length)logger.error('🔑', 'ml_key_stored_key_unusable', {count: unusable.length,teamIds: [...new Set(unusable.map((entry) => entry.teamId))],@@ -144,6 +155,51 @@ export class MlKeyBatch {}}+ private reportUnusable(id: string, reason: MlKeyIdentityMismatchReason): boolean {+ if (this.reportedUnusable.has(id)) {+ return false+ }+ this.reportedUnusable.add(id)+ MlMirrorMetrics.incrementMlKeyIdentityMismatch(reason, 1)+ return true+ }++ private monthKeyFor(identity: MlKeyIdentity): MlDataKey | undefined {+ return this.keys.get(tableKeyString(imageKeyId(identity.teamId, keySessionMonth(identity))))+ }++ /** Resolves a stored row to its key, whether KMS wrapped it or its team month key sealed it. */+ private async openStored(+ identity: MlKeyIdentity,+ item: DynamoItem+ ): Promise<MlDataKey | MlKeyIdentityMismatchReason> {+ if (item.sealed_key?.B && item.key_nonce?.B) {+ const monthKey = this.monthKeyFor(identity)+ if (!monthKey) {+ return 'month_key_unavailable'+ }+ const sealed = { sealed: Buffer.from(item.sealed_key.B), nonce: Buffer.from(item.key_nonce.B) }+ try {+ const plaintext = openSessionKey(monthKey.plaintext, identity, sealed)+ MlMirrorMetrics.incrementMlKeyScheme('v3')+ return { identity, plaintext, wrapped: Buffer.alloc(0) }+ } catch {+ // A seal opens under one month key only, so a failure here means the row and the month key disagree. One row must not stop the lane.+ return 'seal_unopenable'+ }+ }+ if (!item.wrapped_key?.B) {+ return 'wrapped_key_missing'+ }+ if (identity.sessionId) {+ MlMirrorMetrics.incrementMlKeyScheme('v2')+ }+ // A key wrapped while the organization was part of the KMS context only unwraps under that organization, which the row still names.+ const organizationId = item.organization_id?.S+ const storedIdentity = { ...identity, ...(organizationId ? { organizationId } : {}) }+ return this.encryption.decrypt(storedIdentity, Buffer.from(item.wrapped_key.B))+ }+public get(teamId: number, sessionId: string): MlSessionKeys | undefined {const id = tableKeyString(sessionKeyId(teamId, sessionId))const session = this.keys.get(id)@@ -156,12 +212,38 @@ 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> {- let dropped = 0const unstored = [...this.keys].filter(([id]) => !this.state.has(id))- // Every index entry goes in before any key, so a key put that fails still leaves its entry, as it did when each- // key wrote its own. These need no condition, so they batch and a key costs one write request rather than two.+ // The month key commits first. A put that loses leaves session keys sealed under bytes that nobody stored.+ const monthKeys = unstored.filter(([, key]) => !key.identity.sessionId)+ if (monthKeys.length) {+ await this.write(monthKeys, deadline)+ }+ await this.write(+ unstored.filter(([, key]) => key.identity.sessionId),+ deadline+ )+ }++ private async write(entries: [string, MlDataKey][], deadline: AbortSignal): Promise<void> {+ let dropped = 0+ const rows: [string, MlDataKey, DynamoItem][] = []+ for (const [id, key] of entries) {+ const row = this.rowFor(key)+ if (!row) {+ this.keys.delete(id)+ dropped += 1+ continue+ }+ rows.push([id, key, row])+ }+ if (!rows.length) {+ this.reportDropped(dropped)+ return+ }+ // Every index entry goes in before any key, so a key put that fails still leaves its entry. These need no+ // condition, so they batch and a key costs one write request rather than two.await this.db.putMany(- unstored.map(([, key]) => {+ rows.map(([, key]) => {const location = storedKeyId(key.identity)return {key: monthKeyIndexId(key.identity, location),@@ -171,35 +253,39 @@ export class MlKeyBatch {deadline)const results = await Promise.allSettled(- unstored.map(async ([id, key]) => {+ rows.map(async ([id, key, row]) => {const location = storedKeyId(key.identity)- const stored = await this.db.putIfAbsent(- location,- {- wrapped_key: { B: key.wrapped },- team_id: { N: String(key.identity.teamId) },- session_month: { S: keySessionMonth(key.identity) },- },- deadline- )+ const stored = await this.db.putIfAbsent(location, row, deadline)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) {+ if (stored.deleted?.BOOL === true) {this.keys.delete(id)dropped += 1return}- const wrapped = Buffer.from(stored.wrapped_key.B)- if (wrapped.equals(key.wrapped)) {+ // A wrapped blob is stable, so equal bytes name this batch's own write and spare a KMS decrypt.+ if (+ key.wrapped.length &&+ stored.wrapped_key?.B &&+ key.wrapped.equals(Buffer.from(stored.wrapped_key.B))+ ) {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 winner = await this.openStored(key.identity, stored)+ if (typeof winner === 'string') {+ this.keys.delete(id)+ dropped += 1+ return+ }+ if (winner.plaintext.equals(key.plaintext)) {+ this.encryption.rememberCommitted(key)+ return+ }+ this.keys.set(id, winner)}))const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected')@@ -207,11 +293,35 @@ export class MlKeyBatch {if (failure) {throw failure.reason}+ this.reportDropped(dropped)+ }++ private reportDropped(dropped: number): void {if (dropped) {logger.info('🔑', 'ml_key_commit_dropped_blocked', { dropped })}}+ /** A month key keeps its KMS blob. A session key carries the seal its month key made, so it gives no row once that month key goes. */+ private rowFor(key: MlDataKey): DynamoItem | undefined {+ const shared = {+ team_id: { N: String(key.identity.teamId) },+ session_month: { S: keySessionMonth(key.identity) },+ }+ if (!key.identity.sessionId) {+ if (!key.wrapped.length) {+ throw new Error('ML month key has no KMS blob to store')+ }+ return { wrapped_key: { B: key.wrapped }, ...shared }+ }+ const monthKey = this.monthKeyFor(key.identity)+ if (!monthKey) {+ return undefined+ }+ const sealed = sealSessionKey(monthKey.plaintext, key.identity, key.plaintext)+ return { sealed_key: { B: sealed.sealed }, key_nonce: { B: sealed.nonce }, ...shared }+ }+public async commit(): Promise<void> {if (this.committed) {throw new Error('ML batch already committed')diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader.tsindex 4c4231fc96c5..d51938541bd2 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,18 @@-import { MlDataKey, MlKeyEncryption } from './crypto'-import { MlKeyDynamoDB } from './dynamodb'-import { MlKeyIdentity, TableKey, storedSessionId, tableKeyString, teamBlockId } from './schema'+import { logger } from '~/common/utils/logger'+import { MlMirrorMetrics } from '~/ingestion/pipelines/sessionreplay/ml-mirror/metrics'++import { MlDataKey, MlKeyEncryption, openSessionKey } from './crypto'+import { DynamoItem, MlKeyDynamoDB } from './dynamodb'+import {+ MlKeyIdentity,+ TableKey,+ imageKeyId,+ keySessionMonth,+ storedSessionId,+ tableKeyString,+ teamBlockId,+} from './schema'+import { isTransientError } from './transient'export class MlKeyReader {constructor(@@ -8,33 +20,121 @@ export class MlKeyReader {private readonly encryption: MlKeyEncryption) {}+ private identityOf(item: DynamoItem): MlKeyIdentity {+ const teamId = Number(item.team_id?.N)+ if (!Number.isSafeInteger(teamId)) {+ throw new Error('Invalid ML key record')+ }+ const sessionId = item.sk.S ? storedSessionId(item.sk.S) : undefined+ const organizationId = item.organization_id?.S+ return {+ teamId,+ ...(sessionId ? { sessionId } : { sessionMonth: item.session_month?.S }),+ ...(organizationId ? { organizationId } : {}),+ }+ }++ /** The writer seals under the month it takes from the session id, so the reader takes the month the same way. */+ private monthKeyIdFor(identity: MlKeyIdentity): string | undefined {+ try {+ return tableKeyString(imageKeyId(identity.teamId, keySessionMonth(identity)))+ } catch {+ return undefined+ }+ }+public async read(keys: TableKey[]): Promise<Map<string, MlDataKey>> {const stored = await this.db.read(keys)const identities = new Map<string, MlKeyIdentity>()for (const [id, item] of stored) {- if (!item.wrapped_key?.B || item.deleted?.BOOL === true) {+ if (item.deleted?.BOOL === true || !(item.wrapped_key?.B || (item.sealed_key?.B && item.key_nonce?.B))) {+ continue+ }+ identities.set(id, this.identityOf(item))+ }+ // A sealed session key opens under its team month key, so this read includes that row with the team blocks.+ const monthKeys = new Map<string, TableKey>()+ const monthKeyOf = new Map<string, string>()+ for (const [id, identity] of identities) {+ if (!stored.get(id)!.sealed_key?.B) {continue}- const teamId = Number(item.team_id?.N)- if (!Number.isSafeInteger(teamId)) {- throw new Error('Invalid ML key record')+ const monthId = this.monthKeyIdFor(identity)+ if (!monthId) {+ continue}- const sessionId = item.sk.S ? storedSessionId(item.sk.S) : undefined- const organizationId = item.organization_id?.S- identities.set(id, {- teamId,- ...(sessionId ? { sessionId } : { sessionMonth: item.session_month?.S }),- ...(organizationId ? { organizationId } : {}),+ 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 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 = 0+ await Promise.all(+ [...monthKeys.keys()].map(async (id) => {+ const item = state.get(id)+ if (item?.deleted?.BOOL === true) {+ return+ }+ if (!item?.wrapped_key?.B) {+ unavailable += 1+ 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)))+ } 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)) {+ throw error+ }+ unavailable += 1+ refused.push({ id, error: error instanceof Error ? error.name : String(error) })+ }})+ )+ if (unavailable) {+ MlMirrorMetrics.incrementMlKeyIdentityMismatch('month_key_unavailable', unavailable)+ }+ if (refused.length) {+ logger.error('🔑', 'ml_key_month_key_refused', { count: refused.length, rows: refused })}- const state = await this.db.read([...identities.values()].map((identity) => teamBlockId(identity.teamId)))const result = new Map<string, MlDataKey>()await Promise.all([...identities].map(async ([id, identity]) => {- if (state.has(tableKeyString(teamBlockId(identity.teamId)))) {+ if (blocked(identity.teamId)) {return}- result.set(id, await this.encryption.decrypt(identity, Buffer.from(stored.get(id)!.wrapped_key.B!)))+ const item = stored.get(id)!+ if (item.sealed_key?.B && item.key_nonce?.B) {+ const monthId = monthKeyOf.get(id)+ const month = monthId ? months.get(monthId) : undefined+ if (!month) {+ return+ }+ const sealed = { sealed: Buffer.from(item.sealed_key.B), nonce: Buffer.from(item.key_nonce.B) }+ try {+ const plaintext = openSessionKey(month.plaintext, identity, sealed)+ MlMirrorMetrics.incrementMlKeyScheme('v3')+ result.set(id, { identity, plaintext, wrapped: Buffer.alloc(0) })+ } catch {+ // One row that disagrees with its month key must not fail the read for every other session.+ MlMirrorMetrics.incrementMlKeyIdentityMismatch('seal_unopenable', 1)+ }+ return+ }+ if (identity.sessionId) {+ MlMirrorMetrics.incrementMlKeyScheme('v2')+ }+ result.set(id, await this.encryption.decrypt(identity, Buffer.from(item.wrapped_key!.B!)))}))return resultdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.tsindex a24238469b84..f13e39d3ae5d 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts@@ -19,7 +19,7 @@ export type MlUrlCrawlHistoryOutcome = 'fresh' | 'miss' | 'error'export type MlImageSource = 'css' | 'html'/** Phases of the ML key work around one Kafka batch: the key bulk read before processing, the key writes and re-read after it, and the deferred publications. */export type MlKeyPhase = 'prepare' | 'commit' | 'publish'-export type MlKeyIdentityMismatchReason = 'wrapped_key_missing'+export type MlKeyIdentityMismatchReason = 'wrapped_key_missing' | 'month_key_unavailable' | 'seal_unopenable'export type MlKeyRequest =| 'kms_generate'| 'kms_decrypt'@@ -71,7 +71,7 @@ export class MlMirrorMetrics {})private static readonly mlKeyIdentityMismatch = new Counter({name: 'recording_blob_ingestion_v2_ml_key_identity_mismatch_total',- help: 'Stored ML key rows the mirror could not use: the row has no wrapped key and no tombstone, so its sessions are dropped (ml_key_stored_key_unusable log names the rows)',+ help: 'Stored ML key rows the mirror could not use, so their sessions are dropped, by reason. wrapped_key_missing: the row has no key and no tombstone, and the ml_key_stored_key_unusable log names these rows. seal_unopenable: the row and its team month key disagree. month_key_unavailable: the row is intact but its team month key gave no key, so one month key can raise this once per session that needed it. Each reason counts a row once per batch',labelNames: ['reason'],})private static readonly mlProducedVersion = new Counter({@@ -137,6 +137,11 @@ 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 mlKeyScheme = new Counter({+ name: 'recording_blob_ingestion_v2_ml_key_scheme_total',+ help: 'Stored ML session keys resolved, by the scheme that sealed them. v2 wraps a session key with KMS directly. v3 seals a session key under its team month key, so only the month key reaches KMS. A team month key always uses KMS, so this counter leaves month keys out and v2 counts session keys alone. When v2 reaches zero, no session key predates v3, and the team block and the Python deletion sweep can go',+ labelNames: ['scheme'],+ })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',@@ -182,6 +187,10 @@ export class MlMirrorMetrics {this.mlKeyRequestDuration.labels(request).observe(ms)}+ public static incrementMlKeyScheme(scheme: 'v2' | 'v3'): void {+ this.mlKeyScheme.labels(scheme).inc()+ }+public static incrementMlKeyRowCacheLookup(outcome: 'hit' | 'miss'): void {this.mlKeyRowCacheLookups.labels(outcome).inc()}diff --git a/products/ai_training/backend/privacy/store.py b/products/ai_training/backend/privacy/store.pyindex cced194d11f0..cb7804d844b4 100644--- a/products/ai_training/backend/privacy/store.py+++ b/products/ai_training/backend/privacy/store.py@@ -25,6 +25,8 @@ KEY_READ_LEASE_SECONDS = 300MONTH_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)+# A per-session deletion keeps the team month key, so it must also remove the seal that the month key opens.+KEY_MATERIAL_ATTRIBUTES = ("wrapped_key", "sealed_key", "key_nonce")DynamoItem = dict[str, dict[str, str | bool | bytes]]@@ -133,7 +135,7 @@ class AITrainingPrivacyStore:"Update": {"TableName": self.table_name,"Key": {"pk": key["pk"], "sk": key["sk"]},- "UpdateExpression": "SET deleted = :deleted REMOVE wrapped_key",+ "UpdateExpression": "SET deleted = :deleted REMOVE " + ", ".join(KEY_MATERIAL_ATTRIBUTES),"ExpressionAttributeValues": {":deleted": {"BOOL": True}},},}diff --git a/products/ai_training/backend/tests/test_privacy_store.py b/products/ai_training/backend/tests/test_privacy_store.pyindex 940f26f5a150..33e0848cbb35 100644--- a/products/ai_training/backend/tests/test_privacy_store.py+++ b/products/ai_training/backend/tests/test_privacy_store.py@@ -83,19 +83,20 @@ class TestAITrainingPrivacyStore(SimpleTestCase):with self.assertRaisesRegex(ValueError, "can be deleted from"):store.delete_month(month)- def test_session_deletion_shreds_keys_without_querying_user_indexes(self) -> None:+ def test_session_deletion_shreds_every_key_attribute_without_querying_user_indexes(self) -> None:client = MagicMock()sessions = ["01a09f92-e780-7000-8000-000000000001", "01a09f92-e780-7000-8000-000000000002"]store = AITrainingPrivacyStore(client, "table")self.assertEqual(store.initialize(MagicMock(kind="session", team_id=7, identifiers=sessions)), [])updates = client.transact_write_items.call_args.kwargs["TransactItems"]self.assertEqual([update["Update"]["Key"] for update in updates], [session_key(7, value) for value in sessions])- self.assertTrue(- all(- update["Update"]["UpdateExpression"] == "SET deleted = :deleted REMOVE wrapped_key"- for update in updates+ for update in updates:+ expression = update["Update"]["UpdateExpression"]+ self.assertTrue(expression.startswith("SET deleted = :deleted REMOVE "))+ self.assertEqual(update["Update"]["ExpressionAttributeValues"], {":deleted": {"BOOL": True}})+ self.assertEqual(+ sorted(expression.partition(" REMOVE ")[2].split(", ")), ["key_nonce", "sealed_key", "wrapped_key"])- )client.query.assert_not_called()def test_completion_waits_for_reader_leases_then_sweeps_the_team_once_more(self) -> None:diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.mdindex 643facad9e5a..659222f3dcc0 100644--- a/products/ai_training/docs/replay-data.md+++ b/products/ai_training/docs/replay-data.md@@ -34,17 +34,29 @@ There is no separate consent model, DynamoDB consent entry, consent timestamp, o## Keys and batch processingThe independent DynamoDB table stores session keys, team image keys, deletion markers, and monthly key indexes.+A team image key is wrapped by KMS.+A session key is sealed under the team image key of its month, so KMS holds one key per team per month, not one key per session.+A session key stored before this change carries its own KMS blob, and every reader opens both shapes.+HKDF-SHA256 makes the key that seals session keys from the stored team image key, which still seals image data itself.+The `recording_blob_ingestion_v2_ml_key_scheme_total` metric counts session keys by scheme and leaves team image keys out, so v2 reaches zero when no session key predates v3.ML outputs omit distinct IDs, including their hashes and pseudonyms.The metadata consumer projects supported fields before storage, including for messages already in Kafka.A session has one data key.A team has one image key per session start month.-KMS wraps each data key with an encryption context that binds the team, the session or month, and the purpose.+KMS wraps each key it holds with an encryption context that binds the team, the session or month, and the purpose.+A sealed session key authenticates the same context.A team can change organization while a session is open, so the organization is not part of that context; keys wrapped before this change carry the organization they were wrapped under on their row, and the mirror unwraps them under it.Payload encryption uses XSalsa20-Poly1305.The authenticated payload also binds the dataset kind and, for images, the object or reference being encrypted.The envelope seals the raw payload with AES-256-GCM.Its additional authenticated data is the JSON of `{"v": 3, "context": ...}` with sorted keys and no whitespace, so every reader rebuilds the same bytes.The envelope is JSON with `v`, `context`, `nonce` (12 bytes, base64) and `ciphertext` (the sealed bytes followed by the 16-byte tag, base64).+A sealed session key row carries `sealed_key` and `key_nonce`, and carries no `wrapped_key`.+HKDF-SHA256 makes its 32-byte wrapping key from the stored team image key, with an empty salt and the info string `ml-session-key-wrap`.+AES-256-GCM then seals the session key under that wrapping key.+`key_nonce` holds the 12-byte nonce, and `sealed_key` holds the sealed bytes followed by the 16-byte tag.+Its additional authenticated data is the JSON of `{"purpose": "ai-research-session", "team_id": ..., "session_id": ...}` with sorted keys and no whitespace, so every reader rebuilds the same bytes.+The `seal` block in `nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/encryption-vector.json` pins one seal, so a reader in another language can check its own bytes.Ingestion processes key state in batches:@@ -66,8 +78,10 @@ A team block row is held once a read finds one, because nothing clears a block.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.-Data written under such a key stays unreadable, because the envelope stores no wrapped key and the stored row is a tombstone.+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.Readers check live state before each batch and permit key use for at most five minutes from the start of that read.@@ -76,7 +90,7 @@ An expired read must obtain permission again.The key table has no TTL or point-in-time recovery.Its resource policy denies backups, exports, and enabling continuous backups or Kinesis copies.Do not copy wrapped keys into object storage, logs, workflow payloads, or another persistent cache.-Restoring a deleted wrapped key would defeat deletion.+A restored key defeats deletion, whether KMS wrapped it or a team image key sealed it.## Deletion@@ -91,11 +105,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 and 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 | Permanently block the team and remove its session and image keys. |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.