: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(replay): index structured data and full snapshots (#96809)
Robbie7dc184e65e9c
diff --git a/docs/internal/session-replay-structured-data-index.md b/docs/internal/session-replay-structured-data-index.mdnew file mode 100644index 000000000000..d1335cc2742a--- /dev/null+++ b/docs/internal/session-replay-structured-data-index.md@@ -0,0 +1,102 @@+# Session replay structured data index++The ML mirror writes a sparse Parquet index for full snapshots, `$json_ld` custom events, and URL changes.+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.++## Storage and lookup++The existing metadata sink writes the index to the same bucket as block metadata.+Its prefix is `<block-metadata-prefix>-replay-index/v1/`.+For the default prefix, files have this form:++```text+block-metadata-replay-index/v1/kind=json_ld/session_start_date=2026-09-01/part-<writer>-<time>-<sequence>.parquet+block-metadata-replay-index/v1/kind=full_snapshot/session_start_date=2026-09-01/part-<writer>-<time>-<sequence>.parquet+block-metadata-replay-index/v1/kind=page/session_start_date=2026-09-01/part-<writer>-<time>-<sequence>.parquet+```++Each row identifies a pseudonymous team and session, the recording window, an event timestamp, and a zero-based event index within the decompressed block.+The block key and inclusive byte range locate the independently compressed block.+Timestamps use doubles so fractional milliseconds survive an exact join.+Window IDs match the IDs in the scrubbed recording lines.+The index contains no DOM nodes or JSON-LD payload text.++A `json_ld` row contains an optional `full_snapshot_ts_ms` reference and up to 64 distinct root types.+Types come from root objects, root arrays, and `@graph` members.+Nested entity properties, such as a product's offers, do not contribute types.+The types help select candidates; read the payload before deciding which label to use.++The index partitions each row by its session's UTC start date, decoded from UUIDv7 before pseudonymization.+Entries for one session stay under one date, including separate blocks and late arrivals across midnight.+This partition helps session lookups and cross-block joins. An arrival-date partition would make ingestion-time scans simpler, but would spread one session across dates.+The index omits non-v7 session IDs and starts outside the interval from seven days before the block's last event through that event.+Normal replay storage and block metadata continue for those sessions.+For an event-time search, include the preceding seven session-start dates and filter `event_ts_ms`.++## Pairing labels with snapshots++Read the requested session-start partitions into DuckDB views named `labels`, `snapshots`, and `pages`.+Use `union_by_name=true` when reading Parquet files across schema versions.+A label with a reference can join a snapshot in another payload or block:++```sql+SELECT DISTINCT+ j.team_id, j.session_id, j.window_id, j.full_snapshot_ts_ms,+ j.root_types,+ 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 snapshots s+ ON j.team_id = s.team_id+ AND j.session_id = s.session_id+ AND j.window_id = s.window_id+ AND j.full_snapshot_ts_ms = s.event_ts_ms+WHERE NOT j.block_index_truncated AND NOT s.block_index_truncated;+```++This query returns candidates. A timestamp is not a unique rrweb event ID.+Fetch the referenced blocks, check the event kind and timestamp at each index, and deduplicate identical snapshots by content.+Reject a join if distinct full snapshots still share its team, session, window, and timestamp.+Several JSON-LD scripts can label one snapshot. Combine their labels only after that validation.+Do not count them as separate training examples.++Older SDK events and mutation captures have no explicit snapshot reference.+They still appear in the label index, but proximity matching is approximate and must stay separate from explicitly linked pairs.+Out-of-order arrivals need no ingestion-side session cache: a later query can join both entries once both blocks exist.++## Domain and page coverage++Use the latest preceding `page` event in the same team, session, and window as provisional URL context.+Page entries are independent rows because a URL change and a snapshot can arrive in separate payloads.+Check that context when fetching the recording; missing navigation events or truncated index blocks can leave it incomplete.++URLs come from the anonymizer's post-scrub metadata.+Their hostnames permit site grouping, but redacted paths can merge distinct pages.+Report unique scrubbed URLs as a lower bound on page diversity.+Exact page counts need a separately reviewed fingerprint of the original page identity.+For domain-disjoint datasets, normalize hostnames to registrable domains with a public suffix list before assigning train, dev, and test groups.++## Delivery and limits++Each block has a 128 KiB index budget. If it exceeds that budget, its retained entries have `block_index_truncated=true`.+The recorder still stores all replay events.+The metadata batcher also flushes at 32 MiB of input messages, checked after each Kafka batch.+This limits accumulation to that threshold plus one input batch; decoded objects and Parquet encoding require additional memory.+The metadata sink writes index partitions sequentially and commits Kafka offsets only after all index and block-metadata 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 index failures.+`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.++The consumer can deploy before the producer because index metadata is optional.+Deploy the consumer first: an older consumer accepts new metadata but does not write the index.+Confirm that the sink's S3 permissions and bucket lifecycle policy cover the new sibling prefix before rollout.+This change does not backfill old recordings.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/kafka/types.ts b/nodejs/src/ingestion/pipelines/sessionreplay/kafka/types.tsindex f29627faf458..0f6a64c3e05e 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/kafka/types.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/kafka/types.ts@@ -64,14 +64,17 @@ export const PRE_SERIALIZED_FLAG_ACTIVE = 1export const PRE_SERIALIZED_FLAG_CLICK = 2export const PRE_SERIALIZED_FLAG_KEYPRESS = 4export const PRE_SERIALIZED_FLAG_MOUSE_ACTIVITY = 8+export const PRE_SERIALIZED_FLAG_FULL_SNAPSHOT = 16export const PreSerializedEventMetaSchema = z.object({ts: z.number(),flags: z.number(),href: z.string().optional(),+ jsonLd: z.object({ rootTypes: z.array(z.string()), fullSnapshotTimestamp: z.number().optional() }).optional(),})export const PreSerializedEventsSchema = z.object({+ windowId: z.string().optional(),lines: z.instanceof(Buffer),events: z.array(PreSerializedEventMetaSchema),consoleLogCount: z.number(),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 5f9df5e33b5e..e0c3eec624ba 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@@ -51,14 +51,25 @@ describe('BlockMetadataBatcher', () => {offsets = { offsetsStore: jest.fn() }})- it('accumulates across batches and flushes once at the row cap', async () => {- const batcher = makeBatcher(60_000, 3)+ it.each(['rows', 'bytes'])('accumulates across batches and flushes once at the %s cap', async (limit) => {+ const batcher = new BlockMetadataBatcher(+ store,+ offsets,+ {+ flushIntervalMs: 60_000,+ maxRows: limit === 'rows' ? 3 : 1000,+ maxBytes: limit === 'bytes' ? msg(0).value!.length * 3 : undefined,+ },+ 0+ )await batcher.handleBatch([msg(0), msg(1)], 0)expect(store.write).not.toHaveBeenCalled() // 2 < 3, still bufferedawait batcher.handleBatch([msg(2), msg(3)], 0)expect(store.write).toHaveBeenCalledTimes(1)expect(store.write.mock.calls[0][0]).toHaveLength(4) // all four rolled into one object+ await batcher.handleBatch([msg(4)], 0)+ expect(store.write).toHaveBeenCalledTimes(1)})it('flushes the buffer once the interval elapses, even on an empty poll', async () => {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 6e2e64a2f754..8de4f310833b 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@@ -16,10 +16,12 @@ export interface OffsetStore {export interface BlockMetadataBatcherOptions {flushIntervalMs: numbermaxRows: number+ maxBytes?: number}export class BlockMetadataBatcher {private buffer: MlBlockMetadataRow[] = []+ private bufferedBytes = 0private pendingOffsets = new Map<string, TopicPartitionOffset>()private lastFlushMs: number@@ -34,6 +36,9 @@ export class BlockMetadataBatcher {/** Buffers a batch and flushes once the buffer is old enough or large enough. */public async handleBatch(messages: Message[], nowMs: number): Promise<void> {+ for (const message of messages) {+ this.bufferedBytes += message.value?.length ?? 0+ }for (const row of parseBlockMetadataMessages(messages)) {this.buffer.push(row)}@@ -47,7 +52,10 @@ export class BlockMetadataBatcher {}private shouldFlush(nowMs: number): boolean {- if (this.buffer.length >= this.options.maxRows) {+ if (+ this.buffer.length >= this.options.maxRows ||+ this.bufferedBytes >= (this.options.maxBytes ?? 32 * 1024 * 1024)+ ) {return true}// Flush on the interval whenever there's anything to commit — including offsets for batches that@@ -67,6 +75,7 @@ export class BlockMetadataBatcher {await this.store.write(this.buffer)this.buffer = []}+ this.bufferedBytes = 0if (this.pendingOffsets.size > 0) {// Commit after the write lands so a failed write replays; skipped-only batches still advance here.this.offsetStore.offsetsStore([...this.pendingOffsets.values()])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 3cf22d2f9f82..6b135d418191 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@@ -72,6 +72,111 @@ describe('BlockMetadataParquetStore', () => {expect(rows[0].snapshot_source).toBe('web')})+ it('indexes cross-block pairs by session start day and preserves window and fractional timestamps', async () => {+ const store = new BlockMetadataParquetStore(s3, 'ml-bucket', 'block-metadata', 'pod-1')+ const start = Date.parse('2025-01-01T23:59:00Z')+ const snapshotTimestamp = start + 60_000.5+ const full = {+ ...row('s1', 't1'),+ session_start_ts_ms: start,+ first_ts_ms: snapshotTimestamp,+ last_ts_ms: snapshotTimestamp,+ replay_index_entries: [+ { kind: 'full_snapshot' as const, windowId: 'w1', eventTimestamp: snapshotTimestamp, eventIndex: 0 },+ {+ kind: 'page' as const,+ windowId: 'w1',+ eventTimestamp: snapshotTimestamp,+ eventIndex: 1,+ url: 'https://example.com/[redacted]',+ },+ ],+ }+ const label = {+ ...full,+ block_s3_key: 's3://ml-bucket/other-block',+ replay_index_entries: [+ {+ kind: 'json_ld' as const,+ windowId: 'w1',+ eventTimestamp: snapshotTimestamp,+ eventIndex: 2,+ fullSnapshotTimestamp: snapshotTimestamp,+ rootTypes: ['Product'],+ },+ ],+ }+ await store.write([label])+ await store.write([full])+ const indexPuts = puts.filter((put) => put.Key!.includes('-replay-index/'))+ expect(indexPuts).toHaveLength(3)+ for (const put of indexPuts) {+ expect(put.Key).toContain('/session_start_date=2025-01-01/')+ }+ const labels = await readRows(indexPuts.find((put) => put.Key!.includes('kind=json_ld'))!.Body)+ const snapshots = await readRows(indexPuts.find((put) => put.Key!.includes('kind=full_snapshot'))!.Body)+ expect(labels[0]).toMatchObject({+ team_id: 't1',+ session_id: 's1',+ window_id: 'w1',+ event_index: 2,+ full_snapshot_ts_ms: snapshots[0].event_ts_ms,+ root_types: ['Product'],+ block_s3_key: 's3://ml-bucket/other-block',+ block_byte_start: 0,+ block_byte_end: 9,+ })+ expect(snapshots[0].event_ts_ms).toBe(snapshotTimestamp)+ const pages = await readRows(indexPuts.find((put) => put.Key!.includes('kind=page'))!.Body)+ expect(pages[0].url).toBe('https://example.com/[redacted]')+ })++ it('propagates index upload failures so Kafka offsets cannot advance', async () => {+ const store = new BlockMetadataParquetStore(s3, 'ml-bucket', 'block-metadata', 'pod-1')+ jest.mocked(s3.send).mockImplementationOnce(() => Promise.reject(new Error('index unavailable')))+ await expect(+ store.write([+ {+ ...row('s1', 't1'),+ session_start_ts_ms: 1000,+ replay_index_entries: [+ { kind: 'full_snapshot', windowId: 'w1', eventTimestamp: 1000, eventIndex: 0 },+ ],+ },+ ])+ ).rejects.toThrow('index unavailable')+ })++ it.each([+ { session_start_ts_ms: undefined },+ { session_start_ts_ms: 3000 },+ { session_start_ts_ms: 1, last_ts_ms: 8 * 86_400_000 },+ { replay_index_entries: [{ kind: 'full_snapshot', windowId: 'w1', eventTimestamp: 1000, eventIndex: 99 }] },+ {+ replay_index_entries: [+ {+ kind: 'json_ld',+ windowId: 'w1',+ eventTimestamp: 1000,+ eventIndex: 0,+ fullSnapshotTimestamp: 'invalid',+ },+ ],+ },+ ])('keeps block metadata when index fields are unusable: %j', async (override) => {+ const store = new BlockMetadataParquetStore(s3, 'ml-bucket', 'block-metadata', 'pod-1')+ await store.write([+ {+ ...row('s1', 't1'),+ session_start_ts_ms: 1000,+ replay_index_entries: [{ kind: 'full_snapshot', windowId: 'w1', eventTimestamp: 1000, eventIndex: 0 }],+ ...override,+ } as MlBlockMetadataRow,+ ])+ expect(puts).toHaveLength(1)+ expect(puts[0].Key).toMatch(/^block-metadata\/dt=/)+ })+it('sorts rows by (team_id, session_id)', async () => {const store = new BlockMetadataParquetStore(s3, 'ml-bucket', 'block-metadata', 'pod-1')await store.write([row('s9', 't3'), row('s1', 't1'), row('s5', 't2'), row('s2', 't1')])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 058b2b1c8fb7..0cb05ee8f132 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@@ -7,6 +7,7 @@ import { logger } from '~/common/utils/logger'import { MlBlockMetadataRow } from './block-metadata-row'import { MlParquetSinkMetrics } from './metrics'import { rowsToParquetBuffer } from './parquet-writer'+import { replayIndexPartitions, replayIndexToParquetBuffer } from './replay-index'const cmp = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0)@@ -41,6 +42,19 @@ export class BlockMetadataParquetStore {try {// Encoding, key derivation, and upload all count as write failures: each leaves the batch to// replay from Kafka, so the counter must see them, not just the S3 send.+ for (const [partition, records] of replayIndexPartitions(rows)) {+ const indexBody = await replayIndexToParquetBuffer(records)+ this.seq += 1+ await this.s3Client.send(+ new PutObjectCommand({+ Bucket: this.bucket,+ Key: `${this.prefix}-replay-index/v1/${partition}/part-${this.nodeId}-${Date.now()}-${this.seq}.parquet`,+ Body: indexBody,+ ContentType: 'application/vnd.apache.parquet',+ })+ )+ MlParquetSinkMetrics.incReplayIndexRows(String(records[0].kind), records.length)+ }body = await rowsToParquetBuffer(rows)bounds = eventTimeBounds(rows)key = this.objectKey(new Date(bounds.minMs).toISOString().slice(0, 10))diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-row.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-row.test.tsindex 8e7334801325..3cfdd3db4319 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-row.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-row.test.ts@@ -23,6 +23,18 @@ const block = (over: Partial<SessionBlockMetadata> = {}): SessionBlockMetadata =})describe('ml-mirror block-metadata-row', () => {+ it.each([+ ['018bcfe5-6800-7000-8000-000000000001', 1_700_000_000_000],+ ['018BCFE5-6800-7000-8000-000000000001', 1_700_000_000_000],+ ['018bcfe5-6800-4000-8000-000000000001', undefined],+ ['018bcfe5-6800-7000-0000-000000000001', undefined],+ ['legacy-session', undefined],+ ])('derives the session partition before pseudonymizing %s', (sessionId, expected) => {+ const result = toBlockMetadataRow(block({ sessionId: String(sessionId) }), SECRET)!+ expect(result.session_start_ts_ms).toBe(expected)+ expect(result.session_id).not.toBe(sessionId)+ })+describe('parseBlockUrl', () => {it('splits the object key from the byte range', () => {expect(parseBlockUrl('s3://b/key?range=bytes=100-250')).toEqual({ key: 's3://b/key', start: 100, end: 250 })diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-row.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-row.tsindex 26f362b270a7..5af119fb9a2a 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-row.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-row.ts@@ -1,9 +1,13 @@-/** One anonymized block's metadata as a flat row for the ML Parquet dataset; ids are pseudonyms. */+/** One anonymized block's metadata for the ML Parquet datasets; ids are pseudonyms. */+import { ReplayIndexEntry } from '~/ingestion/pipelines/sessionreplay/shared/metadata/replay-index-entry'import { SessionBlockMetadata } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata'import { PSEUDONYM_DISTINCT_ID, PSEUDONYM_SESSION, PSEUDONYM_TEAM, pseudonymize } from './pseudonymize'export interface MlBlockMetadataRow {+ session_start_ts_ms?: number+ replay_index_entries?: ReplayIndexEntry[]+ replay_index_truncated?: booleansession_id: stringteam_id: stringdistinct_id: string@@ -52,7 +56,15 @@ export function toBlockMetadataRow(block: SessionBlockMetadata, secret: string |return null}const { key, start, end } = parseBlockUrl(block.blockUrl)+ const sessionStartTimestamp = sessionStartTimestampFromUuidV7(block.sessionId)return {+ replay_index_entries: block.replayIndexEntries,+ replay_index_truncated: block.replayIndexTruncated,+ ...(sessionStartTimestamp === null+ ? {}+ : {+ session_start_ts_ms: sessionStartTimestamp,+ }),session_id: pseudonymize(secret, PSEUDONYM_SESSION, block.sessionId),team_id: pseudonymize(secret, PSEUDONYM_TEAM, String(block.teamId)),distinct_id: pseudonymize(secret, PSEUDONYM_DISTINCT_ID, block.distinctId),@@ -80,3 +92,11 @@ export function toBlockMetadataRow(block: SessionBlockMetadata, secret: string |retention_period_days: block.retentionPeriodDays,}}++export function sessionStartTimestampFromUuidV7(sessionId: string): number | null {+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(sessionId)) {+ return null+ }+ const timestamp = Number.parseInt(sessionId.slice(0, 8) + sessionId.slice(9, 13), 16)+ return timestamp > 0 ? timestamp : null+}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 89ee1964503c..42f98304da1d 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@@ -16,6 +16,7 @@ import { MlBlockMetadataSink } from './ml-block-metadata-sink'import { PSEUDONYM_DISTINCT_ID, PSEUDONYM_SESSION, PSEUDONYM_TEAM, pseudonymize } from './pseudonymize'const SECRET = 'roundtrip-secret'+const SESSION_A = '018bcfe5-6800-7000-8000-000000000001'const block = (sessionId: string, teamId: number, distinctId: string): SessionBlockMetadata => ({...createNoopBlockMetadata(sessionId, teamId),@@ -28,6 +29,17 @@ const block = (sessionId: string, teamId: number, distinctId: string): SessionBlclickCount: 1,urls: ['https://example.com/[redacted]'],snapshotSource: 'web',+ replayIndexEntries: [+ { kind: 'full_snapshot', windowId: 'w1', eventTimestamp: 1_700_000_000_001.5, eventIndex: 0 },+ {+ kind: 'json_ld',+ windowId: 'w1',+ eventTimestamp: 1_700_000_000_001.5,+ eventIndex: 1,+ fullSnapshotTimestamp: 1_700_000_000_001.5,+ rootTypes: ['Product'],+ },+ ],})async function readRows(body: PutObjectCommandInput['Body']): Promise<Record<string, any>[]> {@@ -56,7 +68,7 @@ describe('ML metadata producer → sink round-trip', () => {} as unknown as IngestionOutputs<MlBlockMetadataOutput>await new MlBlockMetadataSink(outputs, SECRET).storeSessionBlocks([- block('sess-A', 1, 'person-1'),+ block(SESSION_A, 1, 'person-1'),block('sess-B', 2, 'person-2'),])expect(produced).toHaveLength(2)@@ -79,17 +91,28 @@ describe('ML metadata producer → sink round-trip', () => {await batcher.handleBatch(messages, 0)await batcher.flush(1) // force the window out- expect(puts).toHaveLength(1)- const rows = await readRows(puts[0].Body)+ expect(puts).toHaveLength(3)+ const labelPut = puts.find((put) => put.Key!.includes('kind=json_ld'))!+ expect(labelPut.Key).toContain('session_start_date=2023-11-14')+ const labels = await readRows(labelPut.Body)+ expect(labels).toHaveLength(1)+ expect(labels[0]).toMatchObject({+ session_id: pseudonymize(SECRET, PSEUDONYM_SESSION, SESSION_A),+ window_id: 'w1',+ event_index: 1,+ full_snapshot_ts_ms: 1_700_000_000_001.5,+ root_types: ['Product'],+ })+ const rows = await readRows(puts.find((put) => put.Key!.startsWith('block-metadata/dt='))!.Body)expect(rows).toHaveLength(2)const bySession = new Map(rows.map((r) => [r.session_id, r]))- const a = bySession.get(pseudonymize(SECRET, PSEUDONYM_SESSION, 'sess-A'))!+ const a = bySession.get(pseudonymize(SECRET, PSEUDONYM_SESSION, SESSION_A))!expect(a).toBeDefined()expect(a.team_id).toBe(pseudonymize(SECRET, PSEUDONYM_TEAM, '1'))expect(a.distinct_id).toBe(pseudonymize(SECRET, PSEUDONYM_DISTINCT_ID, 'person-1'))// Raw ids never survive the trip (BigInt-safe stringify, since INT64 fields read back as bigint).- expect(a.session_id).not.toBe('sess-A')+ expect(a.session_id).not.toBe(SESSION_A)const serialized = JSON.stringify(a, (_key, value) => (typeof value === 'bigint' ? value.toString() : value))expect(serialized).not.toContain('person-1')// Real block fields round-trip through JSON → Parquet → read.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.tsindex 0d9d4c80d74c..4ddab906cdc3 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts@@ -203,6 +203,23 @@ const PARTITION_DAY_BUCKETS = [0, 1, 2, 3, 7, 14, 30, 90, 365]* buffer stays empty, so flush advances offsets without a write. Kafka lag alone can't see that state.*/export class MlParquetSinkMetrics {+ private static readonly replayIndexRows = new Counter({+ name: 'ml_mirror_replay_index_rows_written_total',+ help: 'Replay index rows uploaded by event kind, including retries',+ labelNames: ['kind'],+ })+ private static readonly replayIndexSkipped = new Counter({+ name: 'ml_mirror_replay_index_skipped_total',+ help: 'Replay index blocks or entries omitted by reason',+ labelNames: ['reason'],+ })+ public static incReplayIndexRows(kind: string, count: number): void {+ this.replayIndexRows.labels(kind).inc(count)+ }+ public static incReplayIndexSkipped(reason: 'session_start' | 'invalid_entry' | 'truncated_block'): void {+ this.replayIndexSkipped.labels(reason).inc()+ }+private static readonly rowsParsed = new Counter({name: 'ml_mirror_parquet_sink_rows_parsed_total',help: 'Block-metadata rows parsed from Kafka and accepted into the Parquet buffer',diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.tsindex 32d298d7236f..8da0c160425c 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.ts@@ -126,6 +126,7 @@ describe('createParseAndAnonymizeMessageStep', () => {expect(parsed.eventsByWindowId).toEqual({})expect(parsed.preSerialized.lines.toString()).toContain('"window-1"')expect(parsed.preSerialized.events).toEqual([{ ts: now, flags: 5 }])+ expect(parsed.preSerialized.windowId).toBe('window-1')expect(parsed.preSerialized.consoleWarnCount).toBe(2)expect(parsed.eventsRange.start.toMillis()).toBe(now)expect(parsed.eventsRange.end.toMillis()).toBe(now + 1000)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.tsindex 4a0c95d27436..e6254971ef05 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts@@ -272,6 +272,7 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInp// Events live in `preSerialized` — consumers use its lines + per-event metadata.eventsByWindowId: {},preSerialized: {+ windowId: meta.windowId,lines: result.lines!,events: meta.events,consoleLogCount: meta.consoleLogCount,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.tsnew file mode 100644index 000000000000..83b714bd4fdb--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.ts@@ -0,0 +1,90 @@+import { ParquetSchema } from '@dsnp/parquetjs'++import { ReplayIndexEntrySchema } from '~/ingestion/pipelines/sessionreplay/shared/metadata/replay-index-entry'+import { parquetRecordsToBuffer } from '~/ingestion/pipelines/sessionreplay/shared/parquet'++import { MlBlockMetadataRow } from './block-metadata-row'+import { MlParquetSinkMetrics } from './metrics'++const DAY_MS = 86_400_000+const schema = new ParquetSchema({+ team_id: { type: 'UTF8', compression: 'SNAPPY' },+ session_id: { type: 'UTF8', compression: 'SNAPPY' },+ window_id: { type: 'UTF8', compression: 'SNAPPY' },+ kind: { type: 'UTF8', compression: 'SNAPPY' },+ session_start_ts_ms: { type: 'DOUBLE', compression: 'SNAPPY' },+ event_ts_ms: { type: 'DOUBLE', compression: 'SNAPPY' },+ block_index_truncated: { type: 'BOOLEAN', compression: 'SNAPPY' },+ event_index: { type: 'INT32', compression: 'SNAPPY' },+ full_snapshot_ts_ms: { type: 'DOUBLE', optional: true, compression: 'SNAPPY' },+ root_types: { type: 'UTF8', repeated: true, compression: 'SNAPPY' },+ url: { type: 'UTF8', optional: true, compression: 'SNAPPY' },+ block_s3_key: { type: 'UTF8', compression: 'SNAPPY' },+ block_byte_start: { type: 'DOUBLE', optional: true, compression: 'SNAPPY' },+ block_byte_end: { type: 'DOUBLE', optional: true, compression: 'SNAPPY' },+})++export function replayIndexPartitions(rows: MlBlockMetadataRow[]): Map<string, Record<string, unknown>[]> {+ const partitions = new Map<string, Record<string, unknown>[]>()+ for (const row of rows) {+ if (row.replay_index_truncated) {+ MlParquetSinkMetrics.incReplayIndexSkipped('truncated_block')+ }+ if (!Array.isArray(row.replay_index_entries) || row.replay_index_entries.length === 0) {+ continue+ }+ const started = row.session_start_ts_ms+ if (+ typeof started !== 'number' ||+ !Number.isSafeInteger(started) ||+ started <= 0 ||+ started > 0xffffffffffff ||+ started > row.last_ts_ms ||+ row.last_ts_ms - started > 7 * DAY_MS+ ) {+ MlParquetSinkMetrics.incReplayIndexSkipped('session_start')+ continue+ }+ const date = new Date(started).toISOString().slice(0, 10)+ for (const value of row.replay_index_entries) {+ const result = ReplayIndexEntrySchema.safeParse(value)+ if (+ !result.success ||+ result.data.eventIndex >= row.event_count ||+ result.data.eventTimestamp < row.first_ts_ms ||+ result.data.eventTimestamp > row.last_ts_ms+ ) {+ MlParquetSinkMetrics.incReplayIndexSkipped('invalid_entry')+ continue+ }+ const entry = result.data+ const key = `kind=${entry.kind}/session_start_date=${date}`+ let records = partitions.get(key)+ if (!records) {+ records = []+ partitions.set(key, records)+ }+ records.push({+ team_id: row.team_id,+ session_id: row.session_id,+ window_id: entry.windowId,+ kind: entry.kind,+ session_start_ts_ms: started,+ event_ts_ms: entry.eventTimestamp,+ event_index: entry.eventIndex,+ block_index_truncated: row.replay_index_truncated === true,+ full_snapshot_ts_ms: entry.fullSnapshotTimestamp ?? null,+ root_types: entry.rootTypes ?? [],+ url: entry.url ?? null,+ block_s3_key: row.block_s3_key,+ block_byte_start: row.block_byte_start,+ block_byte_end: row.block_byte_end,+ })+ }+ }+ return partitions+}++export function replayIndexToParquetBuffer(records: Record<string, unknown>[]): Promise<Buffer> {+ return parquetRecordsToBuffer(schema, records)+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.tsindex 64c5a80134bb..cb4ab80e3adc 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts@@ -277,6 +277,8 @@ export class SessionBatchRecorder {messageCount,snapshotSource,snapshotLibrary,+ replayIndexEntries,+ replayIndexTruncated,batchId,} = await sessionBlockRecorder.end()@@ -328,6 +330,8 @@ export class SessionBatchRecorder {messageCount,snapshotSource,snapshotLibrary,+ replayIndexEntries,+ replayIndexTruncated,batchId,eventCount,retentionPeriodDays,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.test.tsindex 8b1d183cca61..643b000ad25c 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.test.ts@@ -1120,6 +1120,72 @@ describe('SnappySessionRecorder', () => {})})+ it('bounds index metadata without dropping replay events', async () => {+ const t = 1_700_000_000_000+ const href = `https://example.com/${'a'.repeat(4000)}`+ const events = Array.from({ length: 100 }, () => ({ ts: t, flags: 0, href }))+ recorder.recordMessage({+ ...createMessage('w1', []),+ eventsRange: { start: DateTime.fromMillis(t), end: DateTime.fromMillis(t) },+ preSerialized: {+ windowId: 'w1',+ events,+ lines: Buffer.from(+ `${JSON.stringify(['w1', { type: 4, timestamp: t, data: { href } }])}\n`.repeat(events.length)+ ),+ consoleLogCount: 0,+ consoleWarnCount: 0,+ consoleErrorCount: 0,+ },+ })+ const result = await recorder.end()+ expect(result.eventCount).toBe(100)+ expect(result.replayIndexTruncated).toBe(true)+ expect(result.replayIndexEntries!.length).toBeGreaterThan(0)+ expect(result.replayIndexEntries!.length).toBeLessThan(100)+ expect(Buffer.byteLength(JSON.stringify(result.replayIndexEntries))).toBeLessThan(128 * 1024 + 2)+ })++ it('keeps index ordinals across payloads and windows', async () => {+ const t = 1_700_000_000_000.5+ const eventBatches = [+ { windowId: 'w1', events: [{ ts: t, flags: 16 }] },+ {+ windowId: 'w2',+ events: [+ { ts: t, flags: 16 },+ { ts: t, flags: 0, jsonLd: { rootTypes: ['Product'], fullSnapshotTimestamp: t } },+ ],+ },+ ]+ for (const batch of eventBatches) {+ recorder.recordMessage({+ ...createMessage(batch.windowId, []),+ eventsRange: { start: DateTime.fromMillis(t), end: DateTime.fromMillis(t) },+ preSerialized: {+ ...batch,+ lines: Buffer.from('[]\n'.repeat(batch.events.length)),+ consoleLogCount: 0,+ consoleWarnCount: 0,+ consoleErrorCount: 0,+ },+ })+ }+ const result = await recorder.end()+ expect(result.replayIndexEntries).toEqual([+ { kind: 'full_snapshot', windowId: 'w1', eventTimestamp: t, eventIndex: 0 },+ { kind: 'full_snapshot', windowId: 'w2', eventTimestamp: t, eventIndex: 1 },+ {+ kind: 'json_ld',+ windowId: 'w2',+ eventTimestamp: t,+ eventIndex: 2,+ rootTypes: ['Product'],+ fullSnapshotTimestamp: t,+ },+ ])+ })+describe('Pre-serialized messages (native anonymizer fast path)', () => {it('appends the block lines verbatim and derives counts from the per-event metadata', async () => {// Flag bits mirror rust/replay-anonymizer `snapshot.rs`: 1=active 2=click 4=keypress 8=mouse.@@ -1135,6 +1201,7 @@ describe('SnappySessionRecorder', () => {eventsRange: { start: DateTime.fromMillis(t0), end: DateTime.fromMillis(t0 + 2000) },preSerialized: {lines,+ windowId: 'w1',events: [{ ts: t0, flags: 0, href: 'https://example.com/[redacted]' },{ ts: t0 + 1000, flags: 1 | 2 | 8 }, // click: active + click + mouse@@ -1152,6 +1219,15 @@ describe('SnappySessionRecorder', () => {const result = await recorder.end()expect(await readSnappyBuffer(result.buffer)).toBe(lines.toString())expect(result.eventCount).toBe(3)+ expect(result.replayIndexEntries).toEqual([+ {+ kind: 'page',+ windowId: 'w1',+ eventTimestamp: t0,+ eventIndex: 0,+ url: 'https://example.com/[redacted]',+ },+ ])expect(result.clickCount).toBe(1)expect(result.keypressCount).toBe(1)expect(result.mouseActivityCount).toBe(1)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.tsindex cf931c788985..6043aae849c5 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.ts@@ -5,6 +5,7 @@ import { logger } from '~/common/utils/logger'import {PRE_SERIALIZED_FLAG_ACTIVE,PRE_SERIALIZED_FLAG_CLICK,+ PRE_SERIALIZED_FLAG_FULL_SNAPSHOT,PRE_SERIALIZED_FLAG_KEYPRESS,PRE_SERIALIZED_FLAG_MOUSE_ACTIVITY,ParsedMessageData,@@ -15,10 +16,12 @@ import {activeMillisecondsFromSegmentationEvents,toSegmentationEvent,} from '~/ingestion/pipelines/sessionreplay/segmentation'+import { ReplayIndexEntry } from '~/ingestion/pipelines/sessionreplay/shared/metadata/replay-index-entry'const MAX_SNAPSHOT_FIELD_LENGTH = 1000const MAX_URL_LENGTH = 4 * 1024 // 4KBconst MAX_URLS_COUNT = 25+const MAX_REPLAY_INDEX_BYTES = 128 * 1024export interface EndResult {/** The complete compressed session block */@@ -51,6 +54,8 @@ export interface EndResult {snapshotLibrary: string | null/** ID of the batch this session belongs to */batchId: string+ replayIndexEntries?: ReplayIndexEntry[]+ replayIndexTruncated?: boolean}/**@@ -94,6 +99,9 @@ export class SnappySessionRecorder {private snapshotLibrary: string | null = nullprivate segmentationEvents: SegmentationEvent[] = []private droppedUrlsCount: number = 0+ private replayIndexEntries: ReplayIndexEntry[] = []+ private replayIndexBytes = 0+ private replayIndexTruncated = falseconstructor(public readonly sessionId: string,@@ -186,10 +194,25 @@ export class SnappySessionRecorder {* instead of walking parsed events.*/private recordPreSerialized(message: ParsedMessageData): number {- const { lines, events } = message.preSerialized!+ const { lines, events, windowId } = message.preSerialized!this.uncompressedChunks.push(lines)for (const event of events) {+ if (+ windowId !== undefined &&+ (event.flags & PRE_SERIALIZED_FLAG_FULL_SNAPSHOT || event.jsonLd || event.href)+ ) {+ const common = { windowId, eventTimestamp: event.ts, eventIndex: this.eventCount }+ if (event.flags & PRE_SERIALIZED_FLAG_FULL_SNAPSHOT) {+ this.appendReplayIndexEntry({ ...common, kind: 'full_snapshot' })+ }+ if (event.jsonLd) {+ this.appendReplayIndexEntry({ ...common, kind: 'json_ld', ...event.jsonLd })+ }+ if (event.href) {+ this.appendReplayIndexEntry({ ...common, kind: 'page', url: event.href.slice(0, MAX_URL_LENGTH) })+ }+ }this.segmentationEvents.push({timestamp: event.ts,isActive: (event.flags & PRE_SERIALIZED_FLAG_ACTIVE) !== 0,@@ -213,6 +236,19 @@ export class SnappySessionRecorder {return lines.length}+ private appendReplayIndexEntry(entry: ReplayIndexEntry): void {+ if (this.replayIndexTruncated) {+ return+ }+ const bytes = Buffer.byteLength(JSON.stringify(entry)) + 1+ if (this.replayIndexBytes + bytes > MAX_REPLAY_INDEX_BYTES) {+ this.replayIndexTruncated = true+ return+ }+ this.replayIndexEntries.push(entry)+ this.replayIndexBytes += bytes+ }+private addUrl(url: string): void {if (!url) {return@@ -285,6 +321,8 @@ export class SnappySessionRecorder {snapshotSource: this.snapshotSource,snapshotLibrary: this.snapshotLibrary,batchId: this.batchId,+ ...(this.replayIndexEntries.length ? { replayIndexEntries: this.replayIndexEntries } : {}),+ ...(this.replayIndexTruncated ? { replayIndexTruncated: true } : {}),}}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/metadata/replay-index-entry.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/metadata/replay-index-entry.tsnew file mode 100644index 000000000000..d12cd695bb14--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/metadata/replay-index-entry.ts@@ -0,0 +1,13 @@+import { z } from 'zod'++export const ReplayIndexEntrySchema = z.object({+ kind: z.enum(['full_snapshot', 'json_ld', 'page']),+ windowId: z.string(),+ eventTimestamp: z.number().finite().positive(),+ eventIndex: z.number().int().nonnegative(),+ fullSnapshotTimestamp: z.number().finite().positive().optional(),+ rootTypes: z.array(z.string().max(100)).max(64).optional(),+ url: z.string().max(4096).optional(),+})++export type ReplayIndexEntry = z.infer<typeof ReplayIndexEntrySchema>diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata.tsindex 79c51b48c219..dcb3fcde9471 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata.ts@@ -1,5 +1,7 @@import { DateTime } from 'luxon'+import { ReplayIndexEntry } from './replay-index-entry'+/*** Creates a no-op metadata block with all counters set to zero.* Used as a base for special events like deletion markers.@@ -40,6 +42,8 @@ export function createDeletionBlockMetadata(sessionId: string, teamId: number):}export interface SessionBlockMetadata {+ replayIndexEntries?: ReplayIndexEntry[]+ replayIndexTruncated?: boolean/** Unique identifier for the session */sessionId: string/** ID of the team that owns this session recording */diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 438e28f95b4e..a1e3394486cc 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -9318,7 +9318,7 @@ dependencies = [[[package]]name = "posthog-replay-anonymizer"-version = "0.5.0"+version = "0.6.0"dependencies = ["ahash 0.8.12","anyhow",diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.tsindex 8f5f1caa215a..1bb9963e8bd4 100644--- a/rust/replay-anonymizer-node/src/index.ts+++ b/rust/replay-anonymizer-node/src/index.ts@@ -17,6 +17,7 @@ export interface AnonymizeEventMeta {flags: number/** Post-scrub `hrefFrom(event)` (`data.href` / `data.payload.href`, trimmed), when present. */href?: string+ jsonLd?: { rootTypes: string[]; fullSnapshotTimestamp?: number }}/** One collected original image: `offset..offset+len` in {@link AnonymizeKafkaPayloadResult.images}. */diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.tomlindex 50d4afcf5c20..0c11d7db50fe 100644--- a/rust/replay-anonymizer/Cargo.toml+++ b/rust/replay-anonymizer/Cargo.toml@@ -1,6 +1,6 @@[package]name = "posthog-replay-anonymizer"-version = "0.5.0"+version = "0.6.0"edition = "2021"description = "PII scrubber for rrweb session-replay events: text/URL redaction, native image blur, and canvas/cv neutralization"license = "MIT"diff --git a/rust/replay-anonymizer/src/snapshot.rs b/rust/replay-anonymizer/src/snapshot.rsindex 79a0468286d3..6470f65aa541 100644--- a/rust/replay-anonymizer/src/snapshot.rs+++ b/rust/replay-anonymizer/src/snapshot.rs@@ -36,8 +36,8 @@ use crate::event::{};use crate::images::ImagePolicy;use crate::json::{- as_f64, as_object, as_small_uint, as_str, parse_untrusted, parse_untrusted_with_buffers,- reject_if_too_deep,+ as_array, as_f64, as_object, as_small_uint, as_str, parse_untrusted,+ parse_untrusted_with_buffers, reject_if_too_deep,};use crate::scan::{self, Span};use crate::timings::PhaseTimings;@@ -111,20 +111,32 @@ pub const FLAG_ACTIVE: u8 = 1;pub const FLAG_CLICK: u8 = 2;pub const FLAG_KEYPRESS: u8 = 4;pub const FLAG_MOUSE_ACTIVITY: u8 = 8;+pub const FLAG_FULL_SNAPSHOT: u8 = 16;// `DateTime.fromMillis` validity bound (JS Date range: ±8.64e15 ms).const MAX_JS_DATE_MS: f64 = 8.64e15;/// Per-emitted-line metadata, in line order.#[derive(Debug, Clone, Serialize, PartialEq)]+#[serde(rename_all = "camelCase")]pub struct EventMeta {/// The event's `timestamp` (epoch ms; can be fractional).pub ts: f64,- /// Bitmask of FLAG_ACTIVE / FLAG_CLICK / FLAG_KEYPRESS / FLAG_MOUSE_ACTIVITY.+ /// Bitmask of FLAG_ACTIVE / FLAG_CLICK / FLAG_KEYPRESS / FLAG_MOUSE_ACTIVITY / FLAG_FULL_SNAPSHOT.pub flags: u8,/// Post-scrub `hrefFrom(event)` (`data.href` or `data.payload.href`, trimmed, non-empty).#[serde(skip_serializing_if = "Option::is_none")]pub href: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub json_ld: Option<JsonLdMeta>,+}++#[derive(Debug, Clone, Serialize, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct JsonLdMeta {+ pub root_types: Vec<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub full_snapshot_timestamp: Option<f64>,}/// One collected original image: `offset..offset+len` in [`AnonymizedMessage::image_bytes`].@@ -1255,6 +1267,7 @@ fn process_event_at(ts,flags: flags_of(ty, source, interaction),href: scanned_href(inner, &es),+ json_ld: None,});return Ok(end);}@@ -1343,6 +1356,7 @@ fn pass_through(ts,flags: flags_of(ty, source, interaction),href,+ json_ld: None,});}@@ -1375,6 +1389,9 @@ fn scanned_href(inner: &[u8], d: &EventScan) -> Option<String> {}fn flags_of(ty: Option<u8>, source: Option<u8>, interaction: Option<u8>) -> u8 {+ if ty == Some(TYPE_FULL_SNAPSHOT) {+ return FLAG_FULL_SNAPSHOT;+ }if ty != Some(TYPE_INCREMENTAL) {return 0;}@@ -1422,6 +1439,23 @@ fn push_meta_from_data(ty: Option<u8>, ts: f64, data: Option<&Value<'_>>, sink:ts,flags: flags_of(ty, source, interaction),href,+ json_ld: if ty == Some(TYPE_CUSTOM)+ && dobj.and_then(|d| d.get("tag")).and_then(as_str) == Some(JSON_LD_EVENT_TAG)+ {+ let mut root_types = Vec::new();+ if let Some(payload) = dobj.and_then(|d| d.get("payload")) {+ collect_root_types(payload, &mut root_types);+ }+ Some(JsonLdMeta {+ root_types,+ full_snapshot_timestamp: dobj+ .and_then(|d| d.get("fullSnapshotTimestamp"))+ .and_then(as_f64)+ .filter(|ts| ts.is_finite() && *ts > 0.0 && *ts <= MAX_JS_DATE_MS),+ })+ } else {+ None+ },});if ty == Some(TYPE_CUSTOM)@@ -1449,6 +1483,37 @@ fn push_meta_from_data(ty: Option<u8>, ts: f64, data: Option<&Value<'_>>, sink:}}+fn collect_root_types(value: &Value<'_>, types: &mut Vec<String>) {+ if types.len() >= 64 {+ return;+ }+ if let Some(items) = as_array(value) {+ for item in items {+ collect_root_types(item, types);+ }+ } else if let Some(object) = as_object(value) {+ if let Some(type_value) = object.get("@type") {+ let mut add_type = |value: &Value<'_>| {+ if let Some(name) = as_str(value) {+ if types.len() < 64 && !types.iter().any(|t| t == name) {+ types.push(name.to_owned());+ }+ }+ };+ if let Some(items) = as_array(type_value) {+ for item in items {+ add_type(item);+ }+ } else {+ add_type(type_value);+ }+ }+ if let Some(graph) = object.get("@graph") {+ collect_root_types(graph, types);+ }+ }+}+/// Full-parse fallback for a single event whose bytes the scanner cannot prove safe (escaped or/// duplicate keys): parse, scrub, and re-serialize the whole event, normalizing like JSON.parse.fn process_event_via_tree(ctx: &Ctx<'_>, inner: &[u8], span: Span, sink: &mut Sink) -> SResult<()> {diff --git a/rust/replay-anonymizer/tests/snapshot.rs b/rust/replay-anonymizer/tests/snapshot.rsindex 85fb8eae4217..489bb0b5e1d0 100644--- a/rust/replay-anonymizer/tests/snapshot.rs+++ b/rust/replay-anonymizer/tests/snapshot.rs@@ -136,6 +136,44 @@ fn end_to_end_contract() {);}+#[test]+fn replay_index_metadata_tracks_snapshots_and_root_types() {+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());+ for (payload, expected) in [+ (+ json!({"@context":"https://schema.org", "@type":"Product", "offers":{"@type":"Offer", "price":10}}),+ vec!["Product"],+ ),+ (+ json!({"@context":"https://schema.org", "@graph":[{"@type":["WebPage", "Product"]}, {"@type":"WebPage"}]}),+ vec!["WebPage", "Product"],+ ),+ (+ json!([{"@context":"https://schema.org", "@type":"Article"}, {"@context":"https://schema.org", "@type":"Product"}]),+ vec!["Article", "Product"],+ ),+ ] {+ for reference in [json!(TS0 + 0.5), json!(-1), json!("invalid"), Value::Null] {+ let inner = snapshot_message(json!([+ {"type":2,"timestamp":TS0 + 0.5,"data":{"node":{"type":0,"id":1,"childNodes":[]},"initialOffset":{"left":0,"top":0}}},+ {"type":5,"timestamp":TS0 + 0.5,"data":{"tag":"$json_ld","payload":payload,"fullSnapshotTimestamp":reference}},+ ]));+ assert_stream_matches_tree(&allow, &inner.to_string(), "replay index metadata");+ let out = run(&allow, &payload_of(&inner)).unwrap();+ assert_eq!(+ out.meta.events[0].flags,+ posthog_replay_anonymizer::snapshot::FLAG_FULL_SNAPSHOT+ );+ let metadata = out.meta.events[1].json_ld.as_ref().unwrap();+ assert_eq!(metadata.root_types, expected);+ assert_eq!(+ metadata.full_snapshot_timestamp,+ reference.as_f64().filter(|n| *n > 0.0)+ );+ }+ }+}+#[test]fn failure_classification_matches_the_ts_parse_step() {let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());