: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 objects with AES-256-GCM and send Kafka records in cleartext (#101435)
Robbiee16cadb6090a
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.tsindex 49ae34e0c6dd..3dd4ed5fea3d 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts@@ -2,7 +2,6 @@ import type { UrlPolicyDecline } from '@posthog/replay-anonymizer'import { parseJSON } from '~/common/utils/json-parse'import { parseImageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'-import type { MlDataKey } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto'import { identityDigest } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema'import { ImageFetchBlockReason, isImageFetchBlockReason } from './block-reason'@@ -31,7 +30,8 @@ export type StoredRepublishReason =export type RepublishReason = StoredRepublishReasonexport interface FetchCandidate {- dataKey?: MlDataKey+ /** Raw UUIDv7 session ID of the v2 session that collected the URL; a v1 record carries none. */+ sessionId?: stringoriginalRef: stringcurrentUrl: stringhost: string@@ -52,6 +52,7 @@ export interface FrontierRecord {jobs: Array<Pick<FetchCandidate,+ | 'sessionId'| 'originalRef'| 'currentUrl'| 'remainingHops'@@ -218,6 +219,7 @@ function parseJob(job: unknown, kafkaKey: string): ParsedJob {return { kind: 'rejected', reason: 'bad_url' }}const {+ sessionId,originalRef,currentUrl,remainingHops,@@ -230,6 +232,7 @@ function parseJob(job: unknown, kafkaKey: string): ParsedJob {lowOriginDiversityDeferred,} = jobif (+ (sessionId !== undefined && typeof sessionId !== 'string') ||typeof originalRef !== 'string' ||typeof currentUrl !== 'string' ||!isNonNegativeSafeInteger(remainingHops) ||@@ -264,6 +267,7 @@ function parseJob(job: unknown, kafkaKey: string): ParsedJob {return {kind: 'candidate',candidate: {+ ...(sessionId ? { sessionId } : {}),originalRef,currentUrl,host: canonical.host,@@ -284,6 +288,7 @@ export function serializeFrontierRecord(candidates: FetchCandidate[]): Buffer {const record: FrontierRecord = {v: 2,jobs: candidates.map((candidate) => ({+ ...(candidate.sessionId ? { sessionId: candidate.sessionId } : {}),originalRef: candidate.originalRef,currentUrl: candidate.currentUrl,remainingHops: candidate.remainingHops,@@ -299,7 +304,7 @@ export function serializeFrontierRecord(candidates: FetchCandidate[]): Buffer {}export function fetchCandidateHistoryKey(candidate: FetchCandidate): string {- return candidate.dataKey?.identity.sessionId- ? `${candidate.originalRef}:session:${identityDigest(candidate.dataKey.identity.sessionId)}`+ return candidate.sessionId+ ? `${candidate.originalRef}:session:${identityDigest(candidate.sessionId)}`: candidate.originalRef}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.tsindex 0e7c701b3db1..ed4ca32172b0 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts@@ -2,7 +2,7 @@ import { KafkaProducerWrapper } from '~/common/kafka/producer'import { ConcurrencyController } from '~/common/utils/concurrencyController'import { logger } from '~/common/utils/logger'import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport'-import { encryptedKafkaValue } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport'+import { mlKafkaRecord } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport'import {FetchCandidate,@@ -111,7 +111,7 @@ export class FrontierPublisher {if (!result.bytes || !result.contentType) {throw new Error('an image publish needs response bytes and a content type')}- const encrypted = encryptedKafkaValue(candidate.dataKey, 'image-source', result.bytes, candidate.originalRef)+ const record = mlKafkaRecord(candidate.sessionId ? '2' : '1', result.bytes)const headers: Record<string, string> = {'content-type': result.contentType,[CAPTURE_TIMESTAMP_HEADER]: String(candidate.firstSeenAtMs),@@ -129,8 +129,8 @@ export class FrontierPublisher {this.producer.produce({topic: this.options.scrubTopic,key: Buffer.from(candidate.originalRef),- value: encrypted.value,- headers: { ...headers, ...encrypted.headers },+ value: record.value,+ headers: { ...headers, ...record.headers },}),})@@ -230,7 +230,7 @@ class BufferedRepublishBatch implements RepublishBatch {private planMessages(): PlannedRepublishMessage[] {const groups = new Map<string, PendingRepublish[]>()for (const item of this.pending) {- const key = `${item.destination.topic}\0${item.candidate.registrableDomain}\0${JSON.stringify(item.candidate.dataKey?.identity ?? null)}`+ const key = `${item.destination.topic}\0${item.candidate.registrableDomain}\0${item.candidate.sessionId ?? ''}`const group = groups.get(key)if (group) {group.push(item)@@ -304,9 +304,8 @@ class BufferedRepublishBatch implements RepublishBatch {await this.producer.produce({topic: plan.topic,key: Buffer.from(plan.registrableDomain),- ...encryptedKafkaValue(- plan.candidates[0].dataKey,- 'image-frontier',+ ...mlKafkaRecord(+ plan.candidates[0].sessionId ? '2' : '1',serializeFrontierRecord(plan.candidates)),})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.tsindex 2dd6e023a4e4..5f38dc7e7654 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts@@ -3,9 +3,10 @@ import pLimit from 'p-limit'import { logger } from '~/common/utils/logger'import {- MlKafkaEncryption,+ MlDecodedMessage,+ MlKafkaTransport,ingestionVersion,- validateImageOwner,+ validateImageRefVersion,} from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport'import { fetchCandidateHistoryKey } from './collected-urls-record'@@ -56,7 +57,7 @@ export class UrlFetchConsumer {private readonly runner?: FetchPass,private readonly deadLetters: FrontierDeadLetterSink | null = null,private readonly topHogMetrics?: ImageFetchTopHogMetrics,- private readonly keyManager?: MlKafkaEncryption+ private readonly keyManager?: MlKafkaTransport) {if (!Number.isInteger(options.seenTtlSeconds) || options.seenTtlSeconds < 60 * 60) {throw new Error('AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS must be at least 3600')@@ -68,27 +69,27 @@ export class UrlFetchConsumer {}public async handleBatch(messages: Message[], nowMs: number): Promise<void> {- const decoded = this.keyManager- ? await this.keyManager.read(messages, 'image-frontier')+ const decoded: MlDecodedMessage[] = this.keyManager+ ? await this.keyManager.read(messages): messages.map((message) => {let version: 1 | 2try {version = ingestionVersion(message)} catch (error) {if (error instanceof Error && error.message === 'Unsupported ML ingestion version') {- return { message, original: message, key: undefined, invalid: true }+ return { message, original: message, version: undefined, invalid: true }}throw error}if (version === 2) {throw new Error('ML v2 frontier requires key manager configuration')}- return { message, original: message, key: undefined, invalid: undefined }+ return { message, original: message, version, invalid: undefined }})- const decodedValid = decoded.filter((entry) => !entry.invalid)- const encrypted = decodedValid.filter((entry) => entry.key).length- ImageFetchConsumerMetrics.incrementVersion('2', encrypted)- ImageFetchConsumerMetrics.incrementVersion('1', decodedValid.length - encrypted)+ const decodedValid = decoded.filter((entry) => !entry.invalid && !entry.legacy)+ const v2 = decodedValid.filter((entry) => entry.version === 2).length+ ImageFetchConsumerMetrics.incrementVersion('2', v2)+ ImageFetchConsumerMetrics.incrementVersion('1', decodedValid.length - v2)const startedAt = process.hrtime.bigint()const republishDeadlineAtMonotonicMs = performance.now() + REPUBLISH_DEADLINE_FROM_BATCH_START_MSconst drops = new Map<UrlDropReason, number>()@@ -104,7 +105,10 @@ export class UrlFetchConsumer {const stage = ImageFetchProcessingMetrics.start('batch_parse')try {- for (const { message, original, key, invalid } of decoded) {+ for (const { message, original, version, invalid, legacy } of decoded) {+ if (legacy) {+ continue+ }if (invalid) {rejectedRecords.push({ message: original, reasons: ['malformed'] })continue@@ -131,14 +135,17 @@ export class UrlFetchConsumer {}try {for (const candidate of parsed.candidates) {- validateImageOwner(candidate.originalRef, key)+ validateImageRefVersion(candidate.originalRef, version ?? 1)+ if (version === 2 && !candidate.sessionId) {+ throw new Error('A v2 fetch job needs its session ID')+ }}} catch {rejectedRecords.push({ message: original, reasons: ['bad_ref'] })continue}for (const candidate of parsed.candidates) {- const partitionCandidate = { ...candidate, dataKey: key, sourcePartitions: [message.partition] }+ const partitionCandidate = { ...candidate, sourcePartitions: [message.partition] }const existing = candidatesByRef.get(fetchCandidateHistoryKey(partitionCandidate))if (existing) {dedupedInBatch += 1diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.tsindex ce43b8af9a8e..058412cd3966 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts@@ -4,7 +4,7 @@ import { gzipSync } from 'node:zlib'import { MlKeyReader } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader'import { MlKeyManager } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime'import { INGESTION_VERSION_HEADER } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema'-import { MlKafkaEncryption } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport'+import { MlKafkaTransport } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport'import { hashImageBytes, imageRef, urlRef } from './content-ref'import { ImageBatcher, OffsetStore } from './image-batcher'@@ -94,7 +94,7 @@ describe('ImageBatcher', () => {const offsets = new FakeOffsets()const park = jest.fn().mockRejectedValueOnce(new Error('dlq unavailable')).mockResolvedValue(undefined)const keyManager = {- kafka: new MlKafkaEncryption({+ kafka: new MlKafkaTransport({read: jest.fn().mockResolvedValue(new Map()),} as unknown as MlKeyReader),} as MlKeyManager@@ -132,7 +132,7 @@ describe('ImageBatcher', () => {bytes: invalid.value,headers: { [INGESTION_VERSION_HEADER]: '2' },detail: {- reason: 'invalid_encryption',+ reason: 'invalid_record',sourceTopic: invalid.topic,sourcePartition: 0,sourceOffset: 0,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.tsindex 9b9c3fafb012..e60b1275142d 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts@@ -10,7 +10,7 @@ import {imageKeyId,tableKeyString,} from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema'-import { ingestionVersion } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport'+import { MlDecodedMessage, ingestionVersion } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport'import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'import { parseImageRef } from './content-ref'@@ -221,21 +221,22 @@ export class ImageBatcher {if (messages.length) {ImageScrubConsumerMetrics.observeBatchMessages(messages.length)}- const decoded = this.keyManager- ? await this.keyManager.kafka.read(messages, 'image-source', true)+ const decoded: MlDecodedMessage[] = this.keyManager+ ? await this.keyManager.kafka.read(messages, { bindKafkaKey: true }): messages.map((message) => {- if (ingestionVersion(message) === 2) {+ const version = ingestionVersion(message)+ if (version === 2) {throw new Error('ML v2 images require key manager configuration')}- return { message, original: message, key: undefined, invalid: undefined }+ return { message, original: message, version, invalid: undefined }})- const decodedValid = decoded.filter((entry) => !entry.invalid)- const encrypted = decodedValid.filter((entry) => entry.key).length- ImageScrubConsumerMetrics.incrementVersion('2', encrypted)- ImageScrubConsumerMetrics.incrementVersion('1', decodedValid.length - encrypted)+ const decodedValid = decoded.filter((entry) => !entry.invalid && !entry.legacy)+ const v2 = decodedValid.filter((entry) => entry.version === 2).length+ ImageScrubConsumerMetrics.incrementVersion('2', v2)+ ImageScrubConsumerMetrics.incrementVersion('1', decodedValid.length - v2)for (const entry of decoded.filter((entry) => entry.invalid)) {if (!this.deadLetters) {- throw new Error('Invalid encrypted ML image requires a dead-letter destination')+ throw new Error('An invalid ML image record requires a dead-letter destination')}await this.parkImageUntilAccepted({@@ -243,7 +244,7 @@ export class ImageBatcher {bytes: entry.original.value ?? Buffer.alloc(0),headers: parseKafkaHeaders(entry.original.headers),detail: {- reason: 'invalid_encryption',+ reason: 'invalid_record',sourceTopic: entry.original.topic,sourcePartition: entry.original.partition,sourceOffset: entry.original.offset,@@ -252,9 +253,7 @@ export class ImageBatcher {controller.signal)}- const byOriginal = new Map(- decoded.filter((entry) => !entry.invalid).map((entry) => [entry.original, entry.message])- )+ const byOriginal = new Map(decodedValid.map((entry) => [entry.original, entry.message]))const planned = this.planBatch(messages.map((message) => byOriginal.get(message) ?? { ...message, value: null }))diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.tsindex 28e8df9b154d..6bc022acfd40 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.ts@@ -3,7 +3,8 @@ import { ParquetReader } from '@dsnp/parquetjs'import sodium from 'libsodium-wrappers'import { parseJSON } from '~/common/utils/json-parse'-import { MlDataKey, decryptEnvelope } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto'+import { MlDataKey } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto'+import { decryptEnvelope } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/envelope-testing'import { ImageShardStore } from './image-shard-store'diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.test.tsindex ca37afbe0d79..16eaf3e12be9 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.test.ts@@ -8,10 +8,11 @@ import { parseJSON } from '~/common/utils/json-parse'import { BlockMetadataBatcher, OffsetStore } from './block-metadata-batcher'import { BlockMetadataParquetStore } from './block-metadata-parquet-store'import { MlBlockMetadataRow } from './block-metadata-row'-import { MlDataKey, decryptEnvelope } from './keys/crypto'+import { MlDataKey } from './keys/crypto'+import { decryptEnvelope } from './keys/envelope-testing'import { MlKeyReader } from './keys/reader'import { sessionKeyId, tableKeyString } from './keys/schema'-import { MlKafkaEncryption, encryptedKafkaValue } from './keys/transport'+import { MlKafkaTransport, mlKafkaRecord } from './keys/transport'const row = (sessionId: string): MlBlockMetadataRow => ({session_id: sessionId,@@ -131,9 +132,8 @@ describe('BlockMetadataBatcher', () => {{ kind: 'json_ld', eventIndex: 0, eventTimestamp: timestamp, windowId: 'w1', rootTypes: ['Product'] },],}- const encrypted = encryptedKafkaValue(- key,- 'metadata',+ const encrypted = mlKafkaRecord(+ '2',Buffer.from(JSON.stringify({ ...metadata, distinct_id: 'legacy-user', distinctId: 'unexpected-user' })))const message = {@@ -149,7 +149,7 @@ describe('BlockMetadataBatcher', () => {offsets,{ flushIntervalMs: 1000, maxRows: 1 },0,- new MlKafkaEncryption(reader)+ new MlKafkaTransport(reader))await expect(batcher.handleBatch([message], 0)).rejects.toThrow('index upload failed')expect(offsets.offsetsStore).not.toHaveBeenCalled()diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.tsindex 17f260d5eb33..8b03ce26be2d 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.ts@@ -9,7 +9,7 @@ import { parseBlockMetadataMessages } from './block-metadata-message'import { BlockMetadataParquetStore } from './block-metadata-parquet-store'import { MlBlockMetadataRow } from './block-metadata-row'import { MlEncryptedEnvelope, encryptEnvelope } from './keys/crypto'-import { MlKafkaEncryption, ingestionVersion } from './keys/transport'+import { MlDecodedMessage, MlKafkaTransport, ingestionVersion } from './keys/transport'import { MlParquetSinkMetrics } from './metrics'import { EncryptedReplayIndex, encryptReplayIndex } from './replay-index'@@ -37,7 +37,7 @@ export class BlockMetadataBatcher {private readonly offsetStore: OffsetStore,private readonly options: BlockMetadataBatcherOptions,nowMs: number,- private readonly keyManager?: MlKafkaEncryption+ private readonly keyManager?: MlKafkaTransport) {this.lastFlushMs = nowMs}@@ -47,8 +47,8 @@ export class BlockMetadataBatcher {for (const message of messages) {this.bufferedBytes += message.value?.length ?? 0}- const decoded = this.keyManager- ? await this.keyManager.read(messages, 'metadata')+ const decoded: MlDecodedMessage[] = this.keyManager+ ? await this.keyManager.read(messages, { sessionIdentity: rowSessionIdentity }): messages.map((message) => {if (ingestionVersion(message) === 2) {throw new Error('ML v2 metadata requires key manager configuration')@@ -57,9 +57,12 @@ export class BlockMetadataBatcher {})MlParquetSinkMetrics.incRowsRejected('key_missing', messages.length - decoded.length)let encryptedRows = 0- for (const { message, key, invalid } of decoded) {+ for (const { message, key, invalid, legacy } of decoded) {+ if (legacy) {+ continue+ }if (invalid) {- MlParquetSinkMetrics.incRowsRejected('invalid_envelope')+ MlParquetSinkMetrics.incRowsRejected('invalid_record')}if (key) {let row: unknown@@ -87,7 +90,7 @@ export class BlockMetadataBatcher {}MlParquetSinkMetrics.incRowsParsed(encryptedRows)for (const row of parseBlockMetadataMessages(- decoded.filter(({ key, invalid }) => !key && !invalid).map(({ message }) => message)+ decoded.filter(({ key, invalid, legacy }) => !key && !invalid && !legacy).map(({ message }) => message))) {if (row.format_version !== 2) {this.buffer.push(row)@@ -145,3 +148,20 @@ export class BlockMetadataBatcher {}}}++function rowSessionIdentity(message: Message): { teamId: number; sessionId: string } | null {+ let row: unknown+ try {+ row = parseJSON(message.value?.toString() ?? '')+ } catch {+ return null+ }+ if (!row || typeof row !== 'object' || !('session_id' in row) || !('team_id' in row)) {+ return null+ }+ const { session_id, team_id } = row as { session_id: unknown; team_id: unknown }+ if (typeof session_id !== 'string' || typeof team_id !== 'string' || !/^[0-9]+$/.test(team_id)) {+ return null+ }+ return { teamId: Number(team_id), sessionId: session_id }+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.test.tsindex c7a3b3a92ca8..f53992b0ab7b 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.test.ts@@ -7,8 +7,8 @@ import { parseJSON } from '~/common/utils/json-parse'import { BlockMetadataParquetStore } from './block-metadata-parquet-store'import { MlBlockMetadataRow } from './block-metadata-row'-import { MlDataKey, decryptEnvelope } from './keys/crypto'-import { TrainingEncryptionVector } from './keys/test-vectors'+import { MlDataKey } from './keys/crypto'+import { TrainingEncryptionVector, decryptEnvelope } from './keys/envelope-testing'import { encryptReplayIndex, replayIndexPartitions } from './replay-index'const row = (sessionId: string, teamId: string): MlBlockMetadataRow => ({diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/batch-controller.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/batch-controller.tsindex bf5fefeec382..d02db7f562e0 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/batch-controller.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/batch-controller.ts@@ -30,8 +30,8 @@ export class MlKeyBatchController implements KeyStore, RecordingEncryptor {private readonly encryption: MlKeyEncryption) {}- public async start(): Promise<void> {- await this.encryption.start()+ public start(): Promise<void> {+ return Promise.resolve()}public stop(): void {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 4120b9ea2bf8..36c2e4b55dff 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,9 +1,7 @@-import { KMSClient } from '@aws-sdk/client-kms'-import { parseJSON } from '~/common/utils/json-parse'-import { MlDataKey, MlKeyEncryption, decryptEnvelope, encryptEnvelope } from './crypto'-import { TrainingEncryptionVector } from './test-vectors'+import { MlDataKey, encryptEnvelope } from './crypto'+import { TrainingEncryptionVector, decryptEnvelope } from './envelope-testing'import { validateImageOwner } from './transport'const key: MlDataKey = {@@ -17,10 +15,6 @@ const key: MlDataKey = {}describe('ML payload encryption', () => {- beforeAll(async () => {- await new MlKeyEncryption({ send: jest.fn() } as unknown as KMSClient, 'test-key').start()- })-it.each(['rrweb', 'metadata', 'image-source', 'image-frontier', 'image-shard', 'image-index', 'score'])('binds %s payloads to their purpose and owner',(kind) => {@@ -58,7 +52,7 @@ describe('ML payload encryption', () => {expect(() => validateImageOwner(ref.replace('2026-09', '2026-10'), sessionKey)).toThrow('ownership mismatch')})- it('decrypts the shared Python encryption vector', () => {+ it('decrypts the shared encryption vector', () => {expect(decryptEnvelope({diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto.tsindex b4a84849cd77..b518d5881a84 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto.ts@@ -1,32 +1,43 @@import { DecryptCommand, GenerateDataKeyCommand, KMSClient } from '@aws-sdk/client-kms'-import sodium from 'libsodium-wrappers'import { LRUCache } from 'lru-cache'-import { isDeepStrictEqual } from 'node:util'+import { createCipheriv, randomBytes } from 'node:crypto'import pLimit from 'p-limit'-import { parseJSON } from '~/common/utils/json-parse'import { MlKeyRequest, MlMirrorMetrics } from '~/ingestion/pipelines/sessionreplay/ml-mirror/metrics'import { MlKeyIdentity, wrappingContext } from './schema'-export const KEY_READ_LEASE_MS = 300_000--export class MlKeyReadExpiredError extends Error {}-export interface MlDataKey {identity: MlKeyIdentityplaintext: Bufferwrapped: Buffer- decryptUntil?: number}+/** The raw payload sealed with AES-256-GCM; the canonical JSON of `{ v, context }` is the additional authenticated data. */export interface MlEncryptedEnvelope {- v: 2+ v: 3context: MlKeyIdentity & { kind: string; ref?: string }nonce: stringciphertext: string}+const NONCE_BYTES = 12+export const TAG_BYTES = 16++/** Both readers rebuild this byte for byte, so key order is sorted and there is no whitespace. */+export function canonicalJson(value: unknown): string {+ if (Array.isArray(value)) {+ return `[${value.map(canonicalJson).join(',')}]`+ }+ if (value && typeof value === 'object') {+ return `{${Object.keys(value)+ .sort()+ .map((k) => `${JSON.stringify(k)}:${canonicalJson((value as Record<string, unknown>)[k])}`)+ .join(',')}}`+ }+ return JSON.stringify(value)+}+export class MlKeyEncryption {private readonly cache: LRUCache<string, Buffer>private readonly pending = new Map<string, Promise<Buffer>>()@@ -48,10 +59,6 @@ export class MlKeyEncryption {}}- public async start(): Promise<void> {- await sodium.ready- }-private async request<T>(kind: MlKeyRequest, operation: () => Promise<T>): Promise<T> {return this.concurrency(async () => {const queuedAt = performance.now()@@ -138,41 +145,15 @@ export class MlKeyEncryption {export function encryptEnvelope(key: MlDataKey, kind: string, data: Buffer, ref?: string): Buffer {const context = { ...key.identity, kind, ...(ref ? { ref } : {}) }- const nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES)- const authenticated = Buffer.from(JSON.stringify({ context, data: data.toString('base64') }))+ const nonce = randomBytes(NONCE_BYTES)+ const cipher = createCipheriv('aes-256-gcm', key.plaintext, nonce, { authTagLength: TAG_BYTES })+ cipher.setAAD(Buffer.from(canonicalJson({ v: 3, context })))+ const ciphertext = Buffer.concat([cipher.update(data), cipher.final(), cipher.getAuthTag()])const envelope: MlEncryptedEnvelope = {- v: 2,+ v: 3,context,- nonce: Buffer.from(nonce).toString('base64'),- ciphertext: Buffer.from(sodium.crypto_secretbox_easy(authenticated, nonce, key.plaintext)).toString('base64'),+ nonce: nonce.toString('base64'),+ ciphertext: ciphertext.toString('base64'),}return Buffer.from(JSON.stringify(envelope))}--export function decryptEnvelope(key: MlDataKey, envelope: MlEncryptedEnvelope, kind: string, ref?: string): Buffer {- if (key.decryptUntil !== undefined && performance.now() >= key.decryptUntil) {- throw new MlKeyReadExpiredError('ML key read lease expired; read the key again')- }- const decoded: unknown = parseJSON(- Buffer.from(- sodium.crypto_secretbox_open_easy(- Buffer.from(envelope.ciphertext, 'base64'),- Buffer.from(envelope.nonce, 'base64'),- key.plaintext- )- ).toString('utf8')- )- if (!decoded || typeof decoded !== 'object' || !('context' in decoded) || !('data' in decoded)) {- throw new Error('Invalid authenticated ML envelope')- }- const context = { ...key.identity, kind, ...(ref ? { ref } : {}) }- if (- envelope.v !== 2 ||- !isDeepStrictEqual(decoded.context, context) ||- !isDeepStrictEqual(envelope.context, context) ||- typeof decoded.data !== 'string'- ) {- throw new Error('ML envelope context mismatch')- }- return Buffer.from(decoded.data, 'base64')-}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 0695dc8aa88e..b70cb215eaff 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@@ -7,14 +7,14 @@"key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=","data": "c3ludGhldGljIGludGVyb3BlcmFiaWxpdHkgcGF5bG9hZA==","envelope": {- "v": 2,+ "v": 3,"context": {"teamId": 7,"organizationId": "00000000-0000-4000-8000-000000000007","sessionId": "01994569-4380-7000-8000-000000000007","kind": "rrweb"},- "nonce": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMD",- "ciphertext": "J7ZDxBv0xIHU+NbDMakk4Zfw4/QVzp9N/3Nou2Fw5EHMoFUnJlmLR1uMpdNQ9RzghmLG2IQZxuytZzl6nXIwDjThieTFFxsTD88iry/Q3f/IUXtrfO8AwN71Edwmw5cQe4BWZiI1F3lmYLi3SqiwWWOgDAQcaFAy95e9dIaB2uMh74M1617MqtZLMQnnvLwoDUSk60ovZhTwL5spBFy02JOaAOxpazluT8+qeuQEzfgI+/54rUzdJPg6gScSOBIAQWp3Jbk9xVOrxtdqLB4BtPKAPYwqFwIJtuS/UQ=="+ "nonce": "AwMDAwMDAwMDAwMD",+ "ciphertext": "VofNdzJNKisZYCoynzKNY51Zko7W/PgZW6enwYKcLNfQw1APuYhuzy8mpJ3qd2oMKRc="}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/envelope-testing.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/envelope-testing.tsnew file mode 100644index 000000000000..277c6751c931--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/envelope-testing.ts@@ -0,0 +1,25 @@+import { createDecipheriv } from 'node:crypto'+import { isDeepStrictEqual } from 'node:util'++import { MlDataKey, MlEncryptedEnvelope, TAG_BYTES, canonicalJson } from './crypto'+import vector from './encryption-vector.json'++/** Nothing in production reads an envelope; tests use this to check what the encryptors write. */+export function decryptEnvelope(key: MlDataKey, envelope: MlEncryptedEnvelope, kind: string, ref?: string): Buffer {+ const context = { ...key.identity, kind, ...(ref ? { ref } : {}) }+ if (envelope.v !== 3 || !isDeepStrictEqual(envelope.context, context)) {+ throw new Error('ML envelope context mismatch')+ }+ const sealed = Buffer.from(envelope.ciphertext, 'base64')+ if (sealed.length < TAG_BYTES) {+ throw new Error('Invalid authenticated ML envelope')+ }+ const decipher = createDecipheriv('aes-256-gcm', key.plaintext, Buffer.from(envelope.nonce, 'base64'), {+ authTagLength: TAG_BYTES,+ })+ decipher.setAAD(Buffer.from(canonicalJson({ v: 3, context })))+ decipher.setAuthTag(sealed.subarray(sealed.length - TAG_BYTES))+ return Buffer.concat([decipher.update(sealed.subarray(0, sealed.length - TAG_BYTES)), decipher.final()])+}++export const TrainingEncryptionVector = { ...vector, envelope: vector.envelope as MlEncryptedEnvelope }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 603e7c5701d9..cd3b22222209 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@@ -23,7 +23,7 @@ import { DynamoItem, MlKeyDynamoDB, encodeKey } from './dynamodb'import { MlSessionKeyStore } from './key-store'import { MlKeyReader } from './reader'import { MlSessionIdentity, imageKeyId, monthKeyIndexId, sessionKeyId, tableKeyString, teamBlockId } from './schema'-import { MlKafkaEncryption, encryptedKafkaValue } from './transport'+import { MlKafkaTransport, mlKafkaRecord } from './transport'const session: MlSessionIdentity = {teamId: 7,@@ -78,7 +78,7 @@ describe('ML session key batches', () => {let reader: MlKeyReaderlet generated: number- beforeEach(async () => {+ beforeEach(() => {boundary = new DynamoBoundary()generated = 0encryption = new MlKeyEncryption(@@ -97,7 +97,6 @@ describe('ML session key batches', () => {8,1_000_000_000)- await encryption.start()const db = new MlKeyDynamoDB(boundary as unknown as DynamoDBClient, table)store = new MlSessionKeyStore(db, encryption)reader = new MlKeyReader(db, encryption)@@ -391,16 +390,15 @@ describe('ML session key batches', () => {expect(committed).toBe(true)})it.each(['invalid-json', 'oversized-session', 'invalid-session', 'invalid-month'])(- 'reports accepted, malformed (%s) and deleted encrypted metadata separately',+ 'reports accepted, malformed (%s) and deleted metadata rows separately',async (malformed) => {register.resetMetrics()const deleted = { ...session, sessionId: '01994569-4380-7000-8000-000000000008' }const batch = await store.prepare([session, deleted])await batch.commit()const messages = [session, deleted].map((identity, offset) => {- const encoded = encryptedKafkaValue(- batch.get(identity.teamId, identity.sessionId)!.session,- 'metadata',+ const encoded = mlKafkaRecord(+ '2',Buffer.from(JSON.stringify({...toBlockMetadataRow(@@ -425,8 +423,8 @@ describe('ML session key batches', () => {} as Message})boundary.items.delete(tableKeyString(sessionKeyId(deleted.teamId, deleted.sessionId)))- const invalidEnvelope = parseJSON(messages[0].value!.toString())- invalidEnvelope.context.sessionId =+ const invalidRow = parseJSON(messages[0].value!.toString())+ invalidRow.session_id =malformed === 'oversized-session'? 'a'.repeat(1025): malformed === 'invalid-month'@@ -435,7 +433,14 @@ describe('ML session key batches', () => {messages.push({...messages[0],offset: 2,- value: Buffer.from(malformed === 'invalid-json' ? 'invalid' : JSON.stringify(invalidEnvelope)),+ value: Buffer.from(malformed === 'invalid-json' ? 'invalid' : JSON.stringify(invalidRow)),+ })+ messages.push({+ ...messages[0],+ offset: 3,+ value: Buffer.from(+ JSON.stringify({ v: 2, context: { teamId: 7 }, nonce: 'AwMD', ciphertext: 'J7ZDxBv0xIHU' })+ ),})const upload = jest.fn().mockResolvedValue({})const offsetsStore = jest.fn()@@ -449,18 +454,22 @@ describe('ML session key batches', () => {{ offsetsStore },{ flushIntervalMs: 1000, maxRows: 1 },0,- new MlKafkaEncryption(reader)+ new MlKafkaTransport(reader))await batcher.handleBatch(messages, 0)expect(upload).toHaveBeenCalledTimes(1)- expect(offsetsStore).toHaveBeenCalledWith([{ topic: 'metadata', partition: 0, offset: 3 }])+ expect(offsetsStore).toHaveBeenCalledWith([{ topic: 'metadata', partition: 0, offset: 4 }])+ const legacy = await register+ .getSingleMetric('recording_blob_ingestion_v2_ml_legacy_envelopes_dropped_total')!+ .get()+ expect(legacy.values[0].value).toBe(1)const accepted = await register.getSingleMetric('ml_mirror_parquet_sink_rows_parsed_total')!.get()expect(accepted.values[0].value).toBe(1)const rejected = await register.getSingleMetric('ml_mirror_parquet_sink_rows_rejected_total')!.get()expect(rejected.values).toEqual(expect.arrayContaining([expect.objectContaining({ labels: { reason: 'key_missing' }, value: 1 }),- expect.objectContaining({ labels: { reason: 'invalid_envelope' }, value: 1 }),+ expect.objectContaining({ labels: { reason: 'invalid_record' }, value: 1 }),]))}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader.tsindex b012108a4e43..d4cf874e258e 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader.ts@@ -1,4 +1,4 @@-import { KEY_READ_LEASE_MS, MlDataKey, MlKeyEncryption } from './crypto'+import { MlDataKey, MlKeyEncryption } from './crypto'import { MlKeyDynamoDB } from './dynamodb'import { MlKeyIdentity, TableKey, tableKeyString, teamBlockId } from './schema'@@ -9,7 +9,6 @@ export class MlKeyReader {) {}public async read(keys: TableKey[]): Promise<Map<string, MlDataKey>> {- const decryptUntil = performance.now() + KEY_READ_LEASE_MSconst stored = await this.db.read(keys)const identities = new Map<string, MlKeyIdentity>()for (const [id, item] of stored) {@@ -35,10 +34,7 @@ export class MlKeyReader {if (state.has(tableKeyString(teamBlockId(identity.teamId)))) {return}- result.set(id, {- ...(await this.encryption.decrypt(identity, Buffer.from(stored.get(id)!.wrapped_key.B!))),- decryptUntil,- })+ result.set(id, await this.encryption.decrypt(identity, Buffer.from(stored.get(id)!.wrapped_key.B!)))}))return resultdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime.tsindex 58dd20b6b84b..f94b7e4e80c2 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime.ts@@ -6,7 +6,7 @@ import { MlKeyEncryption } from './crypto'import { MlKeyDynamoDB } from './dynamodb'import { MlSessionKeyStore } from './key-store'import { MlKeyReader } from './reader'-import { MlKafkaEncryption } from './transport'+import { MlKafkaTransport } from './transport'export interface MlKeyManagerConfig {AI_RESEARCH_REPLAY_KEY_TABLE: string@@ -22,7 +22,7 @@ export class MlKeyManager {public readonly encryption: MlKeyEncryptionpublic readonly reader: MlKeyReaderpublic readonly controller: MlKeyBatchController- public readonly kafka: MlKafkaEncryption+ public readonly kafka: MlKafkaTransportprivate readonly dynamo: DynamoDBClientprivate readonly kms: KMSClient@@ -47,11 +47,11 @@ export class MlKeyManager {)this.reader = new MlKeyReader(db, this.encryption)this.controller = new MlKeyBatchController(new MlSessionKeyStore(db, this.encryption), this.encryption)- this.kafka = new MlKafkaEncryption(this.reader)+ this.kafka = new MlKafkaTransport(this.reader)}public start(): Promise<void> {- return this.encryption.start()+ return Promise.resolve()}public stop(): void {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/test-vectors.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/test-vectors.tsdeleted file mode 100644index f5706e39787a..000000000000--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/test-vectors.ts+++ /dev/null@@ -1,4 +0,0 @@-import { MlEncryptedEnvelope } from './crypto'-import vector from './encryption-vector.json'--export const TrainingEncryptionVector = { ...vector, envelope: vector.envelope as MlEncryptedEnvelope }diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport.tsindex f088603b6270..e7f57d48fb45 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport.ts@@ -3,17 +3,25 @@ import { Message } from 'node-rdkafka'import { parseKafkaHeaders } from '~/common/kafka/consumer/consumer-v1'import { parseJSON } from '~/common/utils/json-parse'import { parseImageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'+import { MlMirrorMetrics } from '~/ingestion/pipelines/sessionreplay/ml-mirror/metrics'import { sessionStartMonth } from '~/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format'-import { MlDataKey, MlEncryptedEnvelope, MlKeyReadExpiredError, decryptEnvelope, encryptEnvelope } from './crypto'+import { MlDataKey } from './crypto'import { MlKeyReader } from './reader'import { INGESTION_VERSION_HEADER, MlWireVersion, sessionKeyId, tableKeyString } from './schema'export interface MlDecodedMessage {message: Messageoriginal: Message+ version?: 1 | 2key?: MlDataKeyinvalid?: true+ /** A record in the sealed envelope shape the lanes wrote before cleartext records; consumers skip it. */+ legacy?: true+}++export interface MlSessionIdentityLocator {+ (message: Message): { teamId: number; sessionId: string } | null}export function ingestionVersion(message: Pick<Message, 'headers'>): 1 | 2 {@@ -27,25 +35,17 @@ export function ingestionVersion(message: Pick<Message, 'headers'>): 1 | 2 {throw new Error('Unsupported ML ingestion version')}-/** Only an encrypted record carries a key, so the key decides the version every producer stamps. */+/** Only a v2 session has a key, so the key decides the version every producer stamps. */export function mlWireVersion(key: MlDataKey | undefined): MlWireVersion {return key ? '2' : '1'}-export function encryptedKafkaValue(- key: MlDataKey | undefined,- kind: string,- value: Buffer,- ref?: string+/** Kafka carries the record in cleartext; the header tells consumers which identifier scheme and datasets it belongs to. */+export function mlKafkaRecord(+ version: MlWireVersion,+ value: Buffer): { value: Buffer; headers: Record<string, string> } {- return key- ? {- value: encryptEnvelope(key, kind, value, ref),- headers: {- [INGESTION_VERSION_HEADER]: mlWireVersion(key),- },- }- : { value, headers: { [INGESTION_VERSION_HEADER]: mlWireVersion(key) } }+ return { value, headers: { [INGESTION_VERSION_HEADER]: version } }}export function validateImageOwner(ref: string, key: MlDataKey | undefined): void {@@ -60,76 +60,99 @@ export function validateImageOwner(ref: string, key: MlDataKey | undefined): voithrow new Error('ML image reference ownership mismatch')}} else if (parsed?.version === 2) {- throw new Error('An ML v2 image requires an encrypted message')+ throw new Error('An ML v2 image requires a v2 session key')}}-export class MlKafkaEncryption {+export function validateImageRefVersion(ref: string, version: 1 | 2): void {+ const parsed = parseImageRef(ref)+ if (version === 2 ? parsed?.version !== 2 : parsed?.version === 2) {+ throw new Error('ML image reference version mismatch')+ }+}++function isLegacyEnvelope(value: Buffer | null | undefined): boolean {+ if (!value?.length || value[0] !== 0x7b) {+ return false+ }+ try {+ const parsed: unknown = parseJSON(value.toString())+ return (+ !!parsed &&+ typeof parsed === 'object' &&+ (parsed as { v?: unknown }).v === 2 &&+ typeof (parsed as { nonce?: unknown }).nonce === 'string' &&+ typeof (parsed as { ciphertext?: unknown }).ciphertext === 'string'+ )+ } catch {+ return false+ }+}++export class MlKafkaTransport {constructor(private readonly reader: MlKeyReader) {}- public async read(messages: Message[], kind: string, bindKafkaKey = false): Promise<MlDecodedMessage[]> {- const envelopes = new Map<Message, MlEncryptedEnvelope>()+ /**+ * Classifies a batch by wire version and, when the caller names the session each record belongs to, resolves+ * that session's key so the caller can seal its output. A record whose session key is deleted or blocked is+ * dropped, so the caller can count the gap.+ */+ public async read(+ messages: Message[],+ options: { bindKafkaKey?: boolean; sessionIdentity?: MlSessionIdentityLocator } = {}+ ): Promise<MlDecodedMessage[]> {+ const versions = new Map<Message, 1 | 2>()+ const identities = new Map<Message, { teamId: number; sessionId: string }>()const invalid = new Set<Message>()+ const legacy = new Set<Message>()for (const message of messages) {try {- if (ingestionVersion(message) === 1) {+ const version = ingestionVersion(message)+ versions.set(message, version)+ if (version === 2 && isLegacyEnvelope(message.value)) {+ legacy.add(message)continue}- if (!message.value) {- throw new Error('Missing ML encrypted payload')+ if (options.bindKafkaKey) {+ validateImageRefVersion(message.key?.toString() ?? '', version)}- const envelope = parseJSON(message.value.toString()) as MlEncryptedEnvelope- const context = envelope?.context- if (- envelope.v !== 2 ||- !context ||- !Number.isSafeInteger(context.teamId) ||- context.teamId <= 0 ||- typeof context.organizationId !== 'string' ||- typeof context.sessionId !== 'string' ||- context.kind !== kind- ) {- throw new Error('Invalid ML encrypted payload context')+ if (version === 2 && options.sessionIdentity) {+ const identity = options.sessionIdentity(message)+ if (!identity || !Number.isSafeInteger(identity.teamId) || identity.teamId <= 0) {+ throw new Error('Missing ML session identity')+ }+ sessionStartMonth(identity.sessionId)+ identities.set(message, identity)}- sessionStartMonth(context.sessionId)- envelopes.set(message, envelope)} catch {invalid.add(message)}}- const keys = await this.reader.read(- [...envelopes.values()].map(({ context }) => sessionKeyId(context.teamId, context.sessionId!))- )+ const keys = identities.size+ ? await this.reader.read(+ [...identities.values()].map((identity) => sessionKeyId(identity.teamId, identity.sessionId))+ )+ : new Map<string, MlDataKey>()+ MlMirrorMetrics.incrementMlLegacyEnvelopesDropped(legacy.size)const result: MlDecodedMessage[] = []for (const original of messages) {+ if (legacy.has(original)) {+ result.push({ original, message: original, version: 2, legacy: true })+ continue+ }if (invalid.has(original)) {- result.push({ original, message: original, invalid: true })+ result.push({ original, message: original, version: versions.get(original), invalid: true })continue}- try {- const envelope = envelopes.get(original)- if (!envelope) {- if (bindKafkaKey) {- validateImageOwner(original.key?.toString() ?? '', undefined)- }- result.push({ message: original, original })- continue- }- const key = keys.get(tableKeyString(sessionKeyId(envelope.context.teamId, envelope.context.sessionId!)))- if (!key) {- continue- }- const ref = bindKafkaKey ? original.key?.toString() : undefined- if (bindKafkaKey) {- validateImageOwner(ref ?? '', key)- }- const value = decryptEnvelope(key, envelope, kind, ref)- result.push({ original, message: { ...original, value, size: value.length }, key })- } catch (error) {- if (error instanceof MlKeyReadExpiredError) {- throw error- }- result.push({ original, message: original, invalid: true })+ const version = versions.get(original)!+ const identity = identities.get(original)+ if (!identity) {+ result.push({ original, message: original, version })+ continue+ }+ const key = keys.get(tableKeyString(sessionKeyId(identity.teamId, identity.sessionId)))+ if (key) {+ result.push({ original, message: original, version, key })}}return resultdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metadata-roundtrip.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metadata-roundtrip.test.tsindex 4653afa16689..419afcf31ac8 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metadata-roundtrip.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metadata-roundtrip.test.ts@@ -14,10 +14,11 @@ import { MlBlockMetadataOutput } from '~/ingestion/pipelines/sessionreplay/shareimport { BlockMetadataBatcher, OffsetStore } from './block-metadata-batcher'import { BlockMetadataParquetStore } from './block-metadata-parquet-store'-import { MlDataKey, decryptEnvelope } from './keys/crypto'+import { MlDataKey } from './keys/crypto'+import { decryptEnvelope } from './keys/envelope-testing'import { MlKeyReader } from './keys/reader'import { sessionKeyId, tableKeyString } from './keys/schema'-import { MlKafkaEncryption } from './keys/transport'+import { MlKafkaTransport } from './keys/transport'import { MlBlockMetadataSink } from './ml-block-metadata-sink'import { PSEUDONYM_SESSION, PSEUDONYM_TEAM, pseudonymize } from './pseudonymize'@@ -117,7 +118,7 @@ describe('ML metadata producer → sink round-trip', () => {offsetStore,{ flushIntervalMs: 60_000, maxRows: 1_000 },0,- new MlKafkaEncryption(reader)+ new MlKafkaTransport(reader))const messages = produced.map(diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.tsindex f06d5862d87a..74b1d6f6df4a 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts@@ -63,6 +63,10 @@ export class MlMirrorMetrics {labelNames: ['outcome'],})+ private static readonly mlLegacyEnvelopesDropped = new Counter({+ name: 'recording_blob_ingestion_v2_ml_legacy_envelopes_dropped_total',+ help: 'Kafka records still in the sealed envelope shape the ML lanes wrote before they switched to cleartext records. The consumers drop them without dead-lettering, so this counter is the only trace of the backlog draining; once it stays at zero after a rollout, nothing else reads that shape',+ })private static readonly mlProducedVersion = new Counter({name: 'recording_blob_ingestion_v2_ml_produced_version_total',help: 'Kafka records the mirror delivered, by lane and wire format version, counted on the delivery ack. Version 2 is encrypted per session and version 1 is cleartext, so the split across a deploy is how far the encryption switchover has reached. The consumer counters count records too, so the two rates compare directly. A lane stuck on version 1 means the session key never resolved, which no other mirror metric distinguishes from ordinary traffic',@@ -175,6 +179,12 @@ export class MlMirrorMetrics {this.mlImagesCollected.labels(outcome).inc(count)}+ public static incrementMlLegacyEnvelopesDropped(count: number): void {+ if (count > 0) {+ this.mlLegacyEnvelopesDropped.inc(count)+ }+ }+public static incrementMlProducedVersion(lane: MlProducedLane, version: MlWireVersion, count: number): void {if (count > 0) {this.mlProducedVersion.labels(lane, version).inc(count)@@ -310,7 +320,7 @@ export class MlParquetSinkMetrics {this.rowsParsed.inc(count)}public static incRowsRejected(- reason: 'parse_failed' | 'invalid' | 'invalid_envelope' | 'key_missing',+ reason: 'parse_failed' | 'invalid' | 'invalid_record' | 'key_missing',count = 1): void {this.rowsRejected.labels(reason).inc(count)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.tsindex 195686fe520b..e62654c7d81a 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.ts@@ -6,7 +6,7 @@ import { ML_BLOCK_METADATA_OUTPUT, MlBlockMetadataOutput } from '~/ingestion/pipimport { toBlockMetadataRow } from './block-metadata-row'import { MlKeyReader } from './keys/reader'import { MlWireVersion, sessionKeyId, tableKeyString } from './keys/schema'-import { encryptedKafkaValue, mlWireVersion } from './keys/transport'+import { mlKafkaRecord, mlWireVersion } from './keys/transport'import { MlMirrorMetrics } from './metrics'import { usesRawSessionIdentifiers } from './session-identifier-format'@@ -36,7 +36,7 @@ export class MlBlockMetadataSink implements SessionMetadataSink {}const version = mlWireVersion(key)producedByVersion.set(version, (producedByVersion.get(version) ?? 0) + 1)- return [{ key: row.session_id, ...encryptedKafkaValue(key, 'metadata', Buffer.from(JSON.stringify(row))) }]+ return [{ key: row.session_id, ...mlKafkaRecord(version, Buffer.from(JSON.stringify(row))) }]})await this.outputs.queueMessages(ML_BLOCK_METADATA_OUTPUT, messages)for (const [version, count] of producedByVersion) {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.tsindex ff405cc7ea0f..a490a1f89b5e 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts@@ -7,7 +7,7 @@ import { ML_IMAGE_SCRUB_OUTPUT, MlImageScrubOutput } from '~/ingestion/pipelinesimport { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'import { MlKeyBatchController } from './keys/batch-controller'-import { encryptedKafkaValue, mlWireVersion, validateImageOwner } from './keys/transport'+import { mlKafkaRecord, mlWireVersion, validateImageOwner } from './keys/transport'import { MlMirrorMetrics } from './metrics'import { CollectedImage } from './parse-and-anonymize-step'import { usesRawSessionIdentifiers } from './session-identifier-format'@@ -83,8 +83,8 @@ export function createProduceCollectedImagesStep<ML_IMAGE_SCRUB_OUTPUT,fresh.map((image) => {validateImageOwner(image.ref, key)- const encrypted = encryptedKafkaValue(key, 'image-source', image.bytes, image.ref)- return { key: image.ref, value: encrypted.value, headers: { ...headers, ...encrypted.headers } }+ const record = mlKafkaRecord(mlWireVersion(key), image.bytes)+ return { key: image.ref, value: record.value, headers: { ...headers, ...record.headers } }})).then(() => {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.tsindex 41555cc2e8d0..e99f277271ca 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts@@ -11,7 +11,7 @@ import { ML_IMAGE_FETCH_OUTPUT, MlImageFetchOutput } from '~/ingestion/pipelinesimport { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'import { MlKeyBatchController } from './keys/batch-controller'-import { encryptedKafkaValue, mlWireVersion, validateImageOwner } from './keys/transport'+import { mlKafkaRecord, mlWireVersion, validateImageOwner } from './keys/transport'import { MlMirrorMetrics } from './metrics'import { CollectedUrl } from './parse-and-anonymize-step'import { usesRawSessionIdentifiers } from './session-identifier-format'@@ -252,6 +252,7 @@ export function createProduceCollectedUrlsStep<for (const { entry } of publishable) {const group = byDomain.get(entry.domain)const record: FrontierJob = {+ ...(key ? { sessionId } : {}),originalRef: entry.ref,currentUrl: entry.url,remainingHops: 10,@@ -279,7 +280,7 @@ export function createProduceCollectedUrlsStep<} satisfies CollectedUrlsMessage))MlMirrorMetrics.observeMlUrlRecord(slice.length, value.length)- return { key: domain, ...encryptedKafkaValue(key, 'image-frontier', value) }+ return { key: domain, ...mlKafkaRecord(mlWireVersion(key), value) }}))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 0b968224cd27..d83b805ca494 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,8 +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.reader import KEY_READ_LEASE_SECONDS-from products.ai_training.backend.privacy.store import AITrainingPrivacyStore+from products.ai_training.backend.privacy.store import KEY_READ_LEASE_SECONDS, AITrainingPrivacyStoreclass Command(BaseCommand):diff --git a/products/ai_training/backend/privacy/reader.py b/products/ai_training/backend/privacy/reader.pydeleted file mode 100644index c9685cc90937..000000000000--- a/products/ai_training/backend/privacy/reader.py+++ /dev/null@@ -1,226 +0,0 @@-from __future__ import annotations--import json-import time-import base64-import random-import hashlib-from collections import OrderedDict-from collections.abc import Sequence-from concurrent.futures import ThreadPoolExecutor-from dataclasses import field-from threading import Lock-from typing import Protocol, TypedDict, cast--from nacl.secret import SecretBox--from posthog.dataclasses import frozen--KEY_READ_LEASE_SECONDS = 300--DynamoItem = dict[str, dict[str, str | bool | bytes]]---class BatchReadResponse(TypedDict, total=False):- Responses: dict[str, list[DynamoItem]]- UnprocessedKeys: dict[str, object]---class DynamoReader(Protocol):- def batch_get_item(self, **kwargs: object) -> BatchReadResponse: ...---class KmsReader(Protocol):- def decrypt(self, **kwargs: object) -> dict[str, bytes]: ...---@frozen-class TrainingKeyIdentity:- team_id: int- organization_id: str- session_id: str | None = None- session_month: str | None = None-- def context(self, kind: str, ref: str | None = None) -> dict[str, str | int]:- context: dict[str, str | int] = {- "teamId": self.team_id,- "organizationId": self.organization_id,- "kind": kind,- }- if self.session_id is not None:- context["sessionId"] = self.session_id- if self.session_month is not None:- context["sessionMonth"] = self.session_month- if ref is not None:- context["ref"] = ref- return context-- def wrapping_context(self) -> dict[str, str]:- context = {- "purpose": "ai-research-session" if self.session_id else "ai-research-image",- "team_id": str(self.team_id),- "organization_id": self.organization_id,- }- if self.session_id:- context["session_id"] = self.session_id- if self.session_month is not None:- context["session_month"] = self.session_month- return context---@frozen-class TrainingDataKey:- identity: TrainingKeyIdentity- plaintext: bytes = field(repr=False)- decrypt_until: float = field(default_factory=lambda: time.monotonic() + KEY_READ_LEASE_SECONDS)-- def encrypt(self, kind: str, data: bytes, ref: str | None = None) -> bytes:- context = self.identity.context(kind, ref)- authenticated = json.dumps({"context": context, "data": base64.b64encode(data).decode()}).encode()- encrypted = SecretBox(self.plaintext).encrypt(authenticated)- return json.dumps(- {- "v": 2,- "context": context,- "nonce": base64.b64encode(encrypted.nonce).decode(),- "ciphertext": base64.b64encode(encrypted.ciphertext).decode(),- }- ).encode()-- def decrypt(self, envelope_bytes: bytes, kind: str, ref: str | None = None) -> bytes:- if time.monotonic() >= self.decrypt_until:- raise TimeoutError("ML key read lease expired; read the key again")- envelope = json.loads(envelope_bytes)- context = self.identity.context(kind, ref)- if envelope.get("v") != 2 or envelope.get("context") != context:- raise ValueError("ML envelope context mismatch")- decoded = json.loads(- SecretBox(self.plaintext).decrypt(- base64.b64decode(envelope["ciphertext"], validate=True),- base64.b64decode(envelope["nonce"], validate=True),- )- )- if decoded.get("context") != context:- raise ValueError("ML authenticated context mismatch")- return base64.b64decode(decoded["data"], validate=True)---@frozen-class TrainingKeyLocation:- pk: str- sk: str-- @classmethod- def session(cls, team_id: int, session_id: str) -> TrainingKeyLocation:- shard = int(hashlib.sha256(session_id.encode()).hexdigest()[:8], 16) % 32- return cls(pk=f"team:{team_id}:shard:{shard}", sk=f"session:{session_id}")-- @classmethod- def image(cls, team_id: int, session_month: str) -> TrainingKeyLocation:- return cls(pk=f"team:{team_id}", sk=f"image:{session_month}")-- def encoded(self) -> DynamoItem:- return {"pk": {"S": self.pk}, "sk": {"S": self.sk}}---class TrainingDataKeyReader:- def __init__(- self,- dynamo: DynamoReader,- kms: KmsReader,- table_name: str,- master_key_arn: str,- cache_max: int = 10000,- cache_seconds: int = 60,- kms_requests_per_second: int = 20,- ) -> None:- if cache_max < 1 or cache_seconds < 1 or kms_requests_per_second < 1:- raise ValueError("ML key cache and request limits must be positive")- self.kms_requests_per_second = kms_requests_per_second- self.next_request_at = 0.0- self.lock = Lock()- self.dynamo = dynamo- self.kms = kms- self.table_name = table_name- self.master_key_arn = master_key_arn- self.cache_max = cache_max- self.cache_seconds = cache_seconds- self.cache: OrderedDict[bytes, tuple[float, bytes]] = OrderedDict()-- def bulk_read(self, locations: Sequence[TrainingKeyLocation]) -> dict[TrainingKeyLocation, DynamoItem]:- unique = list(dict.fromkeys(locations))- result: dict[TrainingKeyLocation, DynamoItem] = {}- for start in range(0, len(unique), 100):- pending: dict[str, object] = {- self.table_name: {- "Keys": [location.encoded() for location in unique[start : start + 100]],- "ConsistentRead": True,- }- }- for attempt in range(5):- response = self.dynamo.batch_get_item(RequestItems=pending)- for row in response.get("Responses", {}).get(self.table_name, []):- result[TrainingKeyLocation(pk=str(row["pk"]["S"]), sk=str(row["sk"]["S"]))] = row- pending = response.get("UnprocessedKeys", {})- if not pending:- break- time.sleep(random.uniform(0, min(1, 0.05 * 2**attempt)))- if pending:- raise TimeoutError("ML key batch read did not complete")- return result-- def read(self, locations: Sequence[TrainingKeyLocation]) -> dict[TrainingKeyLocation, TrainingDataKey]:- decrypt_until = time.monotonic() + KEY_READ_LEASE_SECONDS- stored = self.bulk_read(locations)- identities: dict[TrainingKeyLocation, TrainingKeyIdentity] = {}- for location, row in stored.items():- if row.get("deleted", {}).get("BOOL") is True or not row.get("wrapped_key", {}).get("B"):- continue- identities[location] = TrainingKeyIdentity(- team_id=int(str(row["team_id"]["N"])),- organization_id=str(row["organization_id"]["S"]),- session_id=location.sk.removeprefix("session:") if location.sk.startswith("session:") else None,- session_month=str(row["session_month"]["S"]) if location.sk.startswith("image:") else None,- )- state = self.bulk_read(- [TrainingKeyLocation(pk=f"team:{identity.team_id}", sk="deleted") for identity in identities.values()]- )- eligible: dict[TrainingKeyLocation, TrainingKeyIdentity] = {}- for location, identity in identities.items():- if TrainingKeyLocation(pk=f"team:{identity.team_id}", sk="deleted") in state:- continue- eligible[location] = identity- with ThreadPoolExecutor(max_workers=8) as executor:- plaintexts = executor.map(- lambda location: self.decrypt_key(- eligible[location], cast(bytes, stored[location]["wrapped_key"]["B"])- ),- eligible,- )- return {- location: TrainingDataKey(identity=eligible[location], plaintext=plaintext, decrypt_until=decrypt_until)- for location, plaintext in zip(eligible, plaintexts, strict=True)- }-- def decrypt_key(self, identity: TrainingKeyIdentity, wrapped: bytes) -> bytes:- cache_id = hashlib.sha256(wrapped + json.dumps(identity.wrapping_context(), sort_keys=True).encode()).digest()- with self.lock:- cached = self.cache.get(cache_id)- if cached and cached[0] > time.monotonic():- self.cache.move_to_end(cache_id)- return cached[1]- scheduled_at = max(time.monotonic(), self.next_request_at)- self.next_request_at = scheduled_at + 1 / self.kms_requests_per_second- wait = scheduled_at - time.monotonic()- if wait > 0:- time.sleep(wait)- plaintext = self.kms.decrypt(- KeyId=self.master_key_arn, CiphertextBlob=wrapped, EncryptionContext=identity.wrapping_context()- )["Plaintext"]- if len(plaintext) != SecretBox.KEY_SIZE:- raise ValueError("Invalid ML data key")- with self.lock:- self.cache[cache_id] = (time.monotonic() + self.cache_seconds, plaintext)- while len(self.cache) > self.cache_max:- self.cache.popitem(last=False)- return plaintextdiff --git a/products/ai_training/backend/privacy/store.py b/products/ai_training/backend/privacy/store.pyindex e40d5a8534c7..cced194d11f0 100644--- a/products/ai_training/backend/privacy/store.py+++ b/products/ai_training/backend/privacy/store.py@@ -15,11 +15,12 @@ from botocore.config import Configfrom products.ai_training.backend.config import key_table_namefrom products.ai_training.backend.models import AITrainingDeletionRequest-from products.ai_training.backend.privacy.reader import KEY_READ_LEASE_SECONDSlogger = 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.diff --git a/products/ai_training/backend/tests/fixtures/encryption_vector.json b/products/ai_training/backend/tests/fixtures/encryption_vector.jsondeleted file mode 100644index 0695dc8aa88e..000000000000--- a/products/ai_training/backend/tests/fixtures/encryption_vector.json+++ /dev/null@@ -1,20 +0,0 @@-{- "context": {- "teamId": 7,- "organizationId": "00000000-0000-4000-8000-000000000007",- "sessionId": "01994569-4380-7000-8000-000000000007"- },- "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=",- "data": "c3ludGhldGljIGludGVyb3BlcmFiaWxpdHkgcGF5bG9hZA==",- "envelope": {- "v": 2,- "context": {- "teamId": 7,- "organizationId": "00000000-0000-4000-8000-000000000007",- "sessionId": "01994569-4380-7000-8000-000000000007",- "kind": "rrweb"- },- "nonce": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMD",- "ciphertext": "J7ZDxBv0xIHU+NbDMakk4Zfw4/QVzp9N/3Nou2Fw5EHMoFUnJlmLR1uMpdNQ9RzghmLG2IQZxuytZzl6nXIwDjThieTFFxsTD88iry/Q3f/IUXtrfO8AwN71Edwmw5cQe4BWZiI1F3lmYLi3SqiwWWOgDAQcaFAy95e9dIaB2uMh74M1617MqtZLMQnnvLwoDUSk60ovZhTwL5spBFy02JOaAOxpazluT8+qeuQEzfgI+/54rUzdJPg6gScSOBIAQWp3Jbk9xVOrxtdqLB4BtPKAPYwqFwIJtuS/UQ=="- }-}diff --git a/products/ai_training/backend/tests/test_privacy_reader.py b/products/ai_training/backend/tests/test_privacy_reader.pydeleted file mode 100644index 77bf0afecdbd..000000000000--- a/products/ai_training/backend/tests/test_privacy_reader.py+++ /dev/null@@ -1,74 +0,0 @@-import json-import base64-from dataclasses import replace-from pathlib import Path--from unittest import TestCase-from unittest.mock import MagicMock--from products.ai_training.backend.privacy.reader import (- TrainingDataKey,- TrainingDataKeyReader,- TrainingKeyIdentity,- TrainingKeyLocation,-)---class TestTrainingDataKeyReader(TestCase):- def test_shared_node_envelope_and_owner_binding(self) -> None:- path = Path(__file__).parent / "fixtures/encryption_vector.json"- vector = json.loads(path.read_text())- identity = TrainingKeyIdentity(- team_id=vector["context"]["teamId"],- organization_id=vector["context"]["organizationId"],- session_id=vector["context"]["sessionId"],- )- key = TrainingDataKey(identity=identity, plaintext=base64.b64decode(vector["key"]))- envelope = json.dumps(vector["envelope"]).encode()- self.assertEqual(key.decrypt(envelope, "rrweb"), base64.b64decode(vector["data"]))- for wrong_key in [- replace(key, identity=replace(identity, team_id=8)),- replace(key, identity=replace(identity, organization_id="another-organization")),- ]:- with self.assertRaises(ValueError):- wrong_key.decrypt(envelope, "rrweb")- with self.assertRaises(ValueError):- key.decrypt(envelope, "score")- with self.assertRaises(TimeoutError):- replace(key, decrypt_until=0).decrypt(envelope, "rrweb")-- def test_deleted_keys_cannot_be_restored_from_cache(self) -> None:- location = TrainingKeyLocation.session(7, "01994569-4380-7000-8000-000000000007")- rows = {- location: {- **location.encoded(),- "team_id": {"N": "7"},- "organization_id": {"S": "test"},- "wrapped_key": {"B": b"wrapped"},- },- }- dynamo = MagicMock()- dynamo.batch_get_item.side_effect = lambda **kwargs: {- "Responses": {- "table": [- rows[loc]- for item in kwargs["RequestItems"]["table"]["Keys"]- if (loc := TrainingKeyLocation(pk=item["pk"]["S"], sk=item["sk"]["S"])) in rows- ]- }- }- kms = MagicMock()- kms.decrypt.return_value = {"Plaintext": bytes([7]) * 32}- reader = TrainingDataKeyReader(dynamo, kms, "table", "kms-key")- self.assertIn(location, reader.read([location]))- self.assertIn(location, reader.read([location]))- self.assertEqual(kms.decrypt.call_count, 1)- team_block = TrainingKeyLocation(pk="team:7", sk="deleted")- rows[team_block] = {**team_block.encoded(), "deleted": {"BOOL": True}}- self.assertEqual(reader.read([location]), {})- del rows[team_block]- self.assertIn(location, reader.read([location]))- rows[location].pop("wrapped_key")- rows[location]["deleted"] = {"BOOL": True}- self.assertEqual(reader.read([location]), {})- self.assertEqual(kms.decrypt.call_count, 1)diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.mdindex d2625ac98d10..e0f4ca9c1b88 100644--- a/products/ai_training/docs/replay-data.md+++ b/products/ai_training/docs/replay-data.md@@ -41,6 +41,9 @@ A team has one image key per session start month.KMS wraps each data key with an encryption context that binds its owner and purpose.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).Ingestion processes key state in batches:@@ -68,14 +71,14 @@ Restoring a deleted wrapped key would defeat deletion.## Deletion-Existing recording, person, team, and organization deletion flows enqueue ML privacy work.+Existing recording, person, team, and organization deletion flows enqueue ML deletion work.Person deletion resolves the combined supplied and profile distinct IDs through the replay ClickHouse index.This lookup also runs when the user does not select replay deletion and includes IDs with no remaining person profile.-Only the resulting session IDs enter the ML privacy outbox.+Only the resulting session IDs enter the ML deletion outbox.A lookup failure stops the request before profile deletion so it can retry.-Team deletion and its privacy outbox request commit in the same database transaction.+Team deletion and its deletion outbox request commit in the same database transaction.If the outbox write fails, team deletion fails and can retry.-Consent changes do not enqueue privacy requests.+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.@@ -157,7 +160,7 @@ Resolve image references before training because they contain team IDs.V2 references are `image:v2:<team>:<month>:<hash>` and `imageurl:v2:<team>:<month>:<hash>`.Images do not deduplicate across teams or session months.-Source messages use session keys; stored scrubbed images use team image keys.+Kafka records between the ML lanes travel in cleartext; only objects in S3 are sealed, and stored scrubbed images use team image keys.Consumers reject malformed UUIDv7 session identifiers before reading DynamoDB.Oversized identifiers cannot fail a whole bulk key lookup.Inline images have an encrypted lookup for each reference, published after the shard and its index.@@ -170,9 +173,11 @@ Robots.txt and TDM reservation caches keep their shared origin keys and existingIt does not inherit v1 seen flags or successful fetch results.ML Kafka producers write `ai_research_ingestion_version: 1` or `2`.-Retries and dead-letter replay preserve this header and the encrypted bytes.+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 and conflicting v2 ownership are rejected; a failed v2 decode never falls back to 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.Legacy image references and paths remain available for v1 sessions.Their HMAC key must remain stable while that data is in use.@@ -220,14 +225,14 @@ The exclusion must cover every training month, not only the eval partition's monUse the encrypted reader for index entries, then fetch selected recording blocks to inspect their JSON-LD payloads.Legacy v1 indexes retain their pseudonymized identifiers and daily partitions.-### Privacy worker isolation+### Deletion worker isolation-The privacy task uses the `ai_research_privacy` Celery queue.+The deletion task uses the `ai_research_privacy` Celery queue.In prod-us, only the dedicated `ai-research-privacy-worker` deployment consumes this queue.Its service account has a dedicated IAM role and cloud-database user.The database user needs SELECT and UPDATE only on `posthog_aitrainingdeletionrequest`.The worker starts with `bin/docker-worker-ai-training-privacy` and does not use shared Django signing secrets.Its process-local signing key is not used for application requests.The worker skips general migration checks; the outbox table must exist before deployment.-All processes that enqueue privacy work, including the general-purpose Temporal worker, need the key table setting.+All processes that enqueue deletion work, including the general-purpose Temporal worker, need the key table setting.Shared Django and Temporal workers cannot delete keys from the key table.