: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): pack ML blocks with brotli and frame envelopes as bytes (#103042)
Robbief0ddc2f9a5f8
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 6bc022acfd40..cfb200599390 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@@ -4,7 +4,7 @@ import sodium from 'libsodium-wrappers'import { parseJSON } from '~/common/utils/json-parse'import { MlDataKey } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto'-import { decryptEnvelope } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/envelope-testing'+import { decryptEnvelopeFrame } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/envelope-testing'import { ImageShardStore } from './image-shard-store'@@ -84,12 +84,10 @@ describe('ImageShardStore', () => {.map(([command]) => command).find((command) => command.input.Key?.includes('/lookup/')) as PutObjectCommandconst location = parseJSON(- decryptEnvelope(- key,- parseJSON((lookup.input.Body as Buffer).toString()),- 'image-location',- lookup.input.Key- ).toString()+ decryptEnvelopeFrame(key, lookup.input.Body as Buffer, 'image-location', {+ ref: lookup.input.Key,+ codec: 'none',+ }).toString())expect(location).toEqual({ shard: send.mock.calls[0][0].input.Key, offset: 0, length: 3 })expect(lookup.input.Key).toBe(`images/v2/2026-09/7/lookup/${inlineImage.hash}.encrypted`)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.tsindex 0343e8ee8b7f..f4f8b187c2ac 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.ts@@ -212,7 +212,9 @@ export class ImageShardStore {new PutObjectCommand({Bucket: this.bucket,Key: shardKey,- Body: encryptionKey ? encryptEnvelope(encryptionKey, 'image-shard', shardBody, shardKey) : shardBody,+ Body: encryptionKey+ ? encryptEnvelope(encryptionKey, 'image-shard', shardBody, { ref: shardKey, codec: 'none' })+ : shardBody,ContentType: 'application/octet-stream',}))@@ -222,7 +224,7 @@ export class ImageShardStore {Bucket: this.bucket,Key: `${prefix}/index/${stamp}.${encryptionKey ? 'encrypted' : 'parquet'}`,Body: encryptionKey- ? encryptEnvelope(encryptionKey, 'image-index', indexBody, shardKey)+ ? encryptEnvelope(encryptionKey, 'image-index', indexBody, { ref: shardKey, codec: 'none' }): indexBody,ContentType: encryptionKey ? 'application/octet-stream' : 'application/vnd.apache.parquet',})@@ -248,7 +250,7 @@ export class ImageShardStore {Buffer.from(JSON.stringify({ shard: shardKey, offset: row.offset, length: row.length })),- lookupKey+ { ref: lookupKey, codec: 'none' }),ContentType: 'application/octet-stream',}),@@ -292,7 +294,7 @@ export class ImageShardStore {Bucket: this.bucket,Key: key,Body: encryptionKey- ? encryptEnvelope(encryptionKey, 'image-url', image.bytes, key)+ ? encryptEnvelope(encryptionKey, 'image-url', image.bytes, { ref: key, codec: 'none' }): image.bytes,ContentType: 'application/octet-stream',Metadata: {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-compression.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-compression.tsnew file mode 100644index 000000000000..a52e4faa58a0--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-compression.ts@@ -0,0 +1,9 @@+import { BlockCompression } from '~/ingestion/pipelines/sessionreplay/sessions/block-compression'++/**+ * Measured 2026-09-19 on 1500 production blocks: quality 9 stores 0.53 of snappy for 25 times its CPU, and beats zstd+ * level 19 on both counts. Quality 5 stores 6% more for 46% of the CPU. Quality 11 stores 6% less, but costs 47 times+ * quality 9 and needs more packing throughput than the threadpool gives. This lane reads a block rarely and keeps it+ * for months, so it takes the bytes.+ */+export const ML_BLOCK_COMPRESSION = { codec: 'brotli', level: 9 } as const satisfies BlockCompressiondiff --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 8b03ce26be2d..251f550741fe 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@@ -8,7 +8,7 @@ import { isWellFormedRow, selectBlockMetadataFields } from './block-metadata-colimport { 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 { MlEncryptedEnvelope, encryptEnvelopeJson } from './keys/crypto'import { MlDecodedMessage, MlKafkaTransport, ingestionVersion } from './keys/transport'import { MlParquetSinkMetrics } from './metrics'import { EncryptedReplayIndex, encryptReplayIndex } from './replay-index'@@ -74,11 +74,7 @@ export class BlockMetadataBatcher {}if (isWellFormedRow(row)) {const selected = selectBlockMetadataFields(row)- this.encrypted.push(- parseJSON(- encryptEnvelope(key, 'metadata', Buffer.from(JSON.stringify(selected))).toString()- ) as MlEncryptedEnvelope- )+ this.encrypted.push(encryptEnvelopeJson(key, 'metadata', Buffer.from(JSON.stringify(selected))))encryptedRows++const index = encryptReplayIndex(selected, key)this.encryptedIndex.push(...index)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.tsindex 16f6c7ffed19..03f1f0db3028 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts@@ -13,6 +13,10 @@ export type MlMirrorConfig = {AI_RESEARCH_REPLAY_ROW_CACHE_LIFETIME_MS: numberAI_RESEARCH_REPLAY_IMAGE_FETCH_V2_DYNAMODB_TABLE: stringAI_RESEARCH_REPLAY_S3_PREFIX: string+ /** Bucket of the v3 dataset, which holds only AISR03 frames. Empty until the cutover by session start timestamp selects it. */+ AI_RESEARCH_REPLAY_S3_BUCKET: string+ /** Block prefix inside the v3 bucket. Each dataset version has its own, so a bucket policy grants only the versions it holds. */+ AI_RESEARCH_REPLAY_S3_V3_PREFIX: string/** S3 key prefix under the bucket for the block-metadata Parquet dataset (used by the sink). */SESSION_RECORDING_ML_METADATA_PREFIX: string/** Optional S3 key of the `{ text, url }` allow-list document; empty → in-binary defaults. */@@ -221,6 +225,8 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {AI_RESEARCH_REPLAY_ROW_CACHE_LIFETIME_MS: 300_000,AI_RESEARCH_REPLAY_IMAGE_FETCH_V2_DYNAMODB_TABLE: '',AI_RESEARCH_REPLAY_S3_PREFIX: 'rrweb_2',+ AI_RESEARCH_REPLAY_S3_BUCKET: '',+ AI_RESEARCH_REPLAY_S3_V3_PREFIX: 'rrweb_3',SESSION_RECORDING_ML_METADATA_PREFIX: 'block-metadata',SESSION_RECORDING_ML_ALLOW_LIST_S3_KEY: '',AI_RESEARCH_REPLAY_PSEUDONYM_SECRET: '',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 6a72f19b0d07..36bab5d7654c 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@@ -1,3 +1,4 @@+import { ML_BLOCK_COMPRESSION } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-compression'import { MlMirrorMetrics } from '~/ingestion/pipelines/sessionreplay/ml-mirror/metrics'import { usesRawSessionIdentifiers } from '~/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format'import {@@ -109,7 +110,8 @@ export class MlKeyBatchController implements KeyStore, RecordingEncryptor {data: encryptEnvelope({ identity: mlKey.mlIdentity, plaintext: key.plaintextKey, wrapped: key.encryptedKey },'rrweb',- data+ data,+ { codec: ML_BLOCK_COMPRESSION.codec }),sessionState: 'ciphertext',}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 c2c36a2c23d9..749a320e1898 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,10 +1,20 @@import { createDecipheriv } from 'node:crypto'+import { compressSync } from 'snappy'-import { parseJSON } from '~/common/utils/json-parse'+import { ML_BLOCK_COMPRESSION } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-compression'+import { compressBlock } from '~/ingestion/pipelines/sessionreplay/sessions/block-compression'-import { MlDataKey, TAG_BYTES, canonicalJson, encryptEnvelope, openSessionKey, sealSessionKey } from './crypto'+import {+ MlDataKey,+ TAG_BYTES,+ canonicalJson,+ encryptEnvelope,+ encryptEnvelopeJson,+ openSessionKey,+ sealSessionKey,+} from './crypto'import vector from './encryption-vector.json'-import { TrainingEncryptionVector, decryptEnvelope } from './envelope-testing'+import { TrainingEncryptionVector, decryptEnvelope, decryptEnvelopeFrame } from './envelope-testing'import { wrappingContext } from './schema'import { validateImageOwner } from './transport'@@ -19,29 +29,67 @@ const key: MlDataKey = {}describe('ML payload encryption', () => {- it.each(['rrweb', 'metadata', 'image-source', 'image-frontier', 'image-shard', 'image-index', 'score'])(- 'binds %s payloads to their purpose and owner',+ it.each(['metadata', 'replay-index'])('binds %s parquet values to their purpose and owner', (kind) => {+ const data = Buffer.from('private test payload')+ const envelope = encryptEnvelopeJson(key, kind, data)+ expect(JSON.stringify(envelope)).not.toContain(data.toString())+ expect(decryptEnvelope(key, envelope, kind)).toEqual(data)+ expect(() => decryptEnvelope(key, envelope, 'wrong-purpose')).toThrow()+ expect(() => decryptEnvelope({ ...key, identity: { ...key.identity, teamId: 8 } }, envelope, kind)).toThrow()+ expect(() => decryptEnvelope(key, { ...envelope, context: { ...envelope.context, teamId: 8 } }, kind)).toThrow()+ const corrupted = Buffer.from(envelope.ciphertext, 'base64')+ corrupted[0] ^= 1+ expect(() => decryptEnvelope(key, { ...envelope, ciphertext: corrupted.toString('base64') }, kind)).toThrow()+ })++ it.each(['rrweb', 'image-source', 'image-frontier', 'image-shard', 'image-index', 'score'])(+ 'binds %s frames to their purpose and owner',(kind) => {const data = Buffer.from('private test payload')- const encoded = encryptEnvelope(key, kind, data)- expect(encoded.toString()).not.toContain(data.toString())- const envelope = parseJSON(encoded.toString())- expect(decryptEnvelope(key, envelope, kind)).toEqual(data)- expect(() => decryptEnvelope(key, envelope, 'wrong-purpose')).toThrow()+ const frame = encryptEnvelope(key, kind, data, { codec: 'none' })+ expect(frame.subarray(0, 6).toString()).toBe('AISR03')+ expect(frame.toString('latin1')).not.toContain(data.toString())+ expect(decryptEnvelopeFrame(key, frame, kind, { codec: 'none' })).toEqual(data)+ expect(() => decryptEnvelopeFrame(key, frame, 'wrong-purpose', { codec: 'none' })).toThrow()expect(() =>- decryptEnvelope({ ...key, identity: { ...key.identity, teamId: 8 } }, envelope, kind)- ).toThrow()- expect(() =>- decryptEnvelope(key, { ...envelope, context: { ...envelope.context, teamId: 8 } }, kind)- ).toThrow()- const corrupted = Buffer.from(envelope.ciphertext, 'base64')- corrupted[0] ^= 1- expect(() =>- decryptEnvelope(key, { ...envelope, ciphertext: corrupted.toString('base64') }, kind)+ decryptEnvelopeFrame({ ...key, identity: { ...key.identity, teamId: 8 } }, frame, kind, {+ codec: 'none',+ })).toThrow()+ // The codec is inside the signed context, so a reader cannot be talked out of expanding the body.+ expect(() => decryptEnvelopeFrame(key, frame, kind, { codec: 'brotli' })).toThrow()+ const corrupted = Buffer.from(frame)+ corrupted[corrupted.length - TAG_BYTES - 1] ^= 1+ expect(() => decryptEnvelopeFrame(key, corrupted, kind, { codec: 'none' })).toThrow()})+ it('stores far fewer bytes than the snappy and base64 form it replaces', async () => {+ const events = Array.from({ length: 600 }, (_, i) => [+ 'w1',+ {+ type: 3,+ timestamp: 1789740000000 + i * 40,+ data: { source: 1, positions: [{ x: i % 700, id: i % 400 }] },+ },+ ])+ const raw = Buffer.from(events.map((event) => JSON.stringify(event)).join('\n'))+ const framed = encryptEnvelope(key, 'rrweb', await compressBlock(raw, ML_BLOCK_COMPRESSION), {+ codec: ML_BLOCK_COMPRESSION.codec,+ })+ const previous = Buffer.from(JSON.stringify(encryptEnvelopeJson(key, 'rrweb', compressSync(raw) as Buffer)))+ expect(framed.length).toBeLessThan(previous.length / 2)+ })++ it('returns the original bytes through the compressor the recorder uses', async () => {+ const data = Buffer.from(JSON.stringify(Array.from({ length: 400 }, (_, i) => ({ row: i, label: 'repeated' }))))+ const frame = encryptEnvelope(key, 'rrweb', await compressBlock(data, ML_BLOCK_COMPRESSION), {+ codec: ML_BLOCK_COMPRESSION.codec,+ })+ expect(frame.length).toBeLessThan(data.length / 4)+ expect(decryptEnvelopeFrame(key, frame, 'rrweb', { codec: ML_BLOCK_COMPRESSION.codec })).toEqual(data)+ })+it('binds image months to the encrypted session start month', () => {const timestamp = Date.parse('2026-09-30T23:59:59.999Z').toString(16).padStart(12, '0')const sessionKey = {@@ -70,15 +118,73 @@ describe('ML payload encryption', () => {).toEqual(Buffer.from(TrainingEncryptionVector.data, 'base64'))})- it('fits the largest fetched image in the ML Kafka transport budget', () => {+ it.each([+ ['truncated', (frame: Buffer) => frame.subarray(0, 100)],+ ['a header shorter than the magic', (frame: Buffer) => frame.subarray(0, 4)],+ [+ 'a length that overruns the frame',+ (frame: Buffer) => {+ const overrun = Buffer.from(frame)+ overrun.writeUInt16BE(0xffff, 6)+ return overrun+ },+ ],+ ])('refuses a frame that is %s', (_name, damage) => {+ const frame = Buffer.from(TrainingEncryptionVector.frame.frame, 'base64')+ expect(() =>+ decryptEnvelopeFrame(+ {+ ...key,+ identity: TrainingEncryptionVector.context,+ plaintext: Buffer.from(TrainingEncryptionVector.key, 'base64'),+ },+ damage(frame),+ TrainingEncryptionVector.frame.kind,+ { codec: TrainingEncryptionVector.frame.codec }+ )+ ).toThrow(/Not an ML envelope frame|Invalid authenticated ML envelope/)+ })++ it('opens the shared framed vector, whose pinned parts reassemble into the frame', () => {+ const vector = TrainingEncryptionVector.frame+ const aad = Buffer.from(vector.aad)+ const header = Buffer.allocUnsafe(2)+ header.writeUInt16BE(aad.length)+ expect(vector.aad).toBe(+ canonicalJson({+ v: 3,+ context: { ...TrainingEncryptionVector.context, kind: vector.kind, codec: vector.codec },+ })+ )+ expect(+ Buffer.concat(+ [Buffer.from('AISR03'), header, aad].concat(+ [vector.nonce, vector.ciphertext, vector.tag].map((part) => Buffer.from(part, 'base64'))+ )+ ).toString('base64')+ ).toBe(vector.frame)+ expect(+ decryptEnvelopeFrame(+ {+ ...key,+ identity: TrainingEncryptionVector.context,+ plaintext: Buffer.from(TrainingEncryptionVector.key, 'base64'),+ },+ Buffer.from(vector.frame, 'base64'),+ vector.kind,+ { codec: vector.codec }+ )+ ).toEqual(Buffer.from(vector.data, 'base64'))+ })++ it('frames the largest fetched image without inflating it', () => {+ const image = Buffer.alloc(20 * 1024 * 1024)expect(- encryptEnvelope(- key,- 'image-source',- Buffer.alloc(20 * 1024 * 1024),- 'imageurl:v2:7:2026-09:aaaaaaaaaaaaaaaaaaaaaa'- ).length- ).toBeLessThan(40 * 1024 * 1024 + 64 * 1024)+ encryptEnvelope(key, 'image-source', image, {+ ref: 'imageurl:v2:7:2026-09:aaaaaaaaaaaaaaaaaaaaaa',+ codec: 'none',+ }).length+ ).toBeLessThan(image.length + 1024)})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto.tsindex 0dc9673d93f9..ec2aeda61231 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/crypto.ts@@ -21,7 +21,7 @@ export interface MlEncryptedEnvelope {ciphertext: string}-const NONCE_BYTES = 12+export const NONCE_BYTES = 12export const TAG_BYTES = 16/** Both readers rebuild this byte for byte, so key order is sorted and there is no whitespace. */@@ -181,17 +181,43 @@ export class MlKeyEncryption {}}-export function encryptEnvelope(key: MlDataKey, kind: string, data: Buffer, ref?: string): Buffer {+/** Names how the reader must expand the plaintext. It sits inside the authenticated context so it cannot be downgraded. */+export type MlEnvelopeCodec = 'none' | 'brotli'++const ENVELOPE_MAGIC = Buffer.from('AISR03')+const AAD_LENGTH_BYTES = 2++/**+ * Frames the ciphertext as raw bytes rather than base64 in JSON, which stores a quarter fewer bytes for the same payload.+ * The frame carries the additional authenticated data verbatim, so a reader authenticates against the bytes we signed+ * instead of rebuilding canonical JSON of its own.+ */+export function encryptEnvelope(+ key: MlDataKey,+ kind: string,+ body: Buffer,+ options: { ref?: string; codec: MlEnvelopeCodec }+): Buffer {+ const context = { ...key.identity, kind, codec: options.codec, ...(options.ref ? { ref: options.ref } : {}) }+ const aad = Buffer.from(canonicalJson({ v: 3, context }))+ if (aad.length > 0xffff) {+ throw new Error('ML envelope context is too long to frame')+ }+ const nonce = randomBytes(NONCE_BYTES)+ const cipher = createCipheriv('aes-256-gcm', key.plaintext, nonce, { authTagLength: TAG_BYTES })+ cipher.setAAD(aad)+ const ciphertext = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])+ const header = Buffer.allocUnsafe(AAD_LENGTH_BYTES)+ header.writeUInt16BE(aad.length)+ return Buffer.concat([ENVELOPE_MAGIC, header, aad, nonce, ciphertext])+}++/** Base64 in JSON, for the parquet columns that hold a value rather than an object body. */+export function encryptEnvelopeJson(key: MlDataKey, kind: string, data: Buffer, ref?: string): MlEncryptedEnvelope {const context = { ...key.identity, kind, ...(ref ? { ref } : {}) }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: 3,- context,- nonce: nonce.toString('base64'),- ciphertext: ciphertext.toString('base64'),- }- return Buffer.from(JSON.stringify(envelope))+ return { v: 3, context, nonce: nonce.toString('base64'), ciphertext: ciphertext.toString('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 167a37c6d2fd..061cae00d938 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@@ -26,5 +26,16 @@"sessionKey": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ=","nonce": "eeEJEciFIDqBWFNk","sealedKey": "vxp6SKFXDX5P4p/OXPmke/ahZKBw1+rUcA5OsFanqN665rxNb8kUZPLXQoafeWnv"+ },+ "frame": {+ "kind": "rrweb",+ "codec": "brotli",+ "data": "c3ludGhldGljIGZyYW1lZCBpbnRlcm9wZXJhYmlsaXR5IHBheWxvYWQ=",+ "body": "HygAAES3eb27X9WggVTQnvUglgykkNw6NL6P9hILOhuTcTpNcijjhedGAw==",+ "aad": "{\"context\":{\"codec\":\"brotli\",\"kind\":\"rrweb\",\"organizationId\":\"00000000-0000-4000-8000-000000000007\",\"sessionId\":\"01994569-4380-7000-8000-000000000007\",\"teamId\":7},\"v\":3}",+ "nonce": "BQUFBQUFBQUFBQUF",+ "ciphertext": "/dmHKJUqBo5bKIjQBDlZKqJmng9XTp69EU4XsO4pmM1D8Gg3wEdelERWWQ==",+ "tag": "pBSmiL+q29L2YGDlD1NubQ==",+ "frame": "QUlTUjAzAKl7ImNvbnRleHQiOnsiY29kZWMiOiJicm90bGkiLCJraW5kIjoicnJ3ZWIiLCJvcmdhbml6YXRpb25JZCI6IjAwMDAwMDAwLTAwMDAtNDAwMC04MDAwLTAwMDAwMDAwMDAwNyIsInNlc3Npb25JZCI6IjAxOTk0NTY5LTQzODAtNzAwMC04MDAwLTAwMDAwMDAwMDAwNyIsInRlYW1JZCI6N30sInYiOjN9BQUFBQUFBQUFBQUF/dmHKJUqBo5bKIjQBDlZKqJmng9XTp69EU4XsO4pmM1D8Gg3wEdelERWWaQUpoi/qtvS9mBg5Q9Tbm0="}}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.tsindex 277c6751c931..833cadce5357 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/envelope-testing.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/envelope-testing.ts@@ -1,7 +1,10 @@import { createDecipheriv } from 'node:crypto'import { isDeepStrictEqual } from 'node:util'+import { brotliDecompressSync } from 'node:zlib'-import { MlDataKey, MlEncryptedEnvelope, TAG_BYTES, canonicalJson } from './crypto'+import { parseJSON } from '~/common/utils/json-parse'++import { MlDataKey, MlEncryptedEnvelope, MlEnvelopeCodec, NONCE_BYTES, 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. */@@ -22,4 +25,40 @@ export function decryptEnvelope(key: MlDataKey, envelope: MlEncryptedEnvelope, kreturn Buffer.concat([decipher.update(sealed.subarray(0, sealed.length - TAG_BYTES)), decipher.final()])}-export const TrainingEncryptionVector = { ...vector, envelope: vector.envelope as MlEncryptedEnvelope }+const MAGIC = 'AISR03'+const HEADER_BYTES = MAGIC.length + 2++/** Takes the authenticated bytes from the frame rather than rebuilding them, so a canonical-JSON mismatch cannot fail a test for the wrong reason. */+export function decryptEnvelopeFrame(+ key: MlDataKey,+ frame: Buffer,+ kind: string,+ options: { ref?: string; codec: MlEnvelopeCodec }+): Buffer {+ if (frame.length < HEADER_BYTES || frame.subarray(0, MAGIC.length).toString() !== MAGIC) {+ throw new Error('Not an ML envelope frame')+ }+ // The magic and the length sit outside the authenticated data, so a frame must be bounded before it is sliced.+ const aadLength = frame.readUInt16BE(MAGIC.length)+ if (frame.length < HEADER_BYTES + aadLength + NONCE_BYTES + TAG_BYTES) {+ throw new Error('Invalid authenticated ML envelope')+ }+ const aad = frame.subarray(HEADER_BYTES, HEADER_BYTES + aadLength)+ const nonce = frame.subarray(HEADER_BYTES + aadLength, HEADER_BYTES + aadLength + NONCE_BYTES)+ const sealed = frame.subarray(HEADER_BYTES + aadLength + NONCE_BYTES)+ const context = { ...key.identity, kind, codec: options.codec, ...(options.ref ? { ref: options.ref } : {}) }+ if (!isDeepStrictEqual(parseJSON(aad.toString()), { v: 3, context })) {+ throw new Error('ML envelope context mismatch')+ }+ const decipher = createDecipheriv('aes-256-gcm', key.plaintext, nonce, { authTagLength: TAG_BYTES })+ decipher.setAAD(aad)+ decipher.setAuthTag(sealed.subarray(sealed.length - TAG_BYTES))+ const body = Buffer.concat([decipher.update(sealed.subarray(0, sealed.length - TAG_BYTES)), decipher.final()])+ return options.codec === 'brotli' ? brotliDecompressSync(body) : body+}++export const TrainingEncryptionVector = {+ ...vector,+ envelope: vector.envelope as MlEncryptedEnvelope,+ frame: { ...vector.frame, codec: vector.frame.codec as MlEnvelopeCodec },+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.tsindex 6b4a061b5c86..afdeebd163d6 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.ts@@ -1,6 +1,5 @@import { ParquetSchema } from '@dsnp/parquetjs'-import { parseJSON } from '~/common/utils/json-parse'import {ReplayIndexEntry,ReplayIndexEntrySchema,@@ -8,7 +7,7 @@ import {import { parquetRecordsToBuffer } from '~/ingestion/pipelines/sessionreplay/shared/parquet'import { MlBlockMetadataRow } from './block-metadata-row'-import { MlDataKey, MlEncryptedEnvelope, encryptEnvelope } from './keys/crypto'+import { MlDataKey, MlEncryptedEnvelope, encryptEnvelopeJson } from './keys/crypto'import { MlParquetSinkMetrics } from './metrics'import { sessionStartTimestampFromUuidV7 } from './session-identifier-format'@@ -131,9 +130,7 @@ export function encryptReplayIndex(row: MlBlockMetadataRow, key: MlDataKey): Encreturn {kind,rowCount: records.length,- envelope: parseJSON(- encryptEnvelope(key, 'replay-index', Buffer.from(JSON.stringify(records)), kind).toString()- ) as MlEncryptedEnvelope,+ envelope: encryptEnvelopeJson(key, 'replay-index', Buffer.from(JSON.stringify(records)), kind),}})}diff --git a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.tsindex 097a30dcd98b..31e6bfd98384 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts@@ -15,6 +15,7 @@ import {} from '~/ingestion/pipelines/sessionreplay/consumer'import type { CrawlHistoryStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history'import { DynamoDBCrawlHistory } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history'+import { ML_BLOCK_COMPRESSION } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-compression'import { resolveMlMirrorRedisConnection } from '~/ingestion/pipelines/sessionreplay/ml-mirror/config'import { MlKeyManager } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime'import { MlBlockMetadataSink } from '~/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink'@@ -126,6 +127,7 @@ export class IngestionSessionReplayMlMirrorServer extends MlMirrorConsumerServerfeatureStore: new SessionFeatureStore(outputs, false),keyStore: keyManager,encryptor: keyManager,+ compression: ML_BLOCK_COMPRESSION,runner: new MlMirrorStagedBatchRunner({keyManager,diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.mdindex 8b4938388181..4296dc67146c 100644--- a/products/ai_training/docs/replay-data.md+++ b/products/ai_training/docs/replay-data.md@@ -46,11 +46,20 @@ A team has one image key per session start month.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 replay lane that serves playback encrypts a block with XSalsa20-Poly1305, which is a different format: nothing this lane writes uses it.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).+Its additional authenticated data is the JSON of `{"v": 3, "context": ...}` with sorted keys and no whitespace.+An envelope takes one of two shapes, and where it is stored decides which.+An object body is a binary frame: the ASCII magic `AISR03`, the length of the additional authenticated data as a 16-bit big-endian integer, those bytes themselves, the 12-byte nonce, then the sealed bytes followed by the 16-byte tag.+The frame carries those bytes verbatim, so a reader passes them to AES-GCM as they are rather than rebuilding the canonical JSON and risking a re-serialization mismatch.+A reader must still decode that context and check it equals the object it asked for, because one team month key seals every image object in a flush and the context is the only thing that tells them apart: a reader that skips the check authenticates a shard where it expected an index, or one image's location where it expected another's.+A reader must also bound the frame before it slices, because the magic and the length sit outside the authenticated data.+A parquet column holds a value and not an object body, so `metadata` and `replay-index` stay JSON with `v`, `context`, `nonce` (12 bytes, base64) and `ciphertext` (the sealed bytes followed by the 16-byte tag, base64). A reader there knows the shape from the column and inspects no magic bytes.+The `frame` block in `nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/encryption-vector.json` pins one frame with a brotli body, so a reader in another language can check its own bytes. It carries the whole frame and also each part on its own: the additional authenticated data as text, the nonce, the sealed bytes, the tag, the brotli body, and the decompressed data.+The framed context names a `codec`, which tells a reader how to expand the plaintext.+An `rrweb` block uses `brotli` at quality 9. Each lane declares its own codec, so this lane never produces snappy. It reads a block rarely and keeps it for months, so it stores fewer bytes instead.+An image object uses `none`, because an image already arrives compressed.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.@@ -228,6 +237,8 @@ New key manager and v2 storage settings use the `AI_RESEARCH_REPLAY_*` prefix:- `ROW_CACHE_MAX` and `ROW_CACHE_LIFETIME_MS` bound the stored key row cache. The lifetime applies to a session key row and is capped; a team image key row is held for up to 48 hours. A value that is not a positive integer stops the consumer at startup and names the setting.- `IMAGE_FETCH_V2_DYNAMODB_TABLE` selects the fresh v2 frontier.- `S3_PREFIX` selects v2 replay storage and defaults to `rrweb_2`.+- `S3_BUCKET` names the v3 bucket, which holds only AISR03 frames. It is empty until the cutover by session start timestamp selects it, and v2 keeps its own bucket.+- `S3_V3_PREFIX` selects the block prefix inside the v3 bucket and defaults to `rrweb_3`. Each dataset version has its own prefix, so a bucket policy grants only the versions it holds.The v2 producer requires `AI_RESEARCH_REPLAY_KEY_TABLE` and `AI_RESEARCH_REPLAY_KMS_KEY_ARN` at startup.Missing values stop startup before it consumes Kafka messages.