: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): store v3 metadata and replay index as plain parquet (#105254)
Robbieefd45e98a1a2
diff --git a/docs/internal/session-replay-structured-data-index.md b/docs/internal/session-replay-structured-data-index.mdindex 5f803a7be1a1..838aac9ca51e 100644--- a/docs/internal/session-replay-structured-data-index.md+++ b/docs/internal/session-replay-structured-data-index.md@@ -1,7 +1,9 @@# Session replay structured data indexThe ML mirror extracts a sparse index for full snapshots, `$json_ld` custom events, and URL changes.-Both versions store separate Parquet index files; v2 encrypts the projected entries and also retains the original entries in encrypted block metadata.+Every version stores separate Parquet index files.+V2 encrypts the projected entries and also retains the original entries in encrypted block metadata.+V3 stores the projected entries as plain Parquet columns.Use it to find candidate labels and block locations without downloading DOM payloads.The native anonymizer extracts metadata after scrubbing and passes it beside the serialized recording bytes.The ordinary replay ingestion path does not extract this index.@@ -39,13 +41,35 @@ Each returned block contains raw team and session IDs, its storage key and byteThe entries retain their original fields, including `windowId`, `eventTimestamp`, `eventIndex`, and `rootTypes`.These original metadata entries are separate from the projected, URL-enriched entries returned by `replay_index()`.-When reading original entries through `metadata()` instead of the separate index, data preparation must validate and flatten them before using the SQL example below.+When reading original entries through `metadata()` instead of the separate index, data preparation must validate and flatten them before applying the pairing rules below.Attach the block's identifiers and storage location to each entry, and apply the URL matching rules in this guide.Map `windowId` to `window_id`, `eventTimestamp` to `event_ts_ms`, `eventIndex` to `event_index`, and `rootTypes` to `root_types`.Map the block's `replay_index_truncated` flag to `block_index_truncated`.-The encrypted reader returns metadata; it does not create these query views.+The encrypted reader returns metadata; it does not flatten the entries.Use `ReplayV2Reader.recording()` to fetch and decrypt selected recording blocks before inspecting their events.+### Plain v3 index and metadata++A session that starts at or after the v3 cutoff writes to the v3 bucket.+V3 writes `block-metadata/v3/<YYYY-MM>/part-<writer>-<time>-<sequence>.parquet` and `block-metadata-replay-index/v3/<YYYY-MM>/kind=<kind>/part-<writer>-<time>-<sequence>.parquet`, partitioned by the session's UTC start month.+Both files use plain Parquet columns with real team and session IDs, so a reader queries them without a key.+The index has the v1 columns, including the scrubbed `url`.+The metadata keeps the v1 columns, including the scrubbed `first_url` and `urls`, and has no `replay_index_entries`.+Deletion does not remove rows from these files, and the sink does not check session keys for v3 rows.+The recording blocks that the rows of a deleted session point to become unreadable when the session key is shredded and its cached copies expire.++A v3 prefix can also hold objects in the sealed format, mostly under 2026-09.+A sealed object has a `payload` column that holds an encrypted JSON envelope, and a plain object has no `payload` column.+A reader checks each object in every month, decrypts a sealed object as it decrypts v2 objects, and reads a plain object directly.+The two formats carry some metadata fields differently:++| Field | Sealed payload (JSON) | Plain object (Parquet) |+| ------------------- | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |+| Block start and end | `first_ts_ms` and `last_ts_ms`, in epoch milliseconds | `first_ts` and `last_ts`, as UTC timestamps |+| Identifier scheme | `format_version`, which is 2 | No `format_version` column: the `/v3/` path shows that the `team_id` and `session_id` columns hold raw IDs |+| Session start | `session_start_ts_ms` | No column: decode it from the UUIDv7 session ID |+| Index entries | `replay_index_entries` and `replay_index_truncated` | No column: read the separate index |+### Legacy v1 sparse indexThe legacy metadata sink writes the index to the same bucket as block metadata.@@ -79,7 +103,7 @@ For an event-time search, include the preceding seven session-start dates and fi## Full snapshot URLs-The metadata consumer enriches projected v1 and v2 index rows before writing Parquet.+The metadata consumer enriches the projected index rows of every version before writing Parquet.Apply these same matching rules if preparing original entries from decrypted v2 block metadata instead.For JSON-LD, it copies the URL from the `page` entry at the same event index, then omits that duplicate page row.For a full snapshot, it uses a URL entry at the same event index or the immediately preceding event index.@@ -99,64 +123,131 @@ Payload validation must account for this limit.## Pairing labels with snapshots-For v1, read the requested session-start partitions into DuckDB views named `labels`, `snapshots`, and `pages`.-For v2, create these views from `ReplayV2Reader.replay_index()` results for the requested monthly partitions and kinds.-Use `union_by_name=true` when reading Parquet files across schema versions.-The following query finds candidates by URL and time, including separate blocks and out-of-order arrivals.+Pair labels with snapshots in Athena.+Athena reads the plain v1 and v3 index files.+It cannot read sealed entries, which are the v2 index and the sealed objects under the v3 prefix.+Decrypt those entries with the encrypted reader, and apply the same rules to them.++An Athena table over the v3 index uses these columns and partitions:++```sql+CREATE EXTERNAL TABLE replay_index_v3 (+ team_id string,+ session_id string,+ window_id string,+ session_start_ts_ms double,+ event_ts_ms double,+ block_index_truncated boolean,+ event_index int,+ full_snapshot_ts_ms double,+ root_types array<string>,+ url string,+ block_s3_key string,+ block_byte_start double,+ block_byte_end double,+ payload binary+)+PARTITIONED BY (session_month string, kind string)+STORED AS PARQUET+LOCATION 's3://<v3-bucket>/block-metadata-replay-index/v3/'+TBLPROPERTIES (+ 'projection.enabled' = 'true',+ 'projection.session_month.type' = 'date',+ 'projection.session_month.format' = 'yyyy-MM',+ 'projection.session_month.range' = '2026-09,NOW',+ 'projection.session_month.interval' = '1',+ 'projection.session_month.interval.unit' = 'MONTHS',+ 'projection.kind.type' = 'enum',+ 'projection.kind.values' = 'json_ld,full_snapshot,page',+ 'storage.location.template' = 's3://<v3-bucket>/block-metadata-replay-index/v3/${session_month}/kind=${kind}/'+)+```++The v3 path does not write its month as `key=value`, so the table finds each partition through `storage.location.template`.+The `kind` partition supplies the `kind` value, because an Athena table cannot use one name for a column and a partition.+Only a sealed object has a `payload` value, so the query keeps the rows where `payload` is null.+A v1 table uses the same columns at `block-metadata-replay-index/v1/`, with a `session_start_date` partition in place of `session_month`.++Set the session months and the training team IDs in `index_rows` before you run the query.+For v1, filter on `session_start_date` in place of `session_month`.+The query finds candidates by URL and time, including separate blocks and out-of-order arrivals.Its one-second Meta gap and two-second label gap are example selection parameters, not SDK guarantees.Measure match coverage and audit payloads before choosing the final thresholds.```sql-WITH page_urls AS (+WITH index_rows AS (+ SELECT *+ FROM replay_index_v3+ WHERE session_month IN ('2026-10', '2026-11')+ AND payload IS NULL+ AND team_id NOT IN ('<training team ID>')+), labels AS (+ SELECT * FROM index_rows WHERE kind = 'json_ld'+), snapshots AS (+ SELECT * FROM index_rows WHERE kind = 'full_snapshot'+), pages AS (+ SELECT * FROM index_rows WHERE kind = 'page'+), page_urls AS (SELECT team_id, session_id, window_id, event_ts_ms,CASE WHEN count(url) = count(*) AND count(DISTINCT url) = 1THEN min(url) END AS urlFROM pagesGROUP BY team_id, session_id, window_id, event_ts_ms+), snapshot_rows AS (+ SELECT DISTINCT team_id, session_id, window_id, event_ts_ms, event_index, url,+ block_s3_key, block_byte_start, block_byte_end+ FROM snapshots), snapshot_urls AS (- SELECT s.* EXCLUDE (url),- coalesce(s.url, CASE WHEN s.event_ts_ms - p.event_ts_ms <= 1000- THEN p.url END) AS url- FROM (SELECT DISTINCT * FROM snapshots) s- ASOF LEFT JOIN page_urls p- ON s.team_id = p.team_id- AND s.session_id = p.session_id- AND s.window_id = p.window_id- AND s.event_ts_ms >= p.event_ts_ms+ -- Athena has no ASOF join, so this takes the latest page row at or before each snapshot.+ SELECT s.team_id, s.session_id, s.window_id, s.event_ts_ms, s.event_index,+ s.block_s3_key, s.block_byte_start, s.block_byte_end,+ coalesce(s.url, CASE WHEN s.event_ts_ms - max(p.event_ts_ms) <= 1000+ THEN max_by(p.url, p.event_ts_ms) END) AS url+ FROM snapshot_rows s+ LEFT JOIN page_urls p+ ON p.team_id = s.team_id+ AND p.session_id = s.session_id+ AND p.window_id = s.window_id+ AND p.event_ts_ms <= s.event_ts_ms+ GROUP BY s.team_id, s.session_id, s.window_id, s.event_ts_ms, s.event_index, s.url,+ s.block_s3_key, s.block_byte_start, s.block_byte_end), incomplete_sessions AS (SELECT team_id, session_id FROM labels WHERE block_index_truncatedUNIONSELECT team_id, session_id FROM snapshots WHERE block_index_truncatedUNIONSELECT team_id, session_id FROM pages WHERE block_index_truncated+), candidates AS (+ SELECT+ j.team_id, j.session_id, j.window_id, j.url, j.root_types,+ j.event_ts_ms AS label_ts_ms, s.event_ts_ms AS snapshot_ts_ms,+ j.block_s3_key AS label_block, j.block_byte_start AS label_start,+ j.block_byte_end AS label_end, j.event_index AS label_event_index,+ s.block_s3_key AS snapshot_block, s.block_byte_start AS snapshot_start,+ s.block_byte_end AS snapshot_end, s.event_index AS snapshot_event_index+ FROM labels j+ JOIN snapshot_urls s+ ON j.team_id = s.team_id+ AND j.session_id = s.session_id+ AND j.window_id = s.window_id+ AND j.url = s.url+ AND abs(j.event_ts_ms - s.event_ts_ms) <= 2000+ LEFT JOIN incomplete_sessions i+ ON i.team_id = j.team_id AND i.session_id = j.session_id+ WHERE j.url IS NOT NULL AND j.url <> ''+ AND i.team_id IS NULL)-SELECT DISTINCT- j.team_id, j.session_id, j.window_id, j.url, j.root_types,- j.event_ts_ms AS label_ts_ms, s.event_ts_ms AS snapshot_ts_ms,- j.block_s3_key AS label_block, j.block_byte_start AS label_start,- j.block_byte_end AS label_end, j.event_index AS label_event_index,- s.block_s3_key AS snapshot_block, s.block_byte_start AS snapshot_start,- s.block_byte_end AS snapshot_end, s.event_index AS snapshot_event_index-FROM labels j-JOIN snapshot_urls s- ON j.team_id = s.team_id- AND j.session_id = s.session_id- AND j.window_id = s.window_id- AND j.url = s.url- AND abs(j.event_ts_ms - s.event_ts_ms) <= 2000-WHERE j.url IS NOT NULL AND j.url <> ''- AND NOT EXISTS (- SELECT 1 FROM incomplete_sessions i- WHERE i.team_id = j.team_id AND i.session_id = j.session_id- )- AND NOT EXISTS (- SELECT 1 FROM page_urls p- WHERE p.team_id = j.team_id AND p.session_id = j.session_id- AND p.window_id = j.window_id- AND p.event_ts_ms BETWEEN least(j.event_ts_ms, s.event_ts_ms)- AND greatest(j.event_ts_ms, s.event_ts_ms)- AND p.url IS DISTINCT FROM j.url- );+-- Keep a pair only when no page row with another URL falls between the label and the snapshot.+SELECT DISTINCT c.*+FROM candidates c+LEFT JOIN page_urls p+ ON p.team_id = c.team_id+ AND p.session_id = c.session_id+ AND p.window_id = c.window_id+ AND p.event_ts_ms BETWEEN least(c.label_ts_ms, c.snapshot_ts_ms)+ AND greatest(c.label_ts_ms, c.snapshot_ts_ms)+ AND p.url IS DISTINCT FROM c.url+WHERE p.team_id IS NULL```This query returns candidates, not verified pairs.@@ -184,14 +275,14 @@ Exclude JSON-LD rows without URLs; do not infer those URLs from older SDK navigaUse the `url` on each `json_ld` row for site and page coverage.The SDK captures it in `data.href` at the same time as the label, after applying replay URL masking and hash settings.The shared recorder emits a label entry and a URL entry for that event.-The consumer combines them by event index for both versions of the separate index.+The consumer combines them by event index for every version of the separate index.The anonymizer scrubs it again before extracting index metadata.This works when navigation events and JSON-LD arrive in separate payloads and needs no session URL cache.Exclude rows without a usable URL from coverage counts and dataset selection.Older SDKs do not send this field; URL masking can also omit it.The index retains those rows, but coverage queries do not infer their URLs from `page` events.-Both index versions omit the duplicate `page` row for JSON-LD events with a URL.+Every index version omits a `page` row at the event index of a JSON-LD or full-snapshot row, and moves its URL onto that row.The original entries inside encrypted v2 block metadata retain both entries.Count distinct normalized scrubbed URLs as page families.@@ -216,7 +307,8 @@ Exclude cross-split content duplicates or keep their domain groups together befoThe v1 layout supports a bounded-date Parquet scan followed by selective block fetches.V2 readers select monthly index objects, decrypt their entries, and then fetch selected blocks.-It does not provide an S3 point lookup by domain or URL: those filters still scan the selected date partitions.+V3 readers scan the monthly index objects directly, and then fetch selected blocks.+No layout provides an S3 point lookup by domain or URL: those filters still scan the selected partitions.Cache the selected index locally for repeated sampling and split experiments.A compacted metadata table can reduce file-listing overhead later without changing SDK capture or replay storage.@@ -228,13 +320,14 @@ The metadata batcher also flushes at 32 MiB of input messages and buffered encryThis limits accumulation to that threshold plus one input batch; decoded objects and Parquet encoding require additional memory.The legacy metadata sink writes index partitions sequentially.The v2 sink writes encrypted index partitions and metadata by session month.-Both paths commit Kafka offsets only after their storage writes succeed.+The v3 sink writes plain index partitions and metadata by session month.+Every path commits Kafka offsets only after its storage writes succeed.A partial upload followed by a retry can produce duplicate rows.Deduplicate rows by team, session, block key, byte range, event index, and kind before counting them.Repeated source blocks can also have different storage keys, so dataset preparation still needs content deduplication.The existing write-error metric includes storage failures.-The following index counters cover both index versions.+The following index counters cover every index version.`ml_mirror_replay_index_rows_written_total` counts uploaded entries by kind, including retries.`ml_mirror_replay_index_skipped_total` counts invalid entries, blocks without a usable session start, and truncated blocks.These counters measure indexing, not unique sessions or pages.@@ -247,7 +340,7 @@ This change does not backfill old recordings.## JSON-LD URL rolloutDeploy the anonymizer that scrubs `data.href` before releasing the SDK change that sends it.-The metadata consumer populates URLs on JSON-LD and full-snapshot index rows for both versions.+The metadata consumer populates URLs on JSON-LD and full-snapshot index rows for every version.The separate v2 index encrypts those projected rows before storage.The existing schema and shared recorder already provide the fields needed by that consumer.Full-snapshot URL enrichment also works with older SDKs that send Meta events; JSON-LD coverage still requires the SDK URL addition.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 f55ada572a58..b30ce5358565 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@@ -48,6 +48,15 @@ const msg = (offset: number, partition = 0, value: Buffer = Buffer.from(JSON.strconst skippedMsg = (offset: number, partition = 0): Message =>msg(offset, partition, Buffer.from(JSON.stringify({ session_id: `s${offset}` })))+// Starts at 2026-09-22T12:00:00Z, after the v3 cutoff.+const V3_SESSION = '01a0c8fc-b600-7000-8000-000000000003'++const v3Msg = (offset: number, value: unknown = { ...row(V3_SESSION), team_id: '7', format_version: 2 }): Message =>+ ({+ ...msg(offset, 0, Buffer.from(JSON.stringify(value))),+ headers: [{ ai_research_ingestion_version: Buffer.from('2') }],+ }) as unknown as Message+describe('BlockMetadataBatcher', () => {let store: jest.Mocked<BlockMetadataParquetStore>let offsets: jest.Mocked<OffsetStore>@@ -56,7 +65,10 @@ describe('BlockMetadataBatcher', () => {new BlockMetadataBatcher(store, offsets, { flushIntervalMs, maxRows }, startMs)beforeEach(() => {- store = { write: jest.fn().mockResolvedValue(undefined) } as unknown as jest.Mocked<BlockMetadataParquetStore>+ store = {+ write: jest.fn().mockResolvedValue(undefined),+ writePlainV3: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<BlockMetadataParquetStore>offsets = { offsetsStore: jest.fn() }})@@ -103,12 +115,23 @@ describe('BlockMetadataBatcher', () => {])})- it('does not store offsets when the write fails (so the window replays)', async () => {- store.write.mockRejectedValueOnce(new Error('s3 down'))- const batcher = makeBatcher(60_000, 1)- await expect(batcher.handleBatch([msg(0)], 0)).rejects.toThrow('s3 down')- expect(offsets.offsetsStore).not.toHaveBeenCalled()- })+ it.each([+ { storage: 'legacy', message: msg(0), write: 'write' as const },+ { storage: 'plain v3', message: v3Msg(0), write: 'writePlainV3' as const },+ ])(+ 'does not store offsets when the $storage write fails, and the retry writes the same rows',+ async ({ message, write }) => {+ store[write].mockRejectedValueOnce(new Error('s3 down'))+ const batcher = makeBatcher(60_000, 1)+ await expect(batcher.handleBatch([message], 0)).rejects.toThrow('s3 down')+ expect(offsets.offsetsStore).not.toHaveBeenCalled()++ await batcher.flush(1)+ expect(store[write]).toHaveBeenCalledTimes(2)+ expect(store[write].mock.calls[1][0]).toHaveLength(1)+ expect(offsets.offsetsStore).toHaveBeenCalledWith([{ topic: 'ml_block_metadata', partition: 0, offset: 1 }])+ }+ )it('keeps v2 offsets pending until the encrypted eval index upload succeeds', async () => {await sodium.ready@@ -177,12 +200,21 @@ describe('BlockMetadataBatcher', () => {expect(store.write).toHaveBeenCalledTimes(1)})- it('commits offsets for a skipped-only batch without writing (so it does not replay forever)', async () => {- const batcher = makeBatcher(1_000, 1_000_000, 0)- await batcher.handleBatch([skippedMsg(7, 0)], 1_000) // all rows dropped by the parser, but offset must advance-- expect(store.write).not.toHaveBeenCalled()- expect(offsets.offsetsStore).toHaveBeenCalledTimes(1)- expect(offsets.offsetsStore.mock.calls[0][0]).toEqual([{ topic: 'ml_block_metadata', partition: 0, offset: 8 }])- })+ it.each([+ { storage: 'legacy', message: skippedMsg(7, 0) },+ { storage: 'plain v3', message: v3Msg(7, { session_id: V3_SESSION, team_id: '7', format_version: 2 }) },+ ])(+ 'commits offsets for a skipped-only $storage batch without writing (so it does not replay forever)',+ async ({ message }) => {+ const batcher = makeBatcher(1_000, 1_000_000, 0)+ await batcher.handleBatch([message], 1_000) // all rows dropped by the parser, but offset must advance++ expect(store.write).not.toHaveBeenCalled()+ expect(store.writePlainV3).not.toHaveBeenCalled()+ expect(offsets.offsetsStore).toHaveBeenCalledTimes(1)+ expect(offsets.offsetsStore.mock.calls[0][0]).toEqual([+ { topic: 'ml_block_metadata', partition: 0, offset: 8 },+ ])+ }+ )})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 251f550741fe..4a82fbd964be 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@@ -12,6 +12,7 @@ import { MlEncryptedEnvelope, encryptEnvelopeJson } from './keys/crypto'import { MlDecodedMessage, MlKafkaTransport, ingestionVersion } from './keys/transport'import { MlParquetSinkMetrics } from './metrics'import { EncryptedReplayIndex, encryptReplayIndex } from './replay-index'+import { usesV3Dataset } from './session-identifier-format'/** The subset of the Kafka consumer the batcher needs: storing offsets it has durably written. */export interface OffsetStore {@@ -28,6 +29,7 @@ export class BlockMetadataBatcher {private encrypted: MlEncryptedEnvelope[] = []private encryptedIndex: EncryptedReplayIndex[] = []private buffer: MlBlockMetadataRow[] = []+ private plainV3: MlBlockMetadataRow[] = []private bufferedBytes = 0private pendingOffsets = new Map<string, TopicPartitionOffset>()private lastFlushMs: number@@ -47,15 +49,16 @@ export class BlockMetadataBatcher {for (const message of messages) {this.bufferedBytes += message.value?.length ?? 0}+ const { plainV3Rows, otherMessages } = splitPlainV3Rows(messages)const decoded: MlDecodedMessage[] = this.keyManager- ? await this.keyManager.read(messages, { sessionIdentity: rowSessionIdentity })- : messages.map((message) => {+ ? await this.keyManager.read(otherMessages, { sessionIdentity: rowSessionIdentity })+ : otherMessages.map((message) => {if (ingestionVersion(message) === 2) {throw new Error('ML v2 metadata requires key manager configuration')}return { message, original: message, key: undefined, invalid: undefined }})- MlParquetSinkMetrics.incRowsRejected('key_missing', messages.length - decoded.length)+ MlParquetSinkMetrics.incRowsRejected('key_missing', otherMessages.length - decoded.length)let encryptedRows = 0for (const { message, key, invalid, legacy } of decoded) {if (legacy) {@@ -84,7 +87,7 @@ export class BlockMetadataBatcher {}}}- MlParquetSinkMetrics.incRowsParsed(encryptedRows)+ MlParquetSinkMetrics.incRowsParsed(encryptedRows + plainV3Rows.length)for (const row of parseBlockMetadataMessages(decoded.filter(({ key, invalid, legacy }) => !key && !invalid && !legacy).map(({ message }) => message))) {@@ -92,6 +95,8 @@ export class BlockMetadataBatcher {this.buffer.push(row)}}+ // No await separates this push from the offsets below, so a batch whose key read throws buffers no rows.+ this.plainV3.push(...plainV3Rows)// Track the next offset to read per partition (highest seen + 1), accumulated across batches.for (const offset of findOffsetsToCommit(messages)) {this.pendingOffsets.set(`${offset.topic}:${offset.partition}`, offset)@@ -103,7 +108,7 @@ export class BlockMetadataBatcher {private shouldFlush(nowMs: number): boolean {if (- this.buffer.length + this.encrypted.length >= this.options.maxRows ||+ this.buffer.length + this.encrypted.length + this.plainV3.length >= this.options.maxRows ||this.bufferedBytes >= (this.options.maxBytes ?? 32 * 1024 * 1024)) {return true@@ -120,7 +125,11 @@ export class BlockMetadataBatcher {*/public async flush(nowMs: number): Promise<void> {this.lastFlushMs = nowMs- const wroteObject = this.buffer.length > 0 || this.encrypted.length > 0+ const wroteObject = this.buffer.length > 0 || this.encrypted.length > 0 || this.plainV3.length > 0+ if (this.plainV3.length > 0) {+ await this.store.writePlainV3(this.plainV3)+ this.plainV3 = []+ }if (this.encryptedIndex.length > 0) {await this.store.writeEncryptedReplayIndex(this.encryptedIndex)this.encryptedIndex = []@@ -145,6 +154,39 @@ export class BlockMetadataBatcher {}}+/** A v3 session needs no session key, because the sink stores its metadata and replay index as plain Parquet. */+function splitPlainV3Rows(messages: Message[]): { plainV3Rows: MlBlockMetadataRow[]; otherMessages: Message[] } {+ const plainV3Rows: MlBlockMetadataRow[] = []+ const otherMessages: Message[] = []+ for (const message of messages) {+ const row = parsedV3Row(message)+ if (row === null) {+ otherMessages.push(message)+ } else if (isWellFormedRow(row) && row.format_version === 2) {+ plainV3Rows.push(selectBlockMetadataFields(row))+ } else {+ MlParquetSinkMetrics.incRowsRejected('invalid')+ }+ }+ return { plainV3Rows, otherMessages }+}++function parsedV3Row(message: Message): object | null {+ let row: unknown+ try {+ if (ingestionVersion(message) !== 2) {+ return null+ }+ row = parseJSON(message.value?.toString() ?? '')+ } catch {+ return null+ }+ if (!row || typeof row !== 'object' || !('session_id' in row)) {+ return null+ }+ return typeof row.session_id === 'string' && usesV3Dataset(row.session_id) ? row : null+}+function rowSessionIdentity(message: Message): { teamId: number; sessionId: string } | null {let row: unknowntry {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-columns.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-columns.tsindex 6e3214f0d617..ba78e3efcfb5 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-columns.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-columns.ts@@ -56,25 +56,41 @@ export function isWellFormedRow(row: unknown): row is MlBlockMetadataRow {return false}for (const col of COLUMNS) {- if (col.optional) {+ const value = r[col.row]+ if (col.optional && (value === null || value === undefined)) {continue}- const value = r[col.row]- if (col.repeated) {- if (!Array.isArray(value)) {- return false- }- } else if (col.type === 'UTF8') {- if (typeof value !== 'string') {- return false- }- } else if (typeof value !== 'number' || !Number.isFinite(value)) {+ const encodable = col.repeated+ ? Array.isArray(value) && value.every((item) => isEncodableValue(col.type, item))+ : isEncodableValue(col.type, value)+ if (!encodable) {return false}}return true}+const INT32_MIN = -(2 ** 31)+const INT32_MAX = 2 ** 31 - 1+// ECMAScript time values stop at 8.64e15 ms either side of the epoch, so a larger timestamp becomes an Invalid Date.+const MAX_TIME_VALUE_MS = 8.64e15++function isEncodableValue(type: ParquetType, value: unknown): boolean {+ if (type === 'UTF8') {+ return typeof value === 'string'+ }+ if (typeof value !== 'number' || !Number.isFinite(value)) {+ return false+ }+ if (type === 'INT32') {+ return Number.isInteger(value) && value >= INT32_MIN && value <= INT32_MAX+ }+ if (type === 'INT64') {+ return Number.isSafeInteger(value)+ }+ return Math.abs(value) <= MAX_TIME_VALUE_MS+}+export function selectBlockMetadataFields(row: MlBlockMetadataRow): MlBlockMetadataRow {return Object.fromEntries([diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-message.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-message.test.tsindex 964aa4c28dca..3659bb186085 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-message.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-message.test.ts@@ -55,6 +55,15 @@ describe('parseBlockMetadataMessages', () => {msg({ session_id: 'a', event_count: 3, team_id: '42', format_version: 2 }), // missing required numeric fields + urlsmsg(fullRow({ event_count: 'oops' as unknown as number })), // wrong typemsg(fullRow({ urls: 'not-an-array' as unknown as string[] })),+ msg(fullRow({ block_byte_start: 'oops' as unknown as number })), // optional and repeated values the writer cannot encode+ msg(fullRow({ first_url: 5 as unknown as string })),+ msg(fullRow({ urls: [1] as unknown as string[] })),+ msg(fullRow({ event_count: 2 ** 31 })), // numbers outside the range of their Parquet type+ msg(fullRow({ retention_period_days: 2 ** 31 })),+ msg(fullRow({ block_length: 2 ** 63 })),+ msg(fullRow({ first_ts_ms: 9e15 })),+ msg(fullRow({ click_count: 0.5 })), // fractions that an integer column would truncate+ msg(fullRow({ block_length: 1.5 })),msg(fullRow({ format_version: 2, team_id: 'a'.repeat(32) })),msg(fullRow({ format_version: 2, team_id: '9007199254740992' })),msg({ ...fullRow(), format_version: 3 }),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 a05ed06b1ca3..3590d9c85cba 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@@ -1,15 +1,11 @@import { PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'import { ParquetReader } from '@dsnp/parquetjs'-import sodium from 'libsodium-wrappers'import { register } from 'prom-client'-import { parseJSON } from '~/common/utils/json-parse'-import { BlockMetadataParquetStore } from './block-metadata-parquet-store'import { MlBlockMetadataRow } from './block-metadata-row'-import { MlDataKey } from './keys/crypto'-import { TrainingEncryptionVector, decryptEnvelope } from './keys/envelope-testing'-import { encryptReplayIndex, replayIndexPartitions } from './replay-index'+import { TrainingEncryptionVector } from './keys/envelope-testing'+import { replayIndexPartitions } from './replay-index'const row = (sessionId: string, teamId: string): MlBlockMetadataRow => ({session_id: sessionId,@@ -38,6 +34,11 @@ const row = (sessionId: string, teamId: string): MlBlockMetadataRow => ({retention_period_days: 30,})+const sessionStartingAt = (date: string): string => {+ const hex = Date.parse(date).toString(16).padStart(12, '0')+ return `${hex.slice(0, 8)}-${hex.slice(8)}-7000-8000-000000000007`+}+async function readRows(body: PutObjectCommandInput['Body']): Promise<Record<string, any>[]> {const reader = await ParquetReader.openBuffer(body as Buffer)const cursor = reader.getCursor()@@ -65,62 +66,56 @@ describe('BlockMetadataParquetStore', () => {} as unknown as S3Client})- it('writes v3 sessions to the v3 bucket and keeps earlier sessions in v2 when both are configured', async () => {- const envelopes = ['2026-09-21T16:59:59.999Z', '2026-09-21T17:00:00Z'].map((date) => {- const hex = Date.parse(date).toString(16).padStart(12, '0')- return {- ...TrainingEncryptionVector.envelope,- context: {- ...TrainingEncryptionVector.envelope.context,- sessionId: `${hex.slice(0, 8)}-${hex.slice(8)}-7000-8000-000000000007`,- },- }- })+ it('keeps sealed storage for v2 sessions and refuses v3 sessions', async () => {+ const [v2Envelope, v3Envelope] = ['2026-09-21T16:59:59.999Z', '2026-09-21T17:00:00Z'].map((date) => ({+ ...TrainingEncryptionVector.envelope,+ context: { ...TrainingEncryptionVector.envelope.context, sessionId: sessionStartingAt(date) },+ }))const store = new BlockMetadataParquetStore(s3,{ v2: 'ml-bucket', v3: 'ml-bucket-v3' },'block-metadata','pod')- await store.writeEncrypted(envelopes)- await store.writeEncryptedReplayIndex(envelopes.map((envelope) => ({ kind: 'page', rowCount: 1, envelope })))+ await store.writeEncrypted([v2Envelope])+ await store.writeEncryptedReplayIndex([{ kind: 'page', rowCount: 1, envelope: v2Envelope }])expect(puts.map((put) => [put.Bucket, put.Key?.split('/').slice(0, 3).join('/')])).toEqual([['ml-bucket', 'block-metadata/v2/2026-09'],- ['ml-bucket-v3', 'block-metadata/v3/2026-09'],['ml-bucket', 'block-metadata-replay-index/v2/2026-09'],- ['ml-bucket-v3', 'block-metadata-replay-index/v3/2026-09'],])+ await expect(store.writeEncrypted([v3Envelope])).rejects.toThrow('plain storage')+ await expect(+ store.writeEncryptedReplayIndex([{ kind: 'page', rowCount: 1, envelope: v3Envelope }])+ ).rejects.toThrow('plain storage')+ expect(puts).toHaveLength(2)})- it('splits encrypted metadata by session month rather than upload time', async () => {- const envelopes = ['2026-09-30T23:59:59.999Z', '2026-10-01T00:00:00Z'].map((date) => {- const hex = Date.parse(date).toString(16).padStart(12, '0')- return {- ...TrainingEncryptionVector.envelope,- context: {- ...TrainingEncryptionVector.envelope.context,- sessionId: `${hex.slice(0, 8)}-${hex.slice(8)}-7000-8000-000000000007`,- },- }- })+ it('writes v3 metadata as plain rows split by session month rather than upload time', async () => {+ const rows = ['2026-09-30T23:59:59.999Z', '2026-10-01T00:00:00Z'].map((date) =>+ row(sessionStartingAt(date), '7')+ )await new BlockMetadataParquetStore(s3,{ v2: 'ml-bucket', v3: 'ml-bucket-v3' },'block-metadata','pod'- ).writeEncrypted(envelopes)- expect(puts.map((put) => put.Key?.split('/').slice(0, 3).join('/'))).toEqual([- 'block-metadata/v3/2026-09',- 'block-metadata/v3/2026-10',+ ).writePlainV3(rows)+ expect(puts.map((put) => [put.Bucket, put.Key?.split('/').slice(0, 3).join('/')])).toEqual([+ ['ml-bucket-v3', 'block-metadata/v3/2026-09'],+ ['ml-bucket-v3', 'block-metadata/v3/2026-10'],])for (const [index, put] of puts.entries()) {- const records = await readRows(put.Body)- expect(records.map((record) => record.session_id)).toEqual([envelopes[index].context.sessionId])+ expect(await readRows(put.Body)).toEqual([+ expect.objectContaining({+ team_id: '7',+ session_id: rows[index].session_id,+ urls: ['https://x/[redacted]'],+ }),+ ])}})- it('stores encrypted eval indexes by session month with raw team IDs across late blocks', async () => {- await sodium.ready+ it('stores v3 eval indexes by session month with raw team IDs and scrubbed URLs across late blocks', async () => {const starts = ['2026-09-30T23:59:59.999Z', '2026-10-01T00:00:00Z']const eventTimestamp = Date.parse('2026-10-01T00:00:01Z')const store = new BlockMetadataParquetStore(@@ -130,36 +125,31 @@ describe('BlockMetadataParquetStore', () => {'pod')for (const [index, start] of starts.entries()) {- const hex = Date.parse(start).toString(16).padStart(12, '0')- const sessionId = `${hex.slice(0, 8)}-${hex.slice(8)}-7000-8000-000000000007`- const key: MlDataKey = {- identity: { teamId: 7, organizationId: 'test-org', sessionId },- plaintext: Buffer.alloc(32, 7),- wrapped: Buffer.from('wrapped'),- }- const metadata: MlBlockMetadataRow = {- ...row(sessionId, '7'),- format_version: 2,- first_ts_ms: eventTimestamp,- last_ts_ms: eventTimestamp,- replay_index_entries: [- { kind: 'full_snapshot', windowId: 'w1', eventTimestamp, eventIndex: 0 },- { kind: 'json_ld', windowId: 'w1', eventTimestamp, eventIndex: 1, rootTypes: ['Product'] },- { kind: 'page', windowId: 'w1', eventTimestamp, eventIndex: 1, url: 'https://example.com/product' },- ],- }- await store.writeEncryptedReplayIndex(encryptReplayIndex(metadata, key))+ const sessionId = sessionStartingAt(start)+ await store.writePlainV3([+ {+ ...row(sessionId, '7'),+ format_version: 2,+ first_ts_ms: eventTimestamp,+ last_ts_ms: eventTimestamp,+ replay_index_entries: [+ { kind: 'full_snapshot', windowId: 'w1', eventTimestamp, eventIndex: 0 },+ { kind: 'json_ld', windowId: 'w1', eventTimestamp, eventIndex: 1, rootTypes: ['Product'] },+ {+ kind: 'page',+ windowId: 'w1',+ eventTimestamp,+ eventIndex: 1,+ url: 'https://example.com/product',+ },+ ],+ },+ ])const month = start.slice(0, 7)const objects = puts.filter((put) => put.Key!.startsWith(`block-metadata-replay-index/v3/${month}/`))expect(objects).toHaveLength(2)const labels = await readRows(objects.find((put) => put.Key!.includes('/kind=json_ld/'))!.Body)- expect(labels).toHaveLength(1)- expect(labels[0]).toMatchObject({ team_id: '7', session_id: sessionId })- expect(labels[0].url).toBeUndefined()- expect(labels[0].root_types).toBeUndefined()- const envelope = parseJSON(labels[0].payload.toString())- const decoded = parseJSON(decryptEnvelope(key, envelope, 'replay-index', 'json_ld').toString())- expect(decoded).toEqual([+ expect(labels).toEqual([expect.objectContaining({team_id: '7',session_id: sessionId,@@ -170,7 +160,6 @@ describe('BlockMetadataParquetStore', () => {url: 'https://example.com/product',}),])- expect(() => decryptEnvelope(key, envelope, 'replay-index', 'full_snapshot')).toThrow()}})@@ -263,14 +252,28 @@ describe('BlockMetadataParquetStore', () => {expect(entries.find((entry) => entry.kind === 'full_snapshot')?.url).toBeNull()})- it('rejects plaintext v2 metadata before writing any objects', async () => {+ it.each([+ {+ storage: 'legacy',+ write: (store: BlockMetadataParquetStore) => store.write([{ ...row('session', '42'), format_version: 2 }]),+ error: 'sealed v2 or plain v3 storage',+ },+ {+ storage: 'plain v3',+ write: (store: BlockMetadataParquetStore) =>+ store.writePlainV3([+ { ...row(sessionStartingAt('2026-09-21T16:59:59.999Z'), '42'), format_version: 2 },+ ]),+ error: 'only v3 sessions',+ },+ ])('rejects v2 metadata in $storage storage before writing any objects', async ({ write, error }) => {const store = new BlockMetadataParquetStore(s3,{ v2: 'ml-bucket', v3: 'ml-bucket-v3' },'block-metadata','pod-1')- await expect(store.write([{ ...row('session', '42'), format_version: 2 }])).rejects.toThrow('encrypted storage')+ await expect(write(store)).rejects.toThrow(error)expect(puts).toHaveLength(0)})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.tsindex 0926541abde4..1875819285a3 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.ts@@ -10,7 +10,12 @@ import { MlBlockMetadataRow } from './block-metadata-row'import { MlEncryptedEnvelope } from './keys/crypto'import { MlParquetSinkMetrics } from './metrics'import { rowsToParquetBuffer } from './parquet-writer'-import { EncryptedReplayIndex, replayIndexPartitions, replayIndexToParquetBuffer } from './replay-index'+import {+ EncryptedReplayIndex,+ replayIndexPartitions,+ replayIndexToParquetBuffer,+ v3ReplayIndexByKind,+} from './replay-index'import { sessionStartMonth, usesV3Dataset } from './session-identifier-format'const cmp = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0)@@ -45,7 +50,7 @@ export class BlockMetadataParquetStore {return}if (rows.some((row) => row.format_version === 2)) {- throw new Error('ML v2 metadata must use encrypted storage')+ throw new Error('ML raw-identifier metadata must use sealed v2 or plain v3 storage')}await this.writeDataset(rows, this.prefix, `${this.prefix}-replay-index/v1`)}@@ -54,52 +59,85 @@ export class BlockMetadataParquetStore {if (envelopes.length === 0) {return}- const partitions = new Map<string, { bucket: string; envelopes: MlEncryptedEnvelope[] }>()+ const partitions = new Map<string, MlEncryptedEnvelope[]>()for (const envelope of envelopes) {- const { dataset, month } = this.datasetOf(envelope.context.sessionId ?? '')- const partition = `${this.prefix}/${dataset}/${month}`- const group = partitions.get(partition) ?? { bucket: this.buckets[dataset], envelopes: [] }- group.envelopes.push(envelope)+ const partition = `${this.prefix}/v2/${sealedSessionMonth(envelope)}`+ const group = partitions.get(partition) ?? []+ group.push(envelope)partitions.set(partition, group)}for (const [partition, group] of partitions) {- const bytes = await this.writeEncryptedPartition(group.bucket, partition, group.envelopes)- MlParquetSinkMetrics.observeWrite(group.envelopes.length, bytes)+ const bytes = await this.writeEncryptedPartition(partition, group)+ MlParquetSinkMetrics.observeWrite(group.length, bytes)}}public async writeEncryptedReplayIndex(indexes: EncryptedReplayIndex[]): Promise<void> {- const partitions = new Map<string, { bucket: string; indexes: EncryptedReplayIndex[] }>()+ const partitions = new Map<string, EncryptedReplayIndex[]>()for (const index of indexes) {- const { kind, envelope } = index- const { dataset, month } = this.datasetOf(envelope.context.sessionId ?? '')- const partition = `${this.prefix}-replay-index/${dataset}/${month}/kind=${kind}`- const group = partitions.get(partition) ?? { bucket: this.buckets[dataset], indexes: [] }- group.indexes.push(index)+ const partition = `${this.prefix}-replay-index/v2/${sealedSessionMonth(index.envelope)}/kind=${index.kind}`+ const group = partitions.get(partition) ?? []+ group.push(index)partitions.set(partition, group)}for (const [partition, group] of partitions) {await this.writeEncryptedPartition(- group.bucket,partition,- group.indexes.map((index) => index.envelope)+ group.map((index) => index.envelope))MlParquetSinkMetrics.incReplayIndexRows(- group.indexes[0].kind,- group.indexes.reduce((count, index) => count + index.rowCount, 0)+ group[0].kind,+ group.reduce((count, index) => count + index.rowCount, 0))}}- private datasetOf(sessionId: string): { dataset: 'v2' | 'v3'; month: string } {- return { dataset: usesV3Dataset(sessionId) ? 'v3' : 'v2', month: sessionStartMonth(sessionId) }+ /** Writes v3 metadata and its replay index as plain Parquet columns, partitioned by the session's UTC start month. */+ public async writePlainV3(rows: MlBlockMetadataRow[]): Promise<void> {+ const months = new Map<string, MlBlockMetadataRow[]>()+ for (const row of rows) {+ if (!usesV3Dataset(row.session_id)) {+ throw new Error('ML plain storage holds only v3 sessions')+ }+ const month = sessionStartMonth(row.session_id)+ const group = months.get(month) ?? []+ group.push(row)+ months.set(month, group)+ }+ try {+ // Every body is encoded before the first upload, so a row that the writer rejects leaves no object behind.+ const uploads: { prefix: string; body: Buffer; rows: number; indexKind?: string }[] = []+ for (const [month, group] of months) {+ group.sort((a, b) => cmp(a.team_id, b.team_id) || cmp(a.session_id, b.session_id))+ for (const [kind, records] of v3ReplayIndexByKind(group)) {+ uploads.push({+ prefix: `${this.prefix}-replay-index/v3/${month}/kind=${kind}`,+ body: await replayIndexToParquetBuffer(records),+ rows: records.length,+ indexKind: kind,+ })+ }+ uploads.push({+ prefix: `${this.prefix}/v3/${month}`,+ body: await rowsToParquetBuffer(group),+ rows: group.length,+ })+ }+ for (const upload of uploads) {+ await this.putParquet(this.buckets.v3, upload.prefix, upload.body)+ if (upload.indexKind) {+ MlParquetSinkMetrics.incReplayIndexRows(upload.indexKind, upload.rows)+ } else {+ MlParquetSinkMetrics.observeWrite(upload.rows, upload.body.length)+ }+ }+ } catch (error) {+ MlParquetSinkMetrics.incWriteError()+ throw error+ }}- private async writeEncryptedPartition(- bucket: string,- prefix: string,- envelopes: MlEncryptedEnvelope[]- ): Promise<number> {+ private async writeEncryptedPartition(prefix: string, envelopes: MlEncryptedEnvelope[]): Promise<number> {let body: Buffertry {const schema = new ParquetSchema({@@ -117,15 +155,7 @@ export class BlockMetadataParquetStore {payload: Buffer.from(JSON.stringify(envelope)),})))- await this.s3Client.send(- new PutObjectCommand({- Bucket: bucket,- Key: `${prefix}/part-${this.nodeId}-${Date.now()}-${++this.seq}.parquet`,- Body: body,- ContentType: 'application/vnd.apache.parquet',- }),- { abortSignal: AbortSignal.timeout(30_000) }- )+ await this.putParquet(this.buckets.v2, prefix, body)} catch (error) {MlParquetSinkMetrics.incWriteError()throw error@@ -133,6 +163,18 @@ export class BlockMetadataParquetStore {return body.length}+ private async putParquet(bucket: string, prefix: string, body: Buffer): Promise<void> {+ await this.s3Client.send(+ new PutObjectCommand({+ Bucket: bucket,+ Key: `${prefix}/part-${this.nodeId}-${Date.now()}-${++this.seq}.parquet`,+ Body: body,+ ContentType: 'application/vnd.apache.parquet',+ }),+ { abortSignal: AbortSignal.timeout(30_000) }+ )+ }+private async writeDataset(rows: MlBlockMetadataRow[], prefix: string, indexPrefix: string): Promise<void> {// Sorting clusters a recording's blocks together for better compression and reads.rows.sort((a, b) => cmp(a.team_id, b.team_id) || cmp(a.session_id, b.session_id))@@ -187,6 +229,14 @@ export class BlockMetadataParquetStore {}}+function sealedSessionMonth(envelope: MlEncryptedEnvelope): string {+ const sessionId = envelope.context.sessionId ?? ''+ if (usesV3Dataset(sessionId)) {+ throw new Error('ML v3 metadata uses plain storage')+ }+ return sessionStartMonth(sessionId)+}+/*** Earliest and latest event time in the batch. The earliest sets the object's `dt=` partition (rows can* span a window, so the min wins); the latest lets the caller measure how far the batch's dates spread.diff --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 a94756c276da..0be2926e2f1c 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@@ -23,13 +23,20 @@ import { MlBlockMetadataSink } from './ml-block-metadata-sink'import { PSEUDONYM_SESSION, PSEUDONYM_TEAM, pseudonymize } from './pseudonymize'const SESSION_A = '01a0a4f0-3200-7000-8000-000000000001'+// Starts at 2026-09-22T12:00:00Z, after the v3 cutoff.+const SESSION_V3 = '01a0c8fc-b600-7000-8000-000000000003'-const block = (sessionId: string, teamId: number, distinctId: string): SessionBlockMetadata => ({+const block = (+ sessionId: string,+ teamId: number,+ distinctId: string,+ startMs = 1789473600000+): SessionBlockMetadata => ({...createNoopBlockMetadata(sessionId, teamId),distinctId,blockUrl: `s3://ml-bucket/key-${sessionId}?range=bytes=10-42`,- startDateTime: DateTime.fromMillis(1789473600000),- endDateTime: DateTime.fromMillis(1789473605000),+ startDateTime: DateTime.fromMillis(startMs),+ endDateTime: DateTime.fromMillis(startMs + 5000),eventCount: 5,messageCount: 2,clickCount: 1,@@ -39,30 +46,47 @@ const block = (sessionId: string, teamId: number, distinctId: string): SessionBl{kind: 'page',windowId: 'w1',- eventTimestamp: 1789473600001.5,+ eventTimestamp: startMs + 1.5,eventIndex: 0,url: 'https://example.com/[redacted]',},- { kind: 'full_snapshot', windowId: 'w1', eventTimestamp: 1789473600001.5, eventIndex: 1 },+ { kind: 'full_snapshot', windowId: 'w1', eventTimestamp: startMs + 1.5, eventIndex: 1 },{kind: 'json_ld',windowId: 'w1',- eventTimestamp: 1789473600001.5,+ eventTimestamp: startMs + 1.5,eventIndex: 2,- fullSnapshotTimestamp: 1789473600001.5,+ fullSnapshotTimestamp: startMs + 1.5,rootTypes: ['Product'],},{kind: 'page',windowId: 'w1',- eventTimestamp: 1789473600001.5,+ eventTimestamp: startMs + 1.5,eventIndex: 2,url: 'https://example.com/[redacted]',},- { kind: 'json_ld', windowId: 'w1', eventTimestamp: 1789473600001.5, eventIndex: 3, rootTypes: ['Article'] },+ { kind: 'json_ld', windowId: 'w1', eventTimestamp: startMs + 1.5, eventIndex: 3, rootTypes: ['Article'] },],})+const sessionKey = (teamId: number, sessionId: string): MlDataKey => ({+ identity: { teamId, sessionId, organizationId: 'test-org' },+ plaintext: Buffer.alloc(32, 7),+ wrapped: Buffer.from('wrapped'),+})++const keyReader = (keys: MlDataKey[]): MlKeyReader =>+ ({+ read: jest.fn(() =>+ Promise.resolve(+ new Map(+ keys.map((key) => [tableKeyString(sessionKeyId(key.identity.teamId, key.identity.sessionId!)), key])+ )+ )+ ),+ }) as unknown as MlKeyReader+async function readRows(body: PutObjectCommandInput['Body']): Promise<Record<string, any>[]> {const reader = await ParquetReader.openBuffer(body as Buffer)const cursor = reader.getCursor()@@ -78,16 +102,12 @@ async function readRows(body: PutObjectCommandInput['Body']): Promise<Record<str// End-to-end across both new deployments' metadata path: the mirror's producer serializes block metadata to the// Kafka topic, and the sink's parser → batcher → Parquet store turns those exact bytes into an object in the ML bucket.describe('ML metadata producer → sink round-trip', () => {- it('encrypts v2 metadata and replay indexes while preserving legacy records', async () => {+ it('writes v3 as plain Parquet without a session key, encrypts v2, and preserves legacy records', async () => {await sodium.ready- const key: MlDataKey = {- identity: { teamId: 1, sessionId: SESSION_A, organizationId: 'test-org' },- plaintext: Buffer.alloc(32, 7),- wrapped: Buffer.from('wrapped'),- }- const reader = {- read: jest.fn(() => Promise.resolve(new Map([[tableKeyString(sessionKeyId(1, SESSION_A)), key]]))),- } as unknown as MlKeyReader+ const key = sessionKey(1, SESSION_A)+ // The sink holds no key for the v3 session, so its row lands only if the sink never looks one up.+ const producerReader = keyReader([key, sessionKey(3, SESSION_V3)])+ const sinkReader = keyReader([key])// --- Mirror (producer) side: block metadata → Kafka message bytes ---const produced: { key?: unknown; value: Buffer | null; headers?: Record<string, string> }[] = []const outputs = {@@ -97,11 +117,12 @@ describe('ML metadata producer → sink round-trip', () => {}),} as unknown as IngestionOutputs<MlBlockMetadataOutput>- await new MlBlockMetadataSink(outputs, 'test-secret', reader).storeSessionBlocks([+ await new MlBlockMetadataSink(outputs, 'test-secret', producerReader).storeSessionBlocks([block(SESSION_A, 1, 'person-1'),block('01a0a4f0-31ff-7000-8000-000000000001', 2, 'person-2'),+ block(SESSION_V3, 3, 'person-3', Date.parse('2026-09-22T12:00:00Z')),])- expect(produced).toHaveLength(2)+ expect(produced).toHaveLength(3)// --- Sink (consumer) side: those exact bytes → parser → batcher → Parquet in S3 ---const puts: PutObjectCommandInput[] = []@@ -123,7 +144,7 @@ describe('ML metadata producer → sink round-trip', () => {offsetStore,{ flushIntervalMs: 60_000, maxRows: 1_000 },0,- new MlKafkaTransport(reader)+ new MlKafkaTransport(sinkReader))const messages = produced.map(@@ -151,9 +172,9 @@ describe('ML metadata producer → sink round-trip', () => {expect(evalRows).toHaveLength(1)expect(evalRows[0]).toMatchObject({ team_id: '1', session_id: SESSION_A })expect(evalRows[0].url).toBeUndefined()- const labels = parseJSON(- decryptEnvelope(key, parseJSON(evalRows[0].payload.toString()), 'replay-index', 'json_ld').toString()- )+ const labelEnvelope = parseJSON(evalRows[0].payload.toString())+ expect(() => decryptEnvelope(key, labelEnvelope, 'replay-index', 'full_snapshot')).toThrow()+ const labels = parseJSON(decryptEnvelope(key, labelEnvelope, 'replay-index', 'json_ld').toString())expect(labels).toEqual([expect.objectContaining({team_id: '1',@@ -170,6 +191,27 @@ describe('ML metadata producer → sink round-trip', () => {url: null,}),])+ const v3Metadata = puts.find((put) => put.Key!.startsWith('block-metadata/v3/2026-09/'))!+ expect(v3Metadata.Bucket).toBe('ml-bucket-v3')+ const v3Rows = await readRows(v3Metadata.Body)+ expect(v3Rows).toEqual([+ expect.objectContaining({ team_id: '3', session_id: SESSION_V3, urls: ['https://example.com/[redacted]'] }),+ ])+ expect(v3Rows[0]).not.toHaveProperty('payload')+ expect(v3Rows[0]).not.toHaveProperty('distinct_id')+ const v3Labels = await readRows(+ puts.find((put) => put.Key!.startsWith('block-metadata-replay-index/v3/2026-09/kind=json_ld/'))!.Body+ )+ expect(v3Labels).toEqual([+ expect.objectContaining({+ team_id: '3',+ session_id: SESSION_V3,+ root_types: ['Product'],+ url: 'https://example.com/[redacted]',+ }),+ expect.objectContaining({ team_id: '3', session_id: SESSION_V3, root_types: ['Article'] }),+ ])+const legacyRows = await readRows(puts.find((put) => put.Key!.startsWith('block-metadata/dt='))!.Body)expect(legacyRows).toHaveLength(1)expect(legacyRows[0]).not.toHaveProperty('distinct_id')@@ -194,6 +236,6 @@ describe('ML metadata producer → sink round-trip', () => {expect(a.urls).toEqual(['https://example.com/[redacted]'])// Offsets advanced only after the write landed.- expect(offsetStore.offsetsStore).toHaveBeenCalledWith([{ topic: 'ml_block_metadata', partition: 0, offset: 2 }])+ expect(offsetStore.offsetsStore).toHaveBeenCalledWith([{ topic: 'ml_block_metadata', partition: 0, offset: 3 }])})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.tsindex afdeebd163d6..c06492a1d5e0 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.ts@@ -112,6 +112,25 @@ export function replayIndexToParquetBuffer(records: Record<string, unknown>[]):return parquetRecordsToBuffer(schema, records)}+export function v3ReplayIndexByKind(+ rows: MlBlockMetadataRow[]+): Map<ReplayIndexEntry['kind'], Record<string, unknown>[]> {+ const byKind = new Map<ReplayIndexEntry['kind'], Record<string, unknown>[]>()+ const partitions = replayIndexPartitions(+ rows.map((row) => ({+ ...row,+ session_start_ts_ms: sessionStartTimestampFromUuidV7(row.session_id) ?? undefined,+ }))+ )+ for (const partitionRecords of partitions.values()) {+ const kind = partitionRecords[0].kind as ReplayIndexEntry['kind']+ const records = byKind.get(kind) ?? []+ records.push(...partitionRecords)+ byKind.set(kind, records)+ }+ return byKind+}+export interface EncryptedReplayIndex {kind: ReplayIndexEntry['kind']rowCount: numberdiff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.mdindex 3757cc12bc44..0238ac2120d9 100644--- a/products/ai_training/docs/replay-data.md+++ b/products/ai_training/docs/replay-data.md@@ -14,7 +14,7 @@ The session UUIDv7 timestamp selects the version:- Before the cutoff: v1 uses HMAC team and session IDs.- At or after the cutoff: v2 uses raw team and session IDs and encrypted payloads.-- At or after **Monday, 2026-09-21 at 17:00 UTC** (18:00 in Europe/London): v3 keeps the v2 identifiers and keys, and stores its objects in the v3 buckets under `rrweb_3/` and the `/v3/` dataset paths.+- At or after **Monday, 2026-09-21 at 17:00 UTC** (18:00 in Europe/London): v3 keeps the v2 identifiers and keys, and stores its objects in the v3 buckets under `rrweb_3/` and the `/v3/` dataset paths. Its metadata catalog and evaluation index are plain Parquet.- The ML mirror drops a session if its ID is not UUIDv7 or its start year is beyond 9999.Event timestamps, arrival times, retries, and flushes do not change the version.@@ -58,7 +58,8 @@ An object body is a binary frame: the ASCII magic `AISR03`, the length of the adThe 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.+In the v2 dataset, 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 v3 dataset does not seal its metadata or its replay index. Both are plain Parquet columns, described in [Data layout and readers](#data-layout-and-readers).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.@@ -147,8 +148,8 @@ A failed request backs off without blocking unrelated requests.Completion follows key removal and the five-minute reader lifetime.Scrubbed images remain available after session or person deletion, but become unreadable after team or month deletion.-This mechanism covers encrypted v2 objects.-It does not erase legacy plaintext objects, previously downloaded data, derived training artifacts, or a trained model.+This mechanism covers encrypted v2 and v3 objects.+It does not erase legacy plaintext objects, plain v3 metadata and index rows, previously downloaded data, derived training artifacts, or a trained model.Legacy dataset retirement needs a separate storage operation before claiming deletion across the entire bucket.## Monthly key deletion@@ -185,14 +186,24 @@ A session that crosses a month boundary stays in its start month, including late| URL images | `scrubbed-images/v2/<month>/<team>/url/<hash>` | Team and session month |A v3 session uses the same layout in the v3 buckets: blocks under `rrweb_3/<month>/`, and the metadata catalog, the evaluation index and every image path with `/v3/` in place of `/v2/`.+The v3 metadata catalog and the v3 evaluation index use no key.+Some v3 objects under those two paths are sealed, mostly under 2026-09. A sealed object has a `payload` column that holds an encrypted JSON envelope, as in v2.+A reader checks each object for a `payload` column in every month. See [the structured data index](../../../docs/internal/session-replay-structured-data-index.md#plain-v3-index-and-metadata).A reader finds the bucket of a block in its `block_url`, and resolves an `image:v3:` or `imageurl:v3:` reference in the v3 images bucket under the `/v3/` paths.-Metadata catalogs expose raw `team_id`, `session_id`, `format_version`, and an encrypted `payload`.+A v2 metadata catalog exposes raw `team_id`, `session_id`, `format_version`, and an encrypted `payload`.URLs, block locations, and replay indexes are inside that payload.Neither the catalog nor its encrypted payload includes a distinct-ID field.V2 does not write a separate plaintext replay index.-Athena can select catalog rows but cannot decrypt replay fields.+A v3 metadata catalog stores each block as plain Parquet columns: raw `team_id` and `session_id`, the block location, timestamps, counts, and the scrubbed `first_url` and `urls`.+It has no distinct-ID field and no replay index entries.+The v3 evaluation index stores its entries as plain Parquet columns with raw team and session IDs and the scrubbed URL.+Deletion does not remove v3 metadata or index rows. The sink reads no session key for a v3 row, so it also writes rows for a session that was deleted after the mirror produced them.+Those rows hold no personal data, and the recording blocks they point to become unreadable when the session key is shredded and the cached copies of that key expire.++Athena can select v2 catalog rows but cannot decrypt replay fields. It can query every column of a plain v3 object.+To leave out sealed v3 objects, include a `payload` column in the table and filter on `payload IS NULL`.Training readers must bulk-read live keys and deletion markers before decrypting.If a download exceeds the key read lifetime, readers must check live eligibility again before decryption.Cross-account readers use the full DynamoDB table ARN and the prod-us KMS key ARN.@@ -210,7 +221,9 @@ Resolve image references before training because they contain team IDs.A reference names its dataset version: `image:v2:<team>:<month>:<hash>` and `imageurl:v2:<team>:<month>:<hash>` for a v2 session, `image:v3:...` and `imageurl:v3:...` for a v3 session. The version is part of the reference, so the fetch frontier and every dedup cache treat a v3 reference as new even when a v2 session already stored the same image, and the v3 dataset gets its own copy.Images do not deduplicate across teams or session months.-Kafka records between the ML lanes travel in cleartext; only objects in S3 are sealed, and stored scrubbed images use team image keys.+Kafka records between the ML lanes travel in cleartext.+In S3, recording blocks and images are sealed, and stored scrubbed images use team image keys.+V2 metadata and the v2 evaluation index are sealed. V3 metadata and the v3 evaluation index are plain Parquet, apart from the sealed v3 objects that [Data layout and readers](#data-layout-and-readers) describes.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.@@ -229,7 +242,8 @@ Retries and dead-letter replay preserve this header and the record bytes.Consumers drop records that still use the sealed envelope shape from before cleartext records, and count them in `recording_blob_ingestion_v2_ml_legacy_envelopes_dropped_total`.Headerless queued messages mean v1.Unknown versions are rejected, and so is an image reference whose version does not match the header.-The metadata sink resolves each row's session key from the row's own team and session identifiers before it seals the row for Parquet; a row whose key is deleted is dropped.+For a v2 session, the metadata sink resolves each row's session key from the row's own team and session identifiers before it seals the row for Parquet; a row whose key is deleted is dropped.+A v3 row needs no key, because the sink writes it as plain Parquet.Legacy image references and paths remain available for v1 sessions.Their HMAC key must remain stable while that data is in use.@@ -243,7 +257,7 @@ 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. A session that started at or after the v3 cutoff writes there, and v2 keeps its own bucket. The mirror, the sink and the image scrubber stop at startup when it is empty.+- `S3_BUCKET` names the v3 bucket of a lane. A session that started at or after the v3 cutoff writes there, and v2 keeps its own bucket. The mirror and the metadata sink use the recording bucket, which holds AISR03 frames for recording blocks and Parquet for the v3 metadata catalog and evaluation index. The image scrubber uses the images bucket, which holds AISR03 frames. The mirror, the sink and the image scrubber stop at startup when it is empty.- `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.@@ -275,9 +289,14 @@ Each Parquet row exposes real `team_id` and `session_id` values and encrypts theSession, person, team, and month deletion therefore remove access to the index along with its recording.The JSON-LD payload remains in the referenced recording block.+The v3 metadata consumer writes the same three kinds as plain Parquet columns with real team and session IDs.+Athena can pair v3 labels with snapshots by URL and time. See [the pairing query](../../../docs/internal/session-replay-structured-data-index.md#pairing-labels-with-snapshots).+Deletion does not remove v3 index rows. It makes the recording blocks that they point to unreadable, as [Data layout and readers](#data-layout-and-readers) describes.+Use the real team ID to exclude all teams present in the model's training data before selecting eval examples.The exclusion must cover every training month, not only the eval partition's month.-Use the encrypted reader for index entries, then fetch selected recording blocks to inspect their JSON-LD payloads.+For v2, use the encrypted reader for index entries. For v3, read the Parquet columns directly.+Then fetch selected recording blocks to inspect their JSON-LD payloads.Legacy v1 indexes retain their pseudonymized identifiers and daily partitions.### Deletion worker isolation