Skip to content

: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.

feat(ai-research): encrypt ml replay data by session (#98650)

Robbiee3416aeba543
diff --git a/docs/internal/session-replay-structured-data-index.md b/docs/internal/session-replay-structured-data-index.md
index 21b185a35903..5f803a7be1a1 100644
--- a/docs/internal/session-replay-structured-data-index.md
+++ b/docs/internal/session-replay-structured-data-index.md
@@ -1,13 +1,54 @@
# Session replay structured data index
-The ML mirror writes a sparse Parquet index for full snapshots, `$json_ld` custom events, and URL changes.
+The 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.
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.
+See [ML replay data](../../products/ai_training/docs/replay-data.md) for identifier formats and dataset paths.
+
## Storage and lookup
-The existing metadata sink writes the index to the same bucket as block metadata.
+### Encrypted v2 index and metadata
+
+V2 writes `block-metadata/v2/<YYYY-MM>/part-<writer>-<time>-<sequence>.parquet` in the recording bucket.
+The partition follows the session's UTC start month, including late arrivals.
+The separate eval index uses these paths:
+
+```text
+block-metadata-replay-index/v2/2026-09/kind=json_ld/part-<writer>-<time>-<sequence>.parquet
+block-metadata-replay-index/v2/2026-09/kind=full_snapshot/part-<writer>-<time>-<sequence>.parquet
+block-metadata-replay-index/v2/2026-09/kind=page/part-<writer>-<time>-<sequence>.parquet
+```
+
+The session's UTC start month selects the partition for every kind, including events and uploads in later months.
+Each Parquet row exposes real team and session IDs and contains an encrypted array of projected entries from one block and kind.
+Use `ReplayV2Reader.replay_index(object_keys, kind, excluded_team_ids=training_team_ids)` to decrypt and flatten these entries.
+The sink applies the URL matching rules below before encryption.
+The index uses the recording's session key, so the same consent and deletion checks apply.
+The JSON-LD payload remains in the referenced replay block.
+
+For evals, exclude the union of real team IDs from every partition used to train the model.
+A separate month does not imply a separate team.
+Apply the exclusion to labels, snapshots, and pages before pairing them.
+Keep these IDs in the preparation manifest and remove them from model inputs.
+
+Use `ReplayV2Reader.metadata()` to decrypt selected metadata objects with live key and consent checks.
+Each returned block contains raw team and session IDs, its storage key and byte range, `replay_index_entries`, and `replay_index_truncated`.
+The 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.
+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.
+Use `ReplayV2Reader.recording()` to fetch and decrypt selected recording blocks before inspecting their events.
+
+### Legacy v1 sparse index
+
+The legacy 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:
@@ -17,7 +58,7 @@ block-metadata-replay-index/v1/kind=full_snapshot/session_start_date=2026-09-01/
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.
+Each legacy row identifies pseudonymized team and session IDs, 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.
@@ -29,7 +70,7 @@ 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.
+The legacy index partitions each row by its session's UTC start date, decoded from UUIDv7.
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.
@@ -38,7 +79,8 @@ For an event-time search, include the preceding seven session-start dates and fi
## Full snapshot URLs
-The ML-mirror metadata consumer enriches index rows before writing Parquet.
+The metadata consumer enriches projected v1 and v2 index rows 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.
The URL entry must belong to the same window and have a timestamp no later than the snapshot.
@@ -57,7 +99,8 @@ Payload validation must account for this limit.
## Pairing labels with snapshots
-Read the requested session-start partitions into DuckDB views named `labels`, `snapshots`, and `pages`.
+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.
Its one-second Meta gap and two-second label gap are example selection parameters, not SDK guarantees.
@@ -123,7 +166,8 @@ Missing events, masked Meta events, and URL collisions can also conceal a naviga
Neither an adjacent URL nor a temporal fallback proves the label describes that snapshot.
A later query can find late arrivals once both blocks exist; record the input object list to make a dataset run reproducible.
-Fetch each distinct block key and inclusive byte range once, then decompress its Snappy JSONL recording lines.
+For v1, fetch each distinct block key and inclusive byte range once, then decompress its Snappy JSONL recording lines.
+For v2, use the encrypted recording reader to perform the fetch, decryption, and decompression.
Check the window, event kind, and timestamp at each event index before using its payload.
Reject ambiguous matches, including distinct full snapshots that share a timestamp or several plausible snapshots for one label.
A timestamp is not a unique rrweb event ID.
@@ -139,14 +183,16 @@ Exclude JSON-LD rows without URLs; do not infer those URLs from older SDK naviga
Use 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 ML-mirror consumer combines them by event index.
+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 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.
-JSON-LD events with a URL do not also create a `page` row in Parquet.
+Both index versions omit the duplicate `page` row for JSON-LD events with a URL.
+The original entries inside encrypted v2 block metadata retain both entries.
Count distinct normalized scrubbed URLs as page families.
Scrubbing can group similar paths, which helps deduplicate similar pages.
@@ -168,7 +214,8 @@ Keep split assignment stable across resampling and dataset versions.
Audit examples where one scrubbed URL has different labels; URL deduplication alone must not silently choose a conflicting label.
Exclude cross-split content duplicates or keep their domain groups together before freezing the final split.
-This layout supports a bounded-date Parquet scan followed by selective block fetches.
+The 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.
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.
@@ -177,14 +224,17 @@ A compacted metadata table can reduce file-listing overhead later without changi
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.
+The metadata batcher also flushes at 32 MiB of input messages and buffered encrypted index envelopes, 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.
+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.
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.
+The existing write-error metric includes storage failures.
+The following index counters cover both index versions.
`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.
@@ -197,7 +247,8 @@ This change does not backfill old recordings.
## JSON-LD URL rollout
Deploy the anonymizer that scrubs `data.href` before releasing the SDK change that sends it.
-Deploy the updated ML-mirror metadata consumer to populate URLs on JSON-LD and full-snapshot Parquet rows.
+The metadata consumer populates URLs on JSON-LD and full-snapshot index rows for both versions.
+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.
Existing events without `data.href` remain readable and do not contribute to URL-based coverage.
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step.test.ts
index 9f5b7db72ff5..c3f8831f70a2 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step.test.ts
@@ -12,7 +12,7 @@ describe('ai-training-optin-filter-step', () => {
})
it('resumes the same session after the team opts in again', async () => {
- const input = { team: team(true), sessionId: '01a0a482-5500-7000-8000-000000000001' }
+ const input = { team: team(true), sessionId: '01a0a4f0-3200-7000-8000-000000000001' }
expect((await step(input)).type).toBe(PipelineResultType.OK)
input.team.aiTrainingOptedIn = false
expect((await step(input)).type).toBe(PipelineResultType.DROP)
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.ts
index e1f019dd6631..bc54a1f549c8 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
@@ -111,8 +111,8 @@ describe('BlockMetadataBatcher', () => {
it('keeps v2 offsets pending until the encrypted eval index upload succeeds', async () => {
await sodium.ready
- const sessionId = '01a0a482-5500-7000-8000-000000000001'
- const timestamp = Date.parse('2026-09-15T10:00:01Z')
+ const sessionId = '01a0a4f0-3200-7000-8000-000000000001'
+ const timestamp = Date.parse('2026-09-15T12:00:01Z')
const key: MlDataKey = {
identity: { teamId: 7, organizationId: 'test-org', sessionId },
plaintext: Buffer.alloc(32, 7),
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.ts
index 6172b44d98c8..45108a4e9790 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
@@ -6,12 +6,11 @@ import {
} from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata'
import { parseBlockUrl, toBlockMetadataRow } from './block-metadata-row'
-import { PSEUDONYM_SESSION, PSEUDONYM_TEAM, pseudonymize } from './pseudonymize'
-
-const SECRET = 'test-secret'
+import { sessionStartTimestampFromUuidV7 } from './session-identifier-format'
+import cases from './session-identifier-format-cases.json'
const block = (over: Partial<SessionBlockMetadata> = {}): SessionBlockMetadata => ({
- ...createNoopBlockMetadata('sess-1', 7),
+ ...createNoopBlockMetadata('01a0a4f0-3200-7000-8000-000000000001', 7),
distinctId: '[email protected]',
blockUrl: 's3://ml-bucket/session_recordings/key-abc?range=bytes=100-250',
startDateTime: DateTime.fromMillis(1_000),
@@ -29,10 +28,8 @@ describe('ml-mirror block-metadata-row', () => {
['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)
+ ])('derives the session partition from %s', (sessionId, expected) => {
+ expect(sessionStartTimestampFromUuidV7(String(sessionId))).toBe(expected ?? null)
})
describe('parseBlockUrl', () => {
@@ -46,16 +43,25 @@ describe('ml-mirror block-metadata-row', () => {
})
describe('toBlockMetadataRow', () => {
- it('pseudonymizes ids and never carries the raw values', () => {
- const row = toBlockMetadataRow(block(), SECRET)!
- expect(row.team_id).toBe(pseudonymize(SECRET, PSEUDONYM_TEAM, '7'))
- expect(row.session_id).toBe(pseudonymize(SECRET, PSEUDONYM_SESSION, 'sess-1'))
- expect(row).not.toHaveProperty('distinct_id')
- expect(row.session_id).not.toBe('sess-1')
+ it.each(cases.cases)('keeps $sessionId in one format across block timestamps', (entry) => {
+ for (const timestamp of [cases.cutoffMs - 1000, cases.cutoffMs + 1000]) {
+ const row = toBlockMetadataRow(
+ block({
+ sessionId: entry.sessionId,
+ startDateTime: DateTime.fromMillis(timestamp),
+ endDateTime: DateTime.fromMillis(timestamp + 1),
+ }),
+ 'test-secret'
+ )!
+ expect(row.team_id).toBe(entry.storedTeamId)
+ expect(row.session_id).toBe(entry.storedSessionId)
+ expect(row).not.toHaveProperty('distinct_id')
+ expect(row.format_version).toBe(entry.rawIdentifiers ? 2 : undefined)
+ }
})
it('maps block fields and the parsed byte range', () => {
- const row = toBlockMetadataRow(block(), SECRET)!
+ const row = toBlockMetadataRow(block(), 'test-secret')!
expect(row).toMatchObject({
block_s3_key: 's3://ml-bucket/session_recordings/key-abc',
block_byte_start: 100,
@@ -72,7 +78,7 @@ describe('ml-mirror block-metadata-row', () => {
['a deletion marker', block({ isDeleted: true })],
['a block with no url', block({ blockUrl: null })],
])('returns null for %s', (_label, b) => {
- expect(toBlockMetadataRow(b, SECRET)).toBeNull()
+ expect(toBlockMetadataRow(b, 'test-secret')).toBeNull()
})
})
})
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.ts
index 14c3379cffed..e467622f8d07 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,8 +1,8 @@
-/** One block's metadata for the ML Parquet datasets. */
import { ReplayIndexEntry } from '~/ingestion/pipelines/sessionreplay/shared/metadata/replay-index-entry'
import { SessionBlockMetadata } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata'
import { PSEUDONYM_SESSION, PSEUDONYM_TEAM, pseudonymize } from './pseudonymize'
+import { sessionStartTimestampFromUuidV7, usesRawSessionIdentifiers } from './session-identifier-format'
export interface MlBlockMetadataRow {
format_version?: 2
@@ -57,7 +57,9 @@ export function toBlockMetadataRow(block: SessionBlockMetadata, secret: string |
}
const { key, start, end } = parseBlockUrl(block.blockUrl)
const sessionStartTimestamp = sessionStartTimestampFromUuidV7(block.sessionId)
+ const rawIdentifiers = usesRawSessionIdentifiers(block.sessionId)
return {
+ ...(rawIdentifiers ? { format_version: 2 as const } : {}),
replay_index_entries: block.replayIndexEntries,
replay_index_truncated: block.replayIndexTruncated,
...(sessionStartTimestamp === null
@@ -65,8 +67,8 @@ export function toBlockMetadataRow(block: SessionBlockMetadata, secret: string |
: {
session_start_ts_ms: sessionStartTimestamp,
}),
- session_id: pseudonymize(secret, PSEUDONYM_SESSION, block.sessionId),
- team_id: pseudonymize(secret, PSEUDONYM_TEAM, String(block.teamId)),
+ session_id: rawIdentifiers ? block.sessionId : pseudonymize(secret, PSEUDONYM_SESSION, block.sessionId),
+ team_id: rawIdentifiers ? String(block.teamId) : pseudonymize(secret, PSEUDONYM_TEAM, String(block.teamId)),
block_url: block.blockUrl,
block_s3_key: key,
block_byte_start: start,
@@ -91,11 +93,3 @@ 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/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
index 6dc735b14793..7c696bf71b89 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
@@ -5,7 +5,7 @@ import { KAFKA_SESSION_REPLAY_IMAGE_SCRUB_DLQ } from '~/common/config/kafka-topi
import { RedisConnectionConfig } from '~/common/utils/db/redis'
export type MlMirrorConfig = {
- AI_RESEARCH_REPLAY_PRIVACY_TABLE: string
+ AI_RESEARCH_REPLAY_KEY_TABLE: string
AI_RESEARCH_REPLAY_KMS_KEY_ARN: string
AI_RESEARCH_REPLAY_AWS_REGION: string
AI_RESEARCH_REPLAY_KMS_REQUESTS_PER_SECOND: number
@@ -218,7 +218,7 @@ export type MlMirrorConfig = {
export function getDefaultMlMirrorConfig(): MlMirrorConfig {
return {
- AI_RESEARCH_REPLAY_PRIVACY_TABLE: '',
+ AI_RESEARCH_REPLAY_KEY_TABLE: '',
AI_RESEARCH_REPLAY_KMS_KEY_ARN: '',
AI_RESEARCH_REPLAY_AWS_REGION: 'us-east-1',
AI_RESEARCH_REPLAY_KMS_REQUESTS_PER_SECOND: 100,
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.ts
index 6680de6c68a6..1243fdd1c023 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
@@ -1,9 +1,11 @@
import { PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'
import { ParquetReader } from '@dsnp/parquetjs'
+import sodium from 'libsodium-wrappers'
import { DateTime } from 'luxon'
import { Message } from 'node-rdkafka'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import { parseJSON } from '~/common/utils/json-parse'
import {
SessionBlockMetadata,
createNoopBlockMetadata,
@@ -13,17 +15,20 @@ import { MlBlockMetadataOutput } from '~/ingestion/pipelines/sessionreplay/share
import { BlockMetadataBatcher, OffsetStore } from './block-metadata-batcher'
import { BlockMetadataParquetStore } from './block-metadata-parquet-store'
import { MlBlockMetadataSink } from './ml-block-metadata-sink'
+import { MlDataKey, decryptEnvelope } from './privacy/crypto'
+import { MlKeyReader } from './privacy/reader'
+import { sessionKeyId, tableKeyString } from './privacy/schema'
+import { MlKafkaEncryption } from './privacy/transport'
import { PSEUDONYM_SESSION, PSEUDONYM_TEAM, pseudonymize } from './pseudonymize'
-const SECRET = 'roundtrip-secret'
-const SESSION_A = '018bcfe5-6800-7000-8000-000000000001'
+const SESSION_A = '01a0a4f0-3200-7000-8000-000000000001'
const block = (sessionId: string, teamId: number, distinctId: string): SessionBlockMetadata => ({
...createNoopBlockMetadata(sessionId, teamId),
distinctId,
blockUrl: `s3://ml-bucket/key-${sessionId}?range=bytes=10-42`,
- startDateTime: DateTime.fromMillis(1_700_000_000_000),
- endDateTime: DateTime.fromMillis(1_700_000_005_000),
+ startDateTime: DateTime.fromMillis(1789473600000),
+ endDateTime: DateTime.fromMillis(1789473605000),
eventCount: 5,
messageCount: 2,
clickCount: 1,
@@ -33,27 +38,27 @@ const block = (sessionId: string, teamId: number, distinctId: string): SessionBl
{
kind: 'page',
windowId: 'w1',
- eventTimestamp: 1_700_000_000_001.5,
+ eventTimestamp: 1789473600001.5,
eventIndex: 0,
url: 'https://example.com/[redacted]',
},
- { kind: 'full_snapshot', windowId: 'w1', eventTimestamp: 1_700_000_000_001.5, eventIndex: 1 },
+ { kind: 'full_snapshot', windowId: 'w1', eventTimestamp: 1789473600001.5, eventIndex: 1 },
{
kind: 'json_ld',
windowId: 'w1',
- eventTimestamp: 1_700_000_000_001.5,
+ eventTimestamp: 1789473600001.5,
eventIndex: 2,
- fullSnapshotTimestamp: 1_700_000_000_001.5,
+ fullSnapshotTimestamp: 1789473600001.5,
rootTypes: ['Product'],
},
{
kind: 'page',
windowId: 'w1',
- eventTimestamp: 1_700_000_000_001.5,
+ eventTimestamp: 1789473600001.5,
eventIndex: 2,
url: 'https://example.com/[redacted]',
},
- { kind: 'json_ld', windowId: 'w1', eventTimestamp: 1_700_000_000_001.5, eventIndex: 3, rootTypes: ['Article'] },
+ { kind: 'json_ld', windowId: 'w1', eventTimestamp: 1789473600001.5, eventIndex: 3, rootTypes: ['Article'] },
],
})
@@ -72,9 +77,18 @@ 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('pseudonymizes on the way out and recovers the same rows from the written Parquet', async () => {
+ it('encrypts v2 metadata and replay indexes while preserving 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
// --- Mirror (producer) side: block metadata → Kafka message bytes ---
- const produced: { key?: unknown; value: Buffer | null }[] = []
+ const produced: { key?: unknown; value: Buffer | null; headers?: Record<string, string> }[] = []
const outputs = {
queueMessages: jest.fn((_output, messages) => {
produced.push(...messages)
@@ -82,9 +96,9 @@ describe('ML metadata producer → sink round-trip', () => {
}),
} as unknown as IngestionOutputs<MlBlockMetadataOutput>
- await new MlBlockMetadataSink(outputs, SECRET).storeSessionBlocks([
+ await new MlBlockMetadataSink(outputs, 'test-secret', reader).storeSessionBlocks([
block(SESSION_A, 1, 'person-1'),
- block('sess-B', 2, 'person-2'),
+ block('01a0a4f0-31ff-7000-8000-000000000001', 2, 'person-2'),
])
expect(produced).toHaveLength(2)
@@ -98,45 +112,75 @@ describe('ML metadata producer → sink round-trip', () => {
} as unknown as S3Client
const store = new BlockMetadataParquetStore(s3, 'ml-bucket', 'block-metadata', 'pod-1')
const offsetStore: OffsetStore = { offsetsStore: jest.fn() }
- const batcher = new BlockMetadataBatcher(store, offsetStore, { flushIntervalMs: 60_000, maxRows: 1_000 }, 0)
+ const batcher = new BlockMetadataBatcher(
+ store,
+ offsetStore,
+ { flushIntervalMs: 60_000, maxRows: 1_000 },
+ 0,
+ new MlKafkaEncryption(reader)
+ )
const messages = produced.map(
- (m, i) => ({ topic: 'ml_block_metadata', partition: 0, offset: i, value: m.value }) as Message
+ (m, i) =>
+ ({
+ topic: 'ml_block_metadata',
+ partition: 0,
+ offset: i,
+ value: m.value,
+ headers: Object.entries(m.headers ?? {}).map(([name, value]) => ({ [name]: Buffer.from(value) })),
+ }) as Message
)
await batcher.handleBatch(messages, 0)
await batcher.flush(1) // force the window out
- expect(puts).toHaveLength(4)
- 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(2)
- expect(labels[1].url ?? null).toBeNull()
- expect(labels[0]).toMatchObject({
- session_id: pseudonymize(SECRET, PSEUDONYM_SESSION, SESSION_A),
- window_id: 'w1',
- event_index: 2,
- full_snapshot_ts_ms: 1_700_000_000_001.5,
- root_types: ['Product'],
- url: 'https://example.com/[redacted]',
+ const rows = await readRows(puts.find((put) => put.Key!.startsWith('block-metadata/v2/2026-09/'))!.Body)
+ expect(rows).toHaveLength(1)
+ expect(rows[0].distinct_id).toBeUndefined()
+ expect(rows[0].urls).toBeUndefined()
+ const decrypted = parseJSON(decryptEnvelope(key, parseJSON(rows[0].payload.toString()), 'metadata').toString())
+ expect(decrypted.replay_index_entries).toHaveLength(5)
+ const evalRows = await readRows(
+ puts.find((put) => put.Key!.startsWith('block-metadata-replay-index/v2/2026-09/kind=json_ld/'))!.Body
+ )
+ 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()
+ )
+ expect(labels).toEqual([
+ expect.objectContaining({
+ team_id: '1',
+ session_id: SESSION_A,
+ kind: 'json_ld',
+ root_types: ['Product'],
+ url: 'https://example.com/[redacted]',
+ }),
+ expect.objectContaining({
+ team_id: '1',
+ session_id: SESSION_A,
+ kind: 'json_ld',
+ root_types: ['Article'],
+ url: null,
+ }),
+ ])
+ 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')
+ expect(legacyRows[0]).toMatchObject({
+ team_id: pseudonymize('test-secret', PSEUDONYM_TEAM, '2'),
+ session_id: pseudonymize('test-secret', PSEUDONYM_SESSION, '01a0a4f0-31ff-7000-8000-000000000001'),
})
- const snapshots = await readRows(puts.find((put) => put.Key!.includes('kind=full_snapshot'))!.Body)
- expect(snapshots[0]).toMatchObject({ event_index: 1, url: 'https://example.com/[redacted]' })
- const pages = await readRows(puts.find((put) => put.Key!.includes('kind=page'))!.Body)
- expect(pages).toHaveLength(1)
- expect(pages[0].event_index).toBe(0)
- const rows = await readRows(puts.find((put) => put.Key!.startsWith('block-metadata/dt='))!.Body)
- expect(rows).toHaveLength(2)
+ const legacyLabels = await readRows(puts.find((put) => put.Key!.includes('v1/kind=json_ld'))!.Body)
+ expect(legacyLabels).toHaveLength(2)
+ expect(legacyLabels[0].session_id).toBe(legacyRows[0].session_id)
- const bySession = new Map(rows.map((r) => [r.session_id, r]))
- const a = bySession.get(pseudonymize(SECRET, PSEUDONYM_SESSION, SESSION_A))!
+ const bySession = new Map([[decrypted.session_id, decrypted]])
+ const a = bySession.get(SESSION_A)!
expect(a).toBeDefined()
- expect(a.team_id).toBe(pseudonymize(SECRET, PSEUDONYM_TEAM, '1'))
+ expect(a.team_id).toBe('1')
expect(a).not.toHaveProperty('distinct_id')
- // Raw ids never survive the trip (BigInt-safe stringify, since INT64 fields read back as bigint).
- 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')
+ expect(a.session_id).toBe(SESSION_A)
// Real block fields round-trip through JSON → Parquet → read.
expect(Number(a.block_byte_start)).toBe(10)
expect(Number(a.block_byte_end)).toBe(42)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
index 74dd8cb1e0f6..f60b2d7210d7 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
@@ -92,9 +92,9 @@ export class MlMirrorMetrics {
help: 'Bytes of collected images delivered to the scrub topic (acked)',
})
- private static readonly mlImagePseudoTeamInvalid = new Counter({
- name: 'recording_blob_ingestion_v2_ml_image_pseudo_team_invalid',
- help: 'Messages whose derived team pseudonym failed the consumer ref-shape check; collection disabled for them (inline blur instead)',
+ private static readonly mlImageTeamIdInvalid = new Counter({
+ name: 'recording_blob_ingestion_v2_ml_image_team_id_invalid',
+ help: 'Messages whose team ID failed the consumer ref-shape check; collection disabled for them (inline blur instead)',
})
private static readonly mlUrlBytes = new Histogram({
@@ -188,8 +188,8 @@ export class MlMirrorMetrics {
this.mlImageBytesProduced.inc(bytes)
}
- public static incrementMlImagePseudoTeamInvalid(): void {
- this.mlImagePseudoTeamInvalid.inc()
+ public static incrementMlImageTeamIdInvalid(): void {
+ this.mlImageTeamIdInvalid.inc()
}
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.test.ts
index fa83354185e6..99ce8f6098a7 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.test.ts
@@ -1,7 +1,6 @@
import { DateTime } from 'luxon'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
-import { parseJSON } from '~/common/utils/json-parse'
import {
SessionBlockMetadata,
createNoopBlockMetadata,
@@ -9,9 +8,6 @@ import {
import { ML_BLOCK_METADATA_OUTPUT, MlBlockMetadataOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
import { MlBlockMetadataSink } from './ml-block-metadata-sink'
-import { PSEUDONYM_SESSION, pseudonymize } from './pseudonymize'
-
-const SECRET = 'test-secret'
const block = (sessionId: string, teamId: number, over: Partial<SessionBlockMetadata> = {}): SessionBlockMetadata => ({
...createNoopBlockMetadata(sessionId, teamId),
@@ -32,27 +28,19 @@ describe('MlBlockMetadataSink', () => {
outputs = { queueMessages: jest.fn().mockResolvedValue(undefined) } as unknown as jest.Mocked<
IngestionOutputs<MlBlockMetadataOutput>
>
- sink = new MlBlockMetadataSink(outputs, SECRET)
+ sink = new MlBlockMetadataSink(outputs, 'test-secret')
})
- it('produces pseudonymized rows to the ML topic, keyed by the session pseudonym', async () => {
- await sink.storeSessionBlocks([block('s1', 7)])
-
- expect(outputs.queueMessages).toHaveBeenCalledTimes(1)
- const [output, messages] = outputs.queueMessages.mock.calls[0]
- expect(output).toBe(ML_BLOCK_METADATA_OUTPUT)
- expect(messages[0].key).toBe(pseudonymize(SECRET, PSEUDONYM_SESSION, 's1'))
-
- const row = parseJSON((messages[0].value as Buffer).toString())
- expect(row.session_id).toBe(pseudonymize(SECRET, PSEUDONYM_SESSION, 's1'))
- expect(row.session_id).not.toBe('s1')
- expect(row).not.toHaveProperty('distinct_id')
- expect(row.block_byte_end).toBe(9)
+ it('rejects v2 metadata when encryption is not configured', async () => {
+ await expect(sink.storeSessionBlocks([block('01a0a4f0-3200-7000-8000-000000000001', 7)])).rejects.toThrow(
+ 'requires privacy configuration'
+ )
+ expect(outputs.queueMessages).not.toHaveBeenCalled()
})
it('skips deletion and url-less markers', async () => {
await sink.storeSessionBlocks([
- block('s1', 1),
+ block('legacy-session', 1),
block('s2', 1, { isDeleted: true }),
block('s3', 1, { blockUrl: null }),
])
@@ -61,7 +49,7 @@ describe('MlBlockMetadataSink', () => {
})
it('still calls queueMessages for an all-skipped batch', async () => {
- await sink.storeSessionBlocks([block('s1', 1, { isDeleted: true })])
+ await sink.storeSessionBlocks([block('01a0a4f0-3200-7000-8000-000000000001', 1, { isDeleted: true })])
expect(outputs.queueMessages).toHaveBeenCalledWith(ML_BLOCK_METADATA_OUTPUT, [])
})
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.ts
index 83a21dbba3fb..d5dac7ec28d8 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.ts
@@ -1,31 +1,39 @@
-/** Produces anonymized, pseudonymized block metadata to the ML Kafka topic for the Parquet sink to consume. */
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
-import {
- KafkaMetadataSink,
- MetadataRecord,
-} from '~/ingestion/pipelines/sessionreplay/shared/metadata/kafka-metadata-sink'
+import { SessionMetadataSink } from '~/ingestion/pipelines/sessionreplay/shared/metadata/kafka-metadata-sink'
import { SessionBlockMetadata } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata'
import { ML_BLOCK_METADATA_OUTPUT, MlBlockMetadataOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
import { toBlockMetadataRow } from './block-metadata-row'
+import { MlKeyReader } from './privacy/reader'
+import { sessionKeyId, tableKeyString } from './privacy/schema'
+import { encryptedKafkaValue } from './privacy/transport'
+import { usesRawSessionIdentifiers } from './session-identifier-format'
-export class MlBlockMetadataSink extends KafkaMetadataSink<MlBlockMetadataOutput> {
+export class MlBlockMetadataSink implements SessionMetadataSink {
constructor(
- outputs: IngestionOutputs<MlBlockMetadataOutput>,
- private readonly pseudonymSecret: string | Buffer
- ) {
- super(outputs, ML_BLOCK_METADATA_OUTPUT)
- }
+ private readonly outputs: IngestionOutputs<MlBlockMetadataOutput>,
+ private readonly pseudonymSecret: string | Buffer,
+ private readonly privacy?: MlKeyReader
+ ) {}
- protected toRecords(blocks: SessionBlockMetadata[]): MetadataRecord[] {
- const records: MetadataRecord[] = []
- for (const block of blocks) {
+ public async storeSessionBlocks(blocks: SessionBlockMetadata[]): Promise<void> {
+ const currentBlocks = blocks.filter(
+ (block) => block.blockUrl && !block.isDeleted && usesRawSessionIdentifiers(block.sessionId)
+ )
+ if (currentBlocks.length && !this.privacy) {
+ throw new Error('ML v2 metadata requires privacy configuration')
+ }
+ const keys =
+ (await this.privacy?.read(currentBlocks.map((block) => sessionKeyId(block.teamId, block.sessionId)))) ??
+ new Map()
+ const messages = blocks.flatMap((block) => {
const row = toBlockMetadataRow(block, this.pseudonymSecret)
- if (row) {
- // Keyed by the pseudonymous session id so a recording's blocks land on one partition.
- records.push({ key: row.session_id, value: row })
+ const key = keys.get(tableKeyString(sessionKeyId(block.teamId, block.sessionId)))
+ if (!row || (usesRawSessionIdentifiers(block.sessionId) && !key)) {
+ return []
}
- }
- return records
+ return [{ key: row.session_id, ...encryptedKafkaValue(key, 'metadata', Buffer.from(JSON.stringify(row))) }]
+ })
+ await this.outputs.queueMessages(ML_BLOCK_METADATA_OUTPUT, messages)
}
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-anonymize-concurrency.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-anonymize-concurrency.test.ts
index c5c3c169997b..2af239b98fb9 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-anonymize-concurrency.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-anonymize-concurrency.test.ts
@@ -37,6 +37,8 @@ const mockCreateApplyEventRestrictionsStep = createApplyEventRestrictionsStep as
const mockCreateParseAndAnonymizeMessageStep = createParseAndAnonymizeMessageStep as jest.Mock
describe('ml-mirror anonymize concurrency', () => {
+ const SESSION_A = '01a0a4f0-3200-7000-8000-000000000001'
+ const SESSION_B = '01a0a4f0-3200-7000-8000-000000000002'
const now = DateTime.now()
const retentionService = {
@@ -187,8 +189,8 @@ describe('ml-mirror anonymize concurrency', () => {
it('scrubs messages concurrently, including messages of the same session', async () => {
let releaseFirstScrub!: () => void
let releaseSecondScrub!: () => void
- scrubGates.set('sess-a:1', new Promise<void>((resolve) => (releaseFirstScrub = resolve)))
- scrubGates.set('sess-a:2', new Promise<void>((resolve) => (releaseSecondScrub = resolve)))
+ scrubGates.set(`${SESSION_A}:1`, new Promise<void>((resolve) => (releaseFirstScrub = resolve)))
+ scrubGates.set(`${SESSION_A}:2`, new Promise<void>((resolve) => (releaseSecondScrub = resolve)))
const recorder = {
record: recordMock,
@@ -196,7 +198,7 @@ describe('ml-mirror anonymize concurrency', () => {
} as unknown as SessionBatchRecorder
const run = runSessionReplayPipeline(
buildPipeline(),
- [message('sess-a', 1), message('sess-a', 2), message('sess-b', 3)],
+ [message(SESSION_A, 1), message(SESSION_A, 2), message(SESSION_B, 3)],
recorder,
promiseScheduler
)
@@ -205,7 +207,7 @@ describe('ml-mirror anonymize concurrency', () => {
// Both of sess-a's scrubs are in flight at once — sequential processing never starts
// the second scrub while the first is gated, and per-session grouping never starts a
// session's second message while its first is gated.
- await until(() => scrubStarts.has('sess-a:1') && scrubStarts.has('sess-a:2'))
+ await until(() => scrubStarts.has(`${SESSION_A}:1`) && scrubStarts.has(`${SESSION_A}:2`))
} finally {
releaseFirstScrub()
releaseSecondScrub()
@@ -213,7 +215,7 @@ describe('ml-mirror anonymize concurrency', () => {
await run
// No ordering guarantees, so only membership is asserted.
- expect(recordedOffsets('sess-a').sort()).toEqual([1, 2])
- expect(recordedOffsets('sess-b')).toEqual([3])
+ expect(recordedOffsets(SESSION_A).sort()).toEqual([1, 2])
+ expect(recordedOffsets(SESSION_B)).toEqual([3])
})
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts
index c74821ae0585..44bfeaa48ac3 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts
@@ -58,6 +58,9 @@ function createMockTopHog(): TopHogRegistry {
}
describe('ml-mirror-pipeline', () => {
+ const V2_SESSION_ID = '01a0a4f0-3200-7000-8000-000000000001'
+ const V2_SESSION_ID_2 = '01a0a4f0-3200-7000-8000-000000000002'
+ const V2_SESSION_ID_3 = '01a0a4f0-3200-7000-8000-000000000003'
let recordMock: jest.Mock
let mockBatchRecorder: jest.Mocked<SessionBatchRecorder>
let mockTeamService: TeamService
@@ -266,7 +269,7 @@ describe('ml-mirror-pipeline', () => {
getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),
} as unknown as TeamService
- await runSessionReplayPipeline(buildPipeline(), [message('sess-1')], mockBatchRecorder, promiseScheduler)
+ await runSessionReplayPipeline(buildPipeline(), [message(V2_SESSION_ID)], mockBatchRecorder, promiseScheduler)
expect(recordMock).toHaveBeenCalledTimes(1)
const [windowId, event] = recordedEvents()[0]
@@ -297,11 +300,28 @@ describe('ml-mirror-pipeline', () => {
getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),
} as unknown as TeamService
- await runSessionReplayPipeline(buildPipeline(), [message('sess-2')], mockBatchRecorder, promiseScheduler)
+ await runSessionReplayPipeline(buildPipeline(), [message(V2_SESSION_ID_2)], mockBatchRecorder, promiseScheduler)
expect(recordMock).not.toHaveBeenCalled()
})
+ it('drops sessions whose ID is not UUIDv7 before session resolution', async () => {
+ mockTeamService = {
+ getTeamByToken: jest.fn().mockResolvedValue(team(true)),
+ getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),
+ } as unknown as TeamService
+
+ await runSessionReplayPipeline(
+ buildPipeline(),
+ [message('legacy-session-id')],
+ mockBatchRecorder,
+ promiseScheduler
+ )
+
+ expect(retentionService.resolveSessionRetentions).not.toHaveBeenCalled()
+ expect(recordMock).not.toHaveBeenCalled()
+ })
+
itAddon('scrubs a FullSnapshot (text, url, free-text data-*) end-to-end before recording', async () => {
mockTeamService = {
getTeamByToken: jest.fn().mockResolvedValue(team(true)),
@@ -310,7 +330,7 @@ describe('ml-mirror-pipeline', () => {
await runSessionReplayPipeline(
buildPipeline(),
- [fullSnapshotMessage('sess-3')],
+ [fullSnapshotMessage(V2_SESSION_ID_3)],
mockBatchRecorder,
promiseScheduler
)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts
index 408770d54446..89e81b630a9a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts
@@ -1,12 +1,12 @@
/** The primary session replay pipeline plus an AI-training opt-in filter and an anonymize step. */
import { OverflowOutput } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
-import { createApplyEventRestrictionsStep, createParseHeadersStep } from '~/ingestion/common/steps/event-preprocessing'
import { newBatchingPipeline } from '~/ingestion/framework/builders'
-import { createTopHogWrapper, sum, timer } from '~/ingestion/framework/extensions/tophog'
+import { createTopHogWrapper, timer } from '~/ingestion/framework/extensions/tophog'
import { aggregateKafkaDebugContexts } from '~/ingestion/framework/helpers'
import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'
-import { ok } from '~/ingestion/framework/results'
+import { drop, ok } from '~/ingestion/framework/results'
+import { ProcessingStep } from '~/ingestion/framework/steps'
import {
SessionReplayPipeline,
SessionReplayPipelineConfig,
@@ -17,21 +17,24 @@ import { createAiTrainingOptInFilterStep } from '~/ingestion/pipelines/sessionre
import type { CrawlHistoryStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history'
import { createProduceCollectedImagesStep } from '~/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step'
import { createProduceCollectedUrlsStep } from '~/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step'
-import { MessageContext } from '~/ingestion/pipelines/sessionreplay/pipeline-types'
+import { MessageContext, SessionReplayHeaders } from '~/ingestion/pipelines/sessionreplay/pipeline-types'
import { createRecordSessionEventStep } from '~/ingestion/pipelines/sessionreplay/record-session-event-step'
-import { createMarkSeenStep } from '~/ingestion/pipelines/sessionreplay/session-batch-mark-seen-step'
-import { createResolveRetentionStep } from '~/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step'
-import { createTrackAndGateStep } from '~/ingestion/pipelines/sessionreplay/session-batch-track-and-gate-step'
-import { createResolveKeyStep } from '~/ingestion/pipelines/sessionreplay/session-resolve-key-step'
+import { RecordSessionEventStepInput } from '~/ingestion/pipelines/sessionreplay/record-session-event-step'
+import {
+ addSessionReplayPreprocessing,
+ addSessionReplaySessionResolution,
+ withSessionReplayRecordingMetrics,
+} from '~/ingestion/pipelines/sessionreplay/session-replay-pipeline-stages'
import { MlImageFetchOutput, MlImageScrubOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
-import { createTeamFilterStep } from '~/ingestion/pipelines/sessionreplay/team-filter-step'
-import { createValidateSessionReplayHeadersStep } from '~/ingestion/pipelines/sessionreplay/validate-headers-step'
import { createParseAndAnonymizeMessageStep } from './parse-and-anonymize-step'
+import { MlPrivacyBatchController } from './privacy/batch-controller'
+import { isSupportedMlSessionId } from './session-identifier-format'
export interface MlMirrorPipelineOptions {
/** Cap on sessions scrubbed concurrently; each in-flight scrub occupies a libuv threadpool thread. */
anonymizeMaxConcurrency: number
+ privacy?: MlPrivacyBatchController
}
/** Enables the image-collection lane: inlined images become refs, originals go to the scrub topic. */
@@ -59,12 +62,20 @@ export interface MlMirrorUrlFetchProducer {
* make that measurement impossible to take on its own.
*/
export interface MlMirrorCollection {
- /** The ML pseudonym HMAC key, also used by the block-metadata sink. */
+ /** The root key for image content and URL HMAC keys. */
pseudonymSecret: string | Buffer
collectImages: boolean
collectUrls: boolean
}
+function createMlSessionIdFilterStep<T extends { headers: SessionReplayHeaders }>(): ProcessingStep<T, T> {
+ return function filterMlSessionId(input) {
+ return Promise.resolve(
+ isSupportedMlSessionId(input.headers.session_id) ? ok(input) : drop('session_id_not_uuid_v7')
+ )
+ }
+}
+
export function createMlMirrorReplayPipeline(
config: SessionReplayPipelineConfig,
mlOptions: MlMirrorPipelineOptions,
@@ -72,23 +83,15 @@ export function createMlMirrorReplayPipeline(
collection?: MlMirrorCollection,
urlFetch?: MlMirrorUrlFetchProducer
): SessionReplayPipeline {
- const {
- outputs,
- eventIngestionRestrictionManager,
- overflowMode,
- promiseScheduler,
- teamService,
- retentionService,
- sessionTracker,
- sessionFilter,
- keyStore,
- sessionKeyResolutionMaxConcurrency,
- topHog,
- isDebugLoggingEnabled,
- } = config
+ const { outputs, promiseScheduler, topHog, isDebugLoggingEnabled } = config
const pipelineConfig: PipelineConfig<OverflowOutput> = { outputs, promiseScheduler }
const topHogWrapper = createTopHogWrapper(topHog)
+ function deferPublication<T extends RecordSessionEventStepInput & { headers: { session_id: string } }>(
+ step: ProcessingStep<T, T>
+ ): ProcessingStep<T, T> {
+ return mlOptions.privacy ? (input) => mlOptions.privacy!.defer(input, step) : step
+ }
return newBatchingPipeline<
SessionReplayPipelineInput,
@@ -100,142 +103,121 @@ export function createMlMirrorReplayPipeline(
>(
(beforeBatch) =>
beforeBatch.pipe(function passThroughBeforeBatch(input) {
+ mlOptions.privacy?.reset()
return Promise.resolve(ok(input))
}),
(batch) =>
batch
.messageAware((b) =>
- b
- .sequentially((b) =>
- b
- .pipe(createParseHeadersStep())
- .pipe(
- createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {
- overflowMode,
- preservePartitionLocality: true,
- // Mirrors replay, which never reads or writes persons.
- pipelineWritesPersons: false,
- })
- )
- .pipe(createValidateSessionReplayHeadersStep())
- .pipe(createTeamFilterStep(teamService))
- // Mirror only data from orgs that opted into AI training.
- .pipe(createAiTrainingOptInFilterStep())
- )
- // Resolve retention up front (before parse), keyed on the (validated) session_id
- // header; drop unresolvable sessions.
- .gather()
- .pipeChunk(createResolveRetentionStep(retentionService), {
- retry: { tries: 3, sleepMs: 100 },
- })
- // Track sessions and rate-limit new ones for the whole batch, tagging each with
- // isNewSession and a gate verdict; blocked sessions are carried (not dropped) to the
- // mark-seen step, all in this step's own retry scope.
- .pipeChunk(createTrackAndGateStep(sessionTracker, sessionFilter), {
- retry: { tries: 3, sleepMs: 100 },
- })
- // Resolve each session's encryption key once per session (grouped), concurrently across
- // sessions with a bounded fan-out and per-session retry. Deleted sessions drop here.
- .concurrentlyPerGroup(
- (element) => `${element.team.teamId}:${element.headers.session_id}`,
- (group) =>
- group.sequentially((b) =>
- b.pipe(createResolveKeyStep(keyStore), {
- retry: { name: 'resolve_session_key', tries: 3, sleepMs: 100 },
- })
- ),
- { maxConcurrency: sessionKeyResolutionMaxConcurrency }
- )
- // Re-collect the per-session groups into one batch — both to mark the whole batch seen
- // in a single Redis write and as the barrier that guarantees every key is resolved first.
- .gather()
- // Mark the surviving new sessions seen, now that every key is durably resolved.
- .pipeChunk(createMarkSeenStep(sessionTracker))
- .filterMap(
- (element) => ({
- result: element.result,
- context: {
- ...element.context,
- team: { id: element.result.value.team.teamId },
- },
+ addSessionReplaySessionResolution(
+ b
+ .sequentially((b) =>
+ addSessionReplayPreprocessing(b, config)
+ .pipe(createMlSessionIdFilterStep())
+ // Mirror only data from orgs that opted into AI training.
+ .pipe(createAiTrainingOptInFilterStep())
+ )
+ .gather()
+ .pipeChunk(async function readMlPrivacyBatch(values) {
+ if (mlOptions.privacy) {
+ await mlOptions.privacy.prepare(
+ values.map((value) => {
+ if (!value.team.organizationId) {
+ throw new Error('ML privacy requires organization ownership')
+ }
+ return {
+ teamId: value.team.teamId,
+ organizationId: value.team.organizationId,
+ sessionId: value.headers.session_id,
+ }
+ })
+ )
+ }
+ return values.map((value) => ok(value))
}),
- (b) =>
- b
- .teamAware((b) =>
- b
- // Downstream consumers don't require event order within a
- // session's block, so scrubbing is free to complete out of order.
- .concurrently(
- (b) => {
- // The native Rust addon fuses parse+anonymize in one step.
- const parsed = b.pipe(
- topHogWrapper(
- createParseAndAnonymizeMessageStep(
- collection?.collectImages || collection?.collectUrls
- ? collection
- : undefined
- ),
- [
- timer('parse_time_ms_by_session_id', (input) => ({
- token: input.headers.token ?? 'unknown',
- session_id: input.headers.session_id ?? 'unknown',
- })),
- ]
- )
+ config
+ ).filterMap(
+ (element) => ({
+ result: element.result,
+ context: {
+ ...element.context,
+ team: { id: element.result.value.team.teamId },
+ },
+ }),
+ (b) =>
+ b
+ .teamAware((b) =>
+ b
+ // Downstream consumers don't require event order within a
+ // session's block, so scrubbing is free to complete out of order.
+ .concurrently(
+ (b) => {
+ // The native Rust addon fuses parse+anonymize in one step.
+ const parsed = b.pipe(
+ topHogWrapper(
+ createParseAndAnonymizeMessageStep(
+ collection?.collectImages || collection?.collectUrls
+ ? collection
+ : undefined,
+ mlOptions.privacy
+ ),
+ [
+ timer('parse_time_ms_by_session_id', (input) => ({
+ token: input.headers.token ?? 'unknown',
+ session_id: input.headers.session_id ?? 'unknown',
+ })),
+ ]
)
- const withImagesProduced = imageScrub
- ? parsed.pipe(
+ )
+ const withImagesProduced = imageScrub
+ ? parsed.pipe(
+ deferPublication(
createProduceCollectedImagesStep(
imageScrub.outputs,
- imageScrub.producedRefCacheMax
+ imageScrub.producedRefCacheMax,
+ mlOptions.privacy
)
)
- : parsed
- const withUrlsProduced = urlFetch
- ? withImagesProduced.pipe(
+ )
+ : parsed
+ const withUrlsProduced = urlFetch
+ ? withImagesProduced.pipe(
+ deferPublication(
createProduceCollectedUrlsStep(urlFetch.outputs, topHog, {
producedRefCacheMax: urlFetch.producedRefCacheMax,
producedRefCacheWindowMs:
urlFetch.producedRefCacheWindowMs,
crawlHistory: urlFetch.crawlHistory,
+ privacy: mlOptions.privacy,
})
)
- : withImagesProduced
- return withUrlsProduced.pipe(
- topHogWrapper(
+ )
+ : withImagesProduced
+ return withUrlsProduced.pipe(
+ withSessionReplayRecordingMetrics(
+ topHog,
+ deferPublication(
createRecordSessionEventStep({
isDebugLoggingEnabled,
- }),
- [
- sum(
- 'message_size_by_session_id',
- (input) => ({
- token: input.parsedMessage.token ?? 'unknown',
- session_id: input.parsedMessage.session_id,
- }),
- (input) => input.parsedMessage.metadata.rawSize
- ),
- timer('consume_time_ms_by_session_id', (input) => ({
- token: input.parsedMessage.token ?? 'unknown',
- session_id: input.parsedMessage.session_id,
- })),
- ]
+ })
)
)
- },
- { maxConcurrency: mlOptions.anonymizeMaxConcurrency }
- )
- .gather()
- )
- .handleIngestionWarnings(outputs)
- )
+ )
+ },
+ { maxConcurrency: mlOptions.anonymizeMaxConcurrency }
+ )
+ .gather()
+ )
+ .handleIngestionWarnings(outputs)
+ )
)
.handleResults(pipelineConfig)
.handleSideEffects(promiseScheduler, { await: false })
.gather(),
(afterBatch) =>
- afterBatch.pipe(function passThroughAfterBatch(input) {
- return Promise.resolve(ok(input))
+ afterBatch.pipe(async function passThroughAfterBatch(input) {
+ await mlOptions.privacy?.commit()
+ return ok(input)
}),
// One batch in flight at a time (also the framework default): each feed tags the manager's
// current recorder, so a concurrent batch could span a flush and record into a stale recorder.
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.ts
index 8da0c160425c..e95251e539c3 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
@@ -51,10 +51,10 @@ jest.mock('@posthog/replay-anonymizer', () => ({
anonymizeKafkaPayload: (
payload: Buffer,
contentEncoding?: string | null,
- pseudoTeam?: string | null,
+ teamId?: string | null,
contentKey?: string | null,
urlKey?: string | null
- ) => mockAnonymizeKafkaPayload(payload, contentEncoding, pseudoTeam, contentKey, urlKey),
+ ) => mockAnonymizeKafkaPayload(payload, contentEncoding, teamId, contentKey, urlKey),
}))
describe('createParseAndAnonymizeMessageStep', () => {
@@ -219,7 +219,7 @@ describe('createParseAndAnonymizeMessageStep with image collection', () => {
collectImages: true,
collectUrls: false,
})
- const pseudoTeam = pseudonymize(secret, PSEUDONYM_TEAM, '1')
+ const teamId = pseudonymize(secret, PSEUDONYM_TEAM, '1')
const contentKey = pseudonymize(secret, PSEUDONYM_IMAGE_CONTENT_KEY, '1')
const now = Date.now()
@@ -248,6 +248,7 @@ describe('createParseAndAnonymizeMessageStep with image collection', () => {
function addonSuccessWithImages(
images: Buffer | null,
imageEntries?: { hash: string; offset: number; len: number }[],
+ sessionId: string = 'session-1',
imageSources?: { source: 'css' | 'html'; property: string; kind: 'inline' | 'url'; count: number }[]
): void {
mockAnonymizeKafkaPayload.mockResolvedValue({
@@ -258,7 +259,7 @@ describe('createParseAndAnonymizeMessageStep with image collection', () => {
images,
meta: JSON.stringify({
distinctId: 'user-1',
- sessionId: 'session-1',
+ sessionId,
windowId: 'window-1',
snapshotSource: 'web',
snapshotLibrary: 'posthog-js',
@@ -279,15 +280,26 @@ describe('createParseAndAnonymizeMessageStep with image collection', () => {
mockAnonymizeKafkaPayload.mockReset()
})
- it('passes the cached per-team pseudonym and content key to the addon', async () => {
- addonSuccessWithImages(null)
- await step({ message: kafkaMessage(), headers, team })
- await step({ message: kafkaMessage(), headers, team })
- expect(mockAnonymizeKafkaPayload).toHaveBeenCalledTimes(2)
- for (const call of mockAnonymizeKafkaPayload.mock.calls) {
- expect(call[2]).toBe(pseudoTeam)
- expect(call[3]).toBe(contentKey)
- expect(call[3]).not.toBe(call[2])
+ it('keeps old and new image refs separate for the same team across repeated messages', async () => {
+ for (const [sessionId, expectedTeamId] of [
+ ['01a0a4f0-31ff-7000-8000-000000000001', teamId],
+ ['01a0a4f0-3200-7000-8000-000000000001', '1'],
+ ['01a0a4f0-31ff-7000-8000-000000000001', teamId],
+ ['01a0a4f0-3200-7000-8000-000000000001', '1'],
+ ]) {
+ addonSuccessWithImages(Buffer.from('a'), [{ hash: 'hashA', offset: 0, len: 1 }], sessionId)
+ const result = await step({ message: kafkaMessage(), headers: { ...headers, session_id: sessionId }, team })
+ expect(mockAnonymizeKafkaPayload).toHaveBeenLastCalledWith(
+ expect.anything(),
+ null,
+ expectedTeamId,
+ contentKey,
+ undefined
+ )
+ expect(result).toMatchObject({
+ type: PipelineResultType.OK,
+ value: { collectedImages: [{ ref: imageRef(expectedTeamId, 'hashA'), bytes: Buffer.from('a') }] },
+ })
}
})
@@ -301,8 +313,8 @@ describe('createParseAndAnonymizeMessageStep with image collection', () => {
expect(result.type).toBe(PipelineResultType.OK)
const images = (result as any).value.collectedImages
expect(images).toEqual([
- { ref: imageRef(pseudoTeam, 'hashA'), bytes: Buffer.from('aaa') },
- { ref: imageRef(pseudoTeam, 'hashB'), bytes: Buffer.from('bb') },
+ { ref: imageRef(teamId, 'hashA'), bytes: Buffer.from('aaa') },
+ { ref: imageRef(teamId, 'hashB'), bytes: Buffer.from('bb') },
])
})
@@ -314,7 +326,7 @@ describe('createParseAndAnonymizeMessageStep with image collection', () => {
const result = await step({ message: kafkaMessage(), headers, team })
expect(result.type).toBe(PipelineResultType.OK)
expect((result as any).value.collectedImages).toEqual([
- { ref: imageRef(pseudoTeam, 'hashA'), bytes: Buffer.from('aaa') },
+ { ref: imageRef(teamId, 'hashA'), bytes: Buffer.from('aaa') },
])
})
@@ -328,14 +340,10 @@ describe('createParseAndAnonymizeMessageStep with image collection', () => {
it('records bounded CSS and HTML image source counts', async () => {
const cssBefore = await imageSourceMetricValue('css', 'background-image', 'inline')
const htmlBefore = await imageSourceMetricValue('html', 'src', 'url')
- addonSuccessWithImages(
- Buffer.from('a'),
- [{ hash: 'hashA', offset: 0, len: 1 }],
- [
- { source: 'css', property: 'background-image', kind: 'inline', count: 3 },
- { source: 'html', property: 'src', kind: 'url', count: 2 },
- ]
- )
+ addonSuccessWithImages(Buffer.from('a'), [{ hash: 'hashA', offset: 0, len: 1 }], 'session-1', [
+ { source: 'css', property: 'background-image', kind: 'inline', count: 3 },
+ { source: 'html', property: 'src', kind: 'url', count: 2 },
+ ])
await step({ message: kafkaMessage(), headers, team })
@@ -346,7 +354,7 @@ describe('createParseAndAnonymizeMessageStep with image collection', () => {
describe('createParseAndAnonymizeMessageStep with url collection', () => {
const secret = 'test-pseudonym-secret'
- const pseudoTeam = pseudonymize(secret, PSEUDONYM_TEAM, '1')
+ const teamId = pseudonymize(secret, PSEUDONYM_TEAM, '1')
const urlKey = pseudonymize(secret, PSEUDONYM_IMAGE_URL_KEY, PSEUDONYM_IMAGE_URL_GLOBAL_VALUE)
const now = Date.now()
const team = { teamId: 1, consoleLogIngestionEnabled: true, aiTrainingOptedIn: true }
@@ -403,11 +411,11 @@ describe('createParseAndAnonymizeMessageStep with url collection', () => {
const otherTeam = { ...team, teamId: 2 }
const otherResult: any = await step({ message: kafkaMessage(), headers, team: otherTeam } as any)
- expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(expect.anything(), null, pseudoTeam, undefined, urlKey)
+ expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(expect.anything(), null, teamId, undefined, urlKey)
expect(result.value.collectedUrls).toEqual([
{
ref: `imageurl:${'h'.repeat(22)}`,
- pseudoTeam,
+ teamId,
url: 'https://cdn.example.com/a.png',
host: 'cdn.example.com',
},
@@ -438,12 +446,6 @@ describe('createParseAndAnonymizeMessageStep with url collection', () => {
await step({ message: kafkaMessage(), headers, team } as any)
- expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(
- expect.anything(),
- null,
- pseudoTeam,
- undefined,
- undefined
- )
+ expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(expect.anything(), null, teamId, undefined, undefined)
})
})
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.ts
index e6254971ef05..9e6699647694 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
@@ -25,6 +25,7 @@ import {
import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
import { MlMirrorMetrics } from './metrics'
+import { MlPrivacyBatchController } from './privacy/batch-controller'
import {
PSEUDONYM_IMAGE_CONTENT_KEY,
PSEUDONYM_IMAGE_URL_GLOBAL_VALUE,
@@ -32,6 +33,7 @@ import {
PSEUDONYM_TEAM,
pseudonymize,
} from './pseudonymize'
+import { sessionStartMonth, usesRawSessionIdentifiers } from './session-identifier-format'
const MESSAGE_TIMESTAMP_DIFF_THRESHOLD_DAYS = 7
@@ -56,7 +58,7 @@ const DLQ_REASONS = new Set([
/** An original image the addon collected for the out-of-band scrub lane, ready to produce. */
export interface CollectedImage {
- /** `image:<pseudoTeam>:<hash>` — the Kafka key the scrub consumer indexes the bytes under. */
+ /** `image:<teamId>:<hash>`, the Kafka key the scrub consumer indexes the bytes under. */
ref: string
bytes: Buffer
}
@@ -71,8 +73,7 @@ export interface CollectedImage {
export interface CollectedUrl {
/** `imageurl:<hash>` stored in the mirrored line's namespaced ref attribute. */
ref: string
- /** The team pseudonym remains transport metadata until the fetch topic moves to its global schema. */
- pseudoTeam: string
+ teamId: string
url: string
/** The host the request goes to. robots.txt and the connection limit are scoped to this. */
host: string
@@ -87,7 +88,7 @@ export interface ParseAndAnonymizeStepOutput extends ParseMessageStepOutput {
}
export interface ImageCollectionConfig {
- /** The ML pseudonym HMAC key; only its per-team derivatives (never the key) cross the FFI. */
+ /** Only derived image content and URL keys cross the FFI; the root key stays here. */
pseudonymSecret: string | Buffer
/** Replace inlined images with refs and return their bytes for the scrub topic. */
collectImages: boolean
@@ -111,7 +112,8 @@ export interface ImageCollectionConfig {
* ingestion warnings are unchanged.
*/
export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInput & { team: TeamForReplay }>(
- imageCollection?: ImageCollectionConfig
+ imageCollection?: ImageCollectionConfig,
+ privacy?: MlPrivacyBatchController
): ProcessingStep<T, T & ParseAndAnonymizeStepOutput> {
const globalUrlKey =
imageCollection?.collectUrls === true
@@ -121,35 +123,37 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInp
// Cache the team values rather than re-deriving them for every message. The content key keys
// the inline image hash. The URL key is global and does not use this cache.
interface TeamImageKeys {
- pseudoTeam: string
+ teamId: string
contentKey?: string
}
- const teamKeysCache = new Map<number, TeamImageKeys>()
- const teamKeysFor = (teamId: number): TeamImageKeys | undefined => {
+ const teamKeysCache = new Map<string, TeamImageKeys>()
+ const teamKeysFor = (teamId: number, sessionId: string): TeamImageKeys | undefined => {
if (!imageCollection) {
return undefined
}
- let keys = teamKeysCache.get(teamId)
+ const rawIdentifiers = usesRawSessionIdentifiers(sessionId)
+ const cacheKey = `${teamId}:${rawIdentifiers}`
+ let keys = teamKeysCache.get(cacheKey)
if (!keys) {
- const pseudoTeam = pseudonymize(imageCollection.pseudonymSecret, PSEUDONYM_TEAM, String(teamId))
+ const teamIdString = rawIdentifiers
+ ? String(teamId)
+ : pseudonymize(imageCollection.pseudonymSecret, PSEUDONYM_TEAM, String(teamId))
const contentKey = pseudonymize(
imageCollection.pseudonymSecret,
PSEUDONYM_IMAGE_CONTENT_KEY,
String(teamId)
)
- // The consumer regex-validates every ref and silently drops non-matches, so a pseudonym
- // format drift would zero the lane with no signal. Refuse to embed a ref the consumer
- // would drop — those messages fall back to the inline blur, loudly.
- if (!isImageRef(imageRef(pseudoTeam, hashImageBytes(contentKey, Buffer.alloc(0))))) {
- logger.error('🖼️', 'ml_image_scrub_pseudo_team_shape_invalid', { teamId })
- MlMirrorMetrics.incrementMlImagePseudoTeamInvalid()
+ // Reject refs the consumer cannot parse so images fall back to inline scrubbing.
+ if (!isImageRef(imageRef(teamIdString, hashImageBytes(contentKey, Buffer.alloc(0))))) {
+ logger.error('🖼️', 'ml_image_scrub_team_id_shape_invalid', { teamId })
+ MlMirrorMetrics.incrementMlImageTeamIdInvalid()
return undefined
}
keys = {
- pseudoTeam,
+ teamId: teamIdString,
contentKey: imageCollection.collectImages ? contentKey : undefined,
}
- teamKeysCache.set(teamId, keys)
+ teamKeysCache.set(cacheKey, keys)
}
return keys
}
@@ -168,17 +172,26 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInp
contentEncoding ?? (isGzipped(message.value) ? 'gzip' : 'none')
)
- const teamKeys = teamKeysFor(input.team.teamId)
+ const teamKeys = teamKeysFor(input.team.teamId, headers.session_id)
+ const privacyKeys = privacy?.keys(input.team.teamId, headers.session_id)
+ let referenceNamespace: string | undefined
+ let imageTeamId: string | undefined
const t0 = performance.now()
const callStartEpochMs = performance.timeOrigin + t0
let result
try {
+ referenceNamespace =
+ privacyKeys && usesRawSessionIdentifiers(headers.session_id)
+ ? `v2:${input.team.teamId}:${sessionStartMonth(headers.session_id)}`
+ : undefined
+ imageTeamId = referenceNamespace ?? teamKeys?.teamId
result = await getRustAnonymizer().anonymizeKafkaPayload(
message.value,
contentEncoding,
- teamKeys?.pseudoTeam,
+ imageTeamId,
teamKeys?.contentKey,
- globalUrlKey
+ globalUrlKey,
+ ...(referenceNamespace ? ([referenceNamespace] as const) : [])
)
} catch (error) {
// A rejected promise (native panic, addon load failure) must fail closed.
@@ -256,6 +269,7 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInp
return dlq('distinct_id_header_body_mismatch')
}
+ recordImageSources(meta)
MlMirrorMetrics.incrementMlJsonLdEvents(meta.jsonLdEventCount)
const parsedMessage: ParsedMessageData = {
@@ -288,10 +302,11 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInp
}
const collectedImages = teamKeys?.contentKey
- ? unpackCollectedImages(teamKeys.pseudoTeam, meta, result.images)
+ ? unpackCollectedImages(imageTeamId!, meta, result.images)
: undefined
- const collectedUrls = globalUrlKey && teamKeys ? unpackCollectedUrls(teamKeys.pseudoTeam, meta) : undefined
- recordImageSources(meta)
+ const collectedUrls =
+ globalUrlKey && teamKeys ? unpackCollectedUrls(teamKeys.teamId, meta, referenceNamespace) : undefined
+
return ok({ ...input, parsedMessage, collectedImages, collectedUrls })
}
}
@@ -313,7 +328,7 @@ function recordImageSources(meta: AnonymizeMeta): void {
* never a blocked message.
*/
function unpackCollectedImages(
- pseudoTeam: string,
+ teamId: string,
meta: AnonymizeMeta,
packed: Buffer | null
): CollectedImage[] | undefined {
@@ -327,7 +342,7 @@ function unpackCollectedImages(
continue
}
images.push({
- ref: imageRef(pseudoTeam, entry.hash),
+ ref: imageRef(teamId, entry.hash),
bytes: packed.subarray(entry.offset, entry.offset + entry.len),
})
}
@@ -342,13 +357,17 @@ function unpackCollectedImages(
* that carry one describes an image-heavy page, and this number exists to size a topic that
* carries all the traffic.
*/
-function unpackCollectedUrls(pseudoTeam: string, meta: AnonymizeMeta): CollectedUrl[] | undefined {
+function unpackCollectedUrls(
+ teamId: string,
+ meta: AnonymizeMeta,
+ referenceNamespace?: string
+): CollectedUrl[] | undefined {
const urls: CollectedUrl[] = []
const domains = new Set<string>()
for (const entry of meta.urls ?? []) {
urls.push({
- ref: urlRef(entry.hash),
- pseudoTeam,
+ ref: referenceNamespace ? `imageurl:${referenceNamespace}:${entry.hash}` : urlRef(entry.hash),
+ teamId,
url: entry.url,
host: entry.host,
domain: entry.domain,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.test.ts
index 4e984be00f64..0cf91b62b060 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.test.ts
@@ -230,7 +230,7 @@ describe('ML session key batches', () => {
})
it('publishes a bounded concurrent batch only after privacy writes commit', async () => {
- const identity = { ...session, sessionId: '01a0a482-5500-7000-8000-000000000001' }
+ const identity = { ...session, sessionId: '01a0a4f0-3200-7000-8000-000000000001' }
const controller = new MlPrivacyBatchController(store, encryption)
await controller.prepare([identity])
let release!: () => void
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/runtime.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/runtime.ts
index 570628fa8525..47c60e9749ec 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/runtime.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/runtime.ts
@@ -9,7 +9,7 @@ import { MlKeyReader } from './reader'
import { MlKafkaEncryption } from './transport'
export interface MlPrivacyConfig {
- AI_RESEARCH_REPLAY_PRIVACY_TABLE: string
+ AI_RESEARCH_REPLAY_KEY_TABLE: string
AI_RESEARCH_REPLAY_KMS_KEY_ARN: string
AI_RESEARCH_REPLAY_AWS_REGION: string
AI_RESEARCH_REPLAY_KEY_CACHE_MAX: number
@@ -27,7 +27,7 @@ export class MlPrivacyRuntime {
private readonly kms: KMSClient
constructor(config: MlPrivacyConfig) {
- if (!config.AI_RESEARCH_REPLAY_PRIVACY_TABLE || !config.AI_RESEARCH_REPLAY_KMS_KEY_ARN) {
+ if (!config.AI_RESEARCH_REPLAY_KEY_TABLE || !config.AI_RESEARCH_REPLAY_KMS_KEY_ARN) {
throw new Error('ML privacy requires a DynamoDB table and a KMS key ARN')
}
this.dynamo = new DynamoDBClient({
@@ -36,7 +36,7 @@ export class MlPrivacyRuntime {
maxAttempts: 3,
})
this.kms = new KMSClient({ region: config.AI_RESEARCH_REPLAY_AWS_REGION, maxAttempts: 3 })
- const db = new MlPrivacyDynamoDB(this.dynamo, config.AI_RESEARCH_REPLAY_PRIVACY_TABLE)
+ const db = new MlPrivacyDynamoDB(this.dynamo, config.AI_RESEARCH_REPLAY_KEY_TABLE)
this.encryption = new MlKeyEncryption(
this.kms,
config.AI_RESEARCH_REPLAY_KMS_KEY_ARN,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.test.ts
index 362c7f57f83b..c3fb992b3696 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.test.ts
@@ -50,12 +50,12 @@ describe('produceCollectedImagesStep', () => {
{
key: 'image:aa:h1',
value: Buffer.from([1]),
- headers: { [CAPTURE_TIMESTAMP_HEADER]: String(CAPTURED_AT) },
+ headers: { [CAPTURE_TIMESTAMP_HEADER]: String(CAPTURED_AT), ai_research_ingestion_version: '1' },
},
{
key: 'image:aa:h2',
value: Buffer.from([2]),
- headers: { [CAPTURE_TIMESTAMP_HEADER]: String(CAPTURED_AT) },
+ headers: { [CAPTURE_TIMESTAMP_HEADER]: String(CAPTURED_AT), ai_research_ingestion_version: '1' },
},
],
])
@@ -80,14 +80,14 @@ describe('produceCollectedImagesStep', () => {
{
key: 'image:aa:h1',
value: Buffer.from([1]),
- headers: { [CAPTURE_TIMESTAMP_HEADER]: String(CAPTURED_AT) },
+ headers: { [CAPTURE_TIMESTAMP_HEADER]: String(CAPTURED_AT), ai_research_ingestion_version: '1' },
},
],
[
{
key: 'image:aa:h2',
value: Buffer.from([1]),
- headers: { [CAPTURE_TIMESTAMP_HEADER]: String(CAPTURED_AT) },
+ headers: { [CAPTURE_TIMESTAMP_HEADER]: String(CAPTURED_AT), ai_research_ingestion_version: '1' },
},
],
])
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts
index f72f42364b0e..d6b0c2d54500 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts
@@ -8,6 +8,9 @@ import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-de
import { MlMirrorMetrics } from './metrics'
import { CollectedImage } from './parse-and-anonymize-step'
+import { MlPrivacyBatchController } from './privacy/batch-controller'
+import { encryptedKafkaValue, validateImageOwner } from './privacy/transport'
+import { usesRawSessionIdentifiers } from './session-identifier-format'
/**
* The Rust collector only dedupes within one message, leaving this as the sole thing between a hot
@@ -22,25 +25,37 @@ const PRODUCED_REF_CACHE_MAX = 500_000
/**
* Produce collected original images to the scrub topic as a fire-and-forget side effect, keyed by
- * their `image:<pseudoTeam>:<hash>` ref. Delivery is deliberately not awaited and never blocks or
+ * their `image:<teamId>:<hash>` ref. Delivery is deliberately not awaited and never blocks or
* fails the message: the mirrored lines already carry the refs, and a ref whose image never lands
* is defined as equivalent to a placeholder for training joins.
*/
export function createProduceCollectedImagesStep<
- T extends { collectedImages?: CollectedImage[]; message: { timestamp?: number } },
+ T extends {
+ team?: { teamId: number }
+ headers?: { session_id: string }
+ collectedImages?: CollectedImage[]
+ message: { timestamp?: number }
+ },
>(
outputs: IngestionOutputs<MlImageScrubOutput>,
- producedRefCacheMax: number = PRODUCED_REF_CACHE_MAX
+ producedRefCacheMax: number = PRODUCED_REF_CACHE_MAX,
+ privacy?: MlPrivacyBatchController
): ProcessingStep<T, T> {
const producedRefs = new RefDedupCache('image_scrub_producer', producedRefCacheMax)
return function produceCollectedImagesStep(input) {
+ const sessionId = input.headers?.session_id
+ const key =
+ sessionId && usesRawSessionIdentifiers(sessionId) && input.team
+ ? privacy?.keys(input.team.teamId, sessionId)?.session
+ : undefined
const images = input.collectedImages
if (!images?.length) {
return Promise.resolve(ok(input))
}
- const fresh = images.filter((image) => !producedRefs.has(image.ref))
+ const cacheRef = (ref: string): string => (key ? `${key.identity.sessionId}:${ref}` : ref)
+ const fresh = images.filter((image) => !producedRefs.has(cacheRef(image.ref)))
MlMirrorMetrics.incrementMlImagesCollected('deduped', images.length - fresh.length)
if (fresh.length === 0) {
return Promise.resolve(ok({ ...input, collectedImages: undefined }))
@@ -48,7 +63,7 @@ export function createProduceCollectedImagesStep<
let bytes = 0
for (const image of fresh) {
- producedRefs.add(image.ref)
+ producedRefs.add(cacheRef(image.ref))
bytes += image.bytes.length
}
MlMirrorMetrics.incrementMlImagesCollected('queued', fresh.length)
@@ -62,11 +77,15 @@ export function createProduceCollectedImagesStep<
// whole packed FFI buffer (up to 32 MB per source message), and queueMessages copies the
// slices synchronously — a closure holding `fresh` would pin the full packed buffer per
// in-flight produce, unbounded by the producer queue's byte accounting.
- const refs = fresh.map((image) => image.ref)
+ const refs = fresh.map((image) => cacheRef(image.ref))
const produce = outputs
.queueMessages(
ML_IMAGE_SCRUB_OUTPUT,
- fresh.map((image) => ({ key: image.ref, value: image.bytes, headers }))
+ fresh.map((image) => {
+ validateImageOwner(image.ref, key)
+ const encrypted = encryptedKafkaValue(key, 'image-source', image.bytes, image.ref)
+ return { key: image.ref, value: encrypted.value, headers: { ...headers, ...encrypted.headers } }
+ })
)
.then(() => {
// queueMessages resolves on delivery acks, so `produced` counts what actually landed.
@@ -83,6 +102,9 @@ export function createProduceCollectedImagesStep<
}
logger.warn('🖼️', 'ml_image_scrub_produce_failed', { count: refs.length, error: String(error) })
MlMirrorMetrics.incrementMlImagesCollected('produce_failed', refs.length)
+ if (key) {
+ throw error
+ }
})
return Promise.resolve(ok({ ...input, collectedImages: undefined }, [produce]))
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.ts
index 58df08cf9cac..513dc947cf77 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.ts
@@ -10,7 +10,7 @@ import { CollectedUrl } from './parse-and-anonymize-step'
import { CollectedUrlsMessage, createProduceCollectedUrlsStep } from './produce-collected-urls-step'
describe('produceCollectedUrlsStep', () => {
- const PSEUDO_TEAM = 'a'.repeat(32)
+ const TEAM_ID = '42'
const CAPTURED_AT = 1_700_000_000_000
let queued: { key: string; value: Buffer }[][]
let outputs: IngestionOutputs<MlImageFetchOutput>
@@ -31,7 +31,7 @@ describe('produceCollectedUrlsStep', () => {
})
function collected(hash: string, host: string, url: string, domain = host): CollectedUrl {
- return { ref: `imageurl:${hash.padEnd(22, 'x')}`, pseudoTeam: PSEUDO_TEAM, url, host, domain }
+ return { ref: `imageurl:${hash.padEnd(22, 'x')}`, teamId: TEAM_ID, url, host, domain }
}
function decode(batch: { key: string; value: Buffer }[]) {
@@ -233,8 +233,8 @@ describe('produceCollectedUrlsStep', () => {
})
test.each([
- ['inline image', `image:${PSEUDO_TEAM}:h1xxxxxxxxxxxxxxxxxxxx`],
- ['legacy team-scoped URL', `imageurl:${PSEUDO_TEAM}:h1xxxxxxxxxxxxxxxxxxxx`],
+ ['inline image', `image:${TEAM_ID}:h1xxxxxxxxxxxxxxxxxxxx`],
+ ['legacy team-scoped URL', `imageurl:${'a'.repeat(32)}:h1xxxxxxxxxxxxxxxxxxxx`],
])('refuses to produce a %s ref', async (_name, ref) => {
const step = createProduceCollectedUrlsStep(outputs, topHog, { producedRefCacheMax: 100 })
@@ -243,7 +243,7 @@ describe('produceCollectedUrlsStep', () => {
collectedUrls: [
{
ref,
- pseudoTeam: PSEUDO_TEAM,
+ teamId: TEAM_ID,
url: 'https://img.example.com/a.png',
host: 'img.example.com',
domain: 'example.com',
@@ -263,8 +263,8 @@ describe('produceCollectedUrlsStep', () => {
collectedUrls: [
collected('h1', 'img.example.com', 'https://img.example.com/a.png'),
{
- ref: `image:${PSEUDO_TEAM}:h2xxxxxxxxxxxxxxxxxxxx`,
- pseudoTeam: PSEUDO_TEAM,
+ ref: `image:${TEAM_ID}:h2xxxxxxxxxxxxxxxxxxxx`,
+ teamId: TEAM_ID,
url: 'https://img.example.com/inlined.png',
host: 'img.example.com',
domain: 'example.com',
@@ -338,7 +338,7 @@ describe('produceCollectedUrlsStep', () => {
collected('h1', 'img.example.com', 'https://img.example.com/a.png'),
{
ref: `imageurl:h2xxxxxxxxxxxxxxxxxxxx`,
- pseudoTeam: otherTeam,
+ teamId: otherTeam,
url: 'https://img.example.com/b.png',
host: 'img.example.com',
domain: 'img.example.com',
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts
index d1553c4dbdcb..1cdca6773b7c 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts
@@ -12,6 +12,9 @@ import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-de
import { MlMirrorMetrics } from './metrics'
import { CollectedUrl } from './parse-and-anonymize-step'
+import { MlPrivacyBatchController } from './privacy/batch-controller'
+import { encryptedKafkaValue, validateImageOwner } from './privacy/transport'
+import { usesRawSessionIdentifiers } from './session-identifier-format'
/**
* The same trade as the image lane's cache, at a much lower cost per entry: a record here holds a
@@ -59,6 +62,7 @@ export interface CollectedUrlsMessage {
}
export interface ProduceCollectedUrlsOptions {
+ privacy?: MlPrivacyBatchController
producedRefCacheMax?: number
producedRefCacheWindowMs?: number
crawlHistory?: Pick<CrawlHistoryStore, 'read'>
@@ -136,7 +140,12 @@ async function excludeFreshCrawlHistory(
* it goes only into the Kafka value. Log lines and metrics carry hosts and counts only.
*/
export function createProduceCollectedUrlsStep<
- T extends { collectedUrls?: CollectedUrl[]; message: { timestamp?: number } },
+ T extends {
+ team?: { teamId: number }
+ headers?: { session_id: string }
+ collectedUrls?: CollectedUrl[]
+ message: { timestamp?: number }
+ },
>(
outputs: IngestionOutputs<MlImageFetchOutput>,
topHog: TopHogRegistry,
@@ -159,6 +168,11 @@ export function createProduceCollectedUrlsStep<
let nextCrawlHistoryWarningAtMs = 0
return async function produceCollectedUrlsStep(input) {
+ const sessionId = input.headers?.session_id
+ const key =
+ sessionId && usesRawSessionIdentifiers(sessionId) && input.team
+ ? options.privacy?.keys(input.team.teamId, sessionId)?.session
+ : undefined
const collected = input.collectedUrls
if (!collected?.length) {
return ok(input)
@@ -167,7 +181,10 @@ export function createProduceCollectedUrlsStep<
const nowMs = Date.now()
const timeBucket = Math.floor(nowMs / producedRefCacheWindowMs)
const fresh = collected
- .map((entry) => ({ entry, cacheKey: producedUrlCacheKey(entry, timeBucket) }))
+ .map((entry) => ({
+ entry,
+ cacheKey: `${key?.identity.sessionId ?? ''}:${producedUrlCacheKey(entry, timeBucket)}`,
+ }))
.filter(({ cacheKey }) => !producedTransportUrls.has(cacheKey))
MlMirrorMetrics.incrementMlUrlsCollected('deduped', collected.length - fresh.length)
if (fresh.length === 0) {
@@ -179,23 +196,24 @@ export function createProduceCollectedUrlsStep<
// reaches the fetcher under a hash nothing will ever match. Both kinds parse, so only
// `source` separates them, and checking one entry would let every later one through.
//
- // Every entry must use the global URL-ref shape and carry the same transport pseudonym. One
- // replay message belongs to one team, and a record stamped with another team's pseudonym is
+ // Every entry must use the global URL-ref shape and carry the same team ID. One
+ // replay message belongs to one team, and a record stamped with another team's ID is
// a tenant-attribution error that nothing downstream can detect.
const usable: typeof fresh = []
- let pseudoTeam: string | undefined
+ let teamId: string | undefined
for (const candidate of fresh) {
const { entry } = candidate
+ validateImageOwner(entry.ref, key)
const parsed = parseImageRef(entry.ref)
if (
!parsed ||
parsed.source !== 'url' ||
parsed.pseudoTeam !== undefined ||
- (pseudoTeam && entry.pseudoTeam !== pseudoTeam)
+ (teamId && entry.teamId !== teamId)
) {
continue
}
- pseudoTeam ??= entry.pseudoTeam
+ teamId ??= entry.teamId
usable.push(candidate)
}
const unusable = fresh.length - usable.length
@@ -205,20 +223,25 @@ export function createProduceCollectedUrlsStep<
// otherwise write an error line at full ingest rate for as long as it lasted.
logger.warn('🌐', 'ml_image_fetch_ref_unusable', { count: unusable })
}
- if (!pseudoTeam || usable.length === 0) {
+ if (!teamId || usable.length === 0) {
return ok({ ...input, collectedUrls: undefined })
}
for (const { cacheKey } of usable) {
producedTransportUrls.add(cacheKey)
}
- const publishable = await excludeFreshCrawlHistory(usable, crawlHistory, nowMs, (error, count) => {
- if (nowMs < nextCrawlHistoryWarningAtMs) {
- return
+ const publishable = await excludeFreshCrawlHistory(
+ usable,
+ key ? undefined : crawlHistory,
+ nowMs,
+ (error, count) => {
+ if (nowMs < nextCrawlHistoryWarningAtMs) {
+ return
+ }
+ nextCrawlHistoryWarningAtMs = nowMs + CRAWL_HISTORY_WARNING_INTERVAL_MS
+ logger.warn('🌐', 'ml_image_fetch_crawl_history_precheck_failed', { count, error: String(error) })
}
- nextCrawlHistoryWarningAtMs = nowMs + CRAWL_HISTORY_WARNING_INTERVAL_MS
- logger.warn('🌐', 'ml_image_fetch_crawl_history_precheck_failed', { count, error: String(error) })
- })
+ )
if (publishable.length === 0) {
return ok({ ...input, collectedUrls: undefined })
}
@@ -256,7 +279,7 @@ export function createProduceCollectedUrlsStep<
} satisfies CollectedUrlsMessage)
)
MlMirrorMetrics.observeMlUrlRecord(slice.length, value.length)
- return { key: domain, value }
+ return { key: domain, ...encryptedKafkaValue(key, 'image-frontier', value) }
})
)
@@ -287,6 +310,9 @@ export function createProduceCollectedUrlsStep<
error: String(error),
})
MlMirrorMetrics.incrementMlUrlsCollected('produce_failed', producedCacheKeys.length)
+ if (key) {
+ throw error
+ }
})
return ok({ ...input, collectedUrls: undefined }, [produce])
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.test.ts
index d827f25443bf..b2d2673b0f9d 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.test.ts
@@ -1,22 +1,28 @@
-import { PSEUDONYM_SESSION, PSEUDONYM_TEAM, pseudonymize } from './pseudonymize'
+import { PSEUDONYM_IMAGE_CONTENT_KEY, PSEUDONYM_IMAGE_URL_KEY, pseudonymize } from './pseudonymize'
describe('ml-mirror/pseudonymize', () => {
const secret = 'super-secret'
it('is deterministic: same input maps to the same value', () => {
- expect(pseudonymize(secret, PSEUDONYM_TEAM, '42')).toBe(pseudonymize(secret, PSEUDONYM_TEAM, '42'))
+ expect(pseudonymize(secret, PSEUDONYM_IMAGE_CONTENT_KEY, '42')).toBe(
+ pseudonymize(secret, PSEUDONYM_IMAGE_CONTENT_KEY, '42')
+ )
})
- it('domain-separates namespaces so a team id and session id with the same value differ', () => {
- expect(pseudonymize(secret, PSEUDONYM_TEAM, '42')).not.toBe(pseudonymize(secret, PSEUDONYM_SESSION, '42'))
+ it('domain-separates image content and URL keys', () => {
+ expect(pseudonymize(secret, PSEUDONYM_IMAGE_CONTENT_KEY, '42')).not.toBe(
+ pseudonymize(secret, PSEUDONYM_IMAGE_URL_KEY, '42')
+ )
})
it('depends on the secret: a different secret produces a different value', () => {
- expect(pseudonymize(secret, PSEUDONYM_TEAM, '42')).not.toBe(pseudonymize('other-secret', PSEUDONYM_TEAM, '42'))
+ expect(pseudonymize(secret, PSEUDONYM_IMAGE_CONTENT_KEY, '42')).not.toBe(
+ pseudonymize('other-secret', PSEUDONYM_IMAGE_CONTENT_KEY, '42')
+ )
})
it('does not contain the raw value', () => {
- const out = pseudonymize(secret, PSEUDONYM_TEAM, 'team-12345')
+ const out = pseudonymize(secret, PSEUDONYM_IMAGE_CONTENT_KEY, 'team-12345')
expect(out).not.toContain('team-12345')
expect(out).toMatch(/^[0-9a-f]{32}$/)
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts
index 7a43507d4e80..7772371db127 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts
@@ -1,21 +1,15 @@
import { createHmac } from 'crypto'
-/**
- * Deterministic, non-reversible pseudonym for an identifier. Same input → same
- * output (so the ML dataset can group by team/session/person), but without the
- * secret (held only by the ingester, never in the ML account) it can't be mapped
- * back. The namespace domain-separates ids so a teamId and sessionId with the
- * same value don't collide.
- */
export function pseudonymize(secret: string | Buffer, namespace: string, value: string): string {
// Length-prefix the namespace so the join is unambiguous even if a value contains the delimiter.
return createHmac('sha256', secret).update(`${namespace.length}:${namespace}:${value}`).digest('hex').slice(0, 32)
}
-export const PSEUDONYM_TEAM = 'team'
/** Namespace for the per-team image content-HMAC key (see ml-mirror-image-scrub/content-ref.ts). */
export const PSEUDONYM_IMAGE_CONTENT_KEY = 'image-content-key'
/** Namespace for the global URL-HMAC key, which hashes a remote image's URL rather than its bytes. */
export const PSEUDONYM_IMAGE_URL_KEY = 'image-url-key'
export const PSEUDONYM_IMAGE_URL_GLOBAL_VALUE = 'global-v1'
+
+export const PSEUDONYM_TEAM = 'team'
export const PSEUDONYM_SESSION = 'session'
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format-cases.json b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format-cases.json
index a87cd6f66ba6..ca03e311b40b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format-cases.json
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format-cases.json
@@ -1,28 +1,28 @@
{
- "cutoffMs": 1789466400000,
+ "cutoffMs": 1789473600000,
"cases": [
{
- "sessionId": "01a0a482-54ff-7000-8000-000000000001",
+ "sessionId": "01a0a4f0-31ff-7000-8000-000000000001",
"rawIdentifiers": false,
- "storedSessionId": "fb55e8182cd5ac4247c1894289cea4d1",
+ "storedSessionId": "eebac832676947ee2e5c90c484e8b424",
"storedTeamId": "a725cc999d0421ba516777bc3c460c8d"
},
{
- "sessionId": "01a0a482-5500-7000-8000-000000000001",
+ "sessionId": "01a0a4f0-3200-7000-8000-000000000001",
"rawIdentifiers": true,
- "storedSessionId": "01a0a482-5500-7000-8000-000000000001",
+ "storedSessionId": "01a0a4f0-3200-7000-8000-000000000001",
"storedTeamId": "7"
},
{
- "sessionId": "01a0a482-5501-7000-8000-000000000001",
+ "sessionId": "01a0a4f0-3201-7000-8000-000000000001",
"rawIdentifiers": true,
- "storedSessionId": "01a0a482-5501-7000-8000-000000000001",
+ "storedSessionId": "01a0a4f0-3201-7000-8000-000000000001",
"storedTeamId": "7"
},
{
- "sessionId": "01A0A482-5500-7000-8000-000000000001",
+ "sessionId": "01A0A4F0-3200-7000-8000-000000000001",
"rawIdentifiers": true,
- "storedSessionId": "01A0A482-5500-7000-8000-000000000001",
+ "storedSessionId": "01A0A4F0-3200-7000-8000-000000000001",
"storedTeamId": "7"
},
{
@@ -32,15 +32,15 @@
"storedTeamId": "a725cc999d0421ba516777bc3c460c8d"
},
{
- "sessionId": "01a0a482-5500-4000-8000-000000000001",
+ "sessionId": "01a0a4f0-3200-4000-8000-000000000001",
"rawIdentifiers": false,
- "storedSessionId": "047dc889f71de4a7dc45e5cf462dbaaf",
+ "storedSessionId": "239c74961345c3a99018f80de07eabaf",
"storedTeamId": "a725cc999d0421ba516777bc3c460c8d"
},
{
- "sessionId": "01a0a482-5500-7000-0000-000000000001",
+ "sessionId": "01a0a4f0-3200-7000-0000-000000000001",
"rawIdentifiers": false,
- "storedSessionId": "730f80c89283a28469d60e44047ed476",
+ "storedSessionId": "4e59ab2ba8d895788f4d28f3e9be9037",
"storedTeamId": "a725cc999d0421ba516777bc3c460c8d"
},
{
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format.ts
index 0015b0e97906..2b789eb29efa 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format.ts
@@ -1,4 +1,4 @@
-export const RAW_SESSION_IDENTIFIERS_START_MS = Date.parse('2026-09-15T10:00:00Z')
+export const RAW_SESSION_IDENTIFIERS_START_MS = Date.parse('2026-09-15T12:00:00Z')
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)) {
@@ -13,6 +13,11 @@ export function usesRawSessionIdentifiers(sessionId: string): boolean {
return startedAt !== null && startedAt >= RAW_SESSION_IDENTIFIERS_START_MS && startedAt < Date.UTC(10000, 0, 1)
}
+export function isSupportedMlSessionId(sessionId: string): boolean {
+ const startedAt = sessionStartTimestampFromUuidV7(sessionId)
+ return startedAt !== null && startedAt < Date.UTC(10000, 0, 1)
+}
+
export function sessionStartMonth(sessionId: string): string {
const timestamp = sessionStartTimestampFromUuidV7(sessionId)
if (timestamp === null) {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts
index 666a645b8c55..73e3b4030c87 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts
@@ -354,32 +354,35 @@ describeAddon('native image collection', () => {
return Buffer.from(JSON.stringify({ distinct_id: 'd-1', data: inner }))
}
- it('replaces the image with a consumer-parseable ref and returns the original bytes', async () => {
- rustAddon!.initAnonymizer({ text: [], url: [] })
- const result = await rustAddon!.anonymizeKafkaPayload(imagePayload(), undefined, PSEUDO_TEAM, CONTENT_KEY)
- expect(result.failed).toBe(false)
-
- const png = Buffer.from(PNG_B64, 'base64')
- const expectedRef = imageRef(PSEUDO_TEAM, hashImageBytes(CONTENT_KEY, png))
- expect(isImageRef(expectedRef)).toBe(true)
- expect(result.lines!.toString()).toContain(expectedRef)
- expect(result.lines!.toString()).not.toContain(PNG_B64)
+ it.each([PSEUDO_TEAM, '42'])(
+ 'emits a consumer-parseable ref for team %s and returns the original bytes',
+ async (team) => {
+ rustAddon!.initAnonymizer({ text: [], url: [] })
+ const result = await rustAddon!.anonymizeKafkaPayload(imagePayload(), undefined, team, CONTENT_KEY)
+ expect(result.failed).toBe(false)
- const meta = parseJSON(result.meta!) as { images?: { hash: string; offset: number; len: number }[] }
- expect(meta.images).toHaveLength(1)
- const entry = meta.images![0]
- const bytes = result.images!.subarray(entry.offset, entry.offset + entry.len)
- expect(Buffer.from(bytes)).toEqual(png)
- // The Rust-emitted hash must be the keyed HMAC of the returned bytes.
- expect(hashImageBytes(CONTENT_KEY, Buffer.from(bytes))).toBe(entry.hash)
- // `source` is what tells a reader whether the hash names the bytes or only the URL they
- // came from. An inlined image is content-addressed, so it must read as `bytes`.
- expect(parseImageRef(expectedRef)).toEqual({
- pseudoTeam: PSEUDO_TEAM,
- hash: entry.hash,
- source: 'bytes',
- })
- })
+ const png = Buffer.from(PNG_B64, 'base64')
+ const expectedRef = imageRef(team, hashImageBytes(CONTENT_KEY, png))
+ expect(isImageRef(expectedRef)).toBe(true)
+ expect(result.lines!.toString()).toContain(expectedRef)
+ expect(result.lines!.toString()).not.toContain(PNG_B64)
+
+ const meta = parseJSON(result.meta!) as { images?: { hash: string; offset: number; len: number }[] }
+ expect(meta.images).toHaveLength(1)
+ const entry = meta.images![0]
+ const bytes = result.images!.subarray(entry.offset, entry.offset + entry.len)
+ expect(Buffer.from(bytes)).toEqual(png)
+ // The Rust-emitted hash must be the keyed HMAC of the returned bytes.
+ expect(hashImageBytes(CONTENT_KEY, Buffer.from(bytes))).toBe(entry.hash)
+ // `source` is what tells a reader whether the hash names the bytes or only the URL they
+ // came from. An inlined image is content-addressed, so it must read as `bytes`.
+ expect(parseImageRef(expectedRef)).toEqual({
+ ...(team === PSEUDO_TEAM ? { pseudoTeam: team } : { teamId: team }),
+ hash: entry.hash,
+ source: 'bytes',
+ })
+ }
+ )
it('collects nothing without the collection keys and blurs inline instead', async () => {
rustAddon!.initAnonymizer({ text: [], url: [] })
@@ -390,7 +393,7 @@ describeAddon('native image collection', () => {
expect(result.lines!.toString()).not.toContain('image:')
})
- it('requires a pseudonym only for the inline image key', async () => {
+ it('requires a team ID only for the inline image key', async () => {
rustAddon!.initAnonymizer({ text: [], url: [] })
await expect(
rustAddon!.anonymizeKafkaPayload(imagePayload(), undefined, undefined, CONTENT_KEY)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-stages.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-stages.ts
new file mode 100644
index 000000000000..ec32583c01db
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-stages.ts
@@ -0,0 +1,120 @@
+import { OverflowOutput } from '~/common/outputs'
+import { createApplyEventRestrictionsStep, createParseHeadersStep } from '~/ingestion/common/steps/event-preprocessing'
+import { ChunkPipelineBuilder, PipelineBuilder, StartPipelineBuilder } from '~/ingestion/framework/builders'
+import { TopHogRegistry, createTopHogWrapper, sum, timer } from '~/ingestion/framework/extensions/tophog'
+import { ProcessingStep } from '~/ingestion/framework/steps'
+
+import { NewSessionFlag, Recordable, SessionReplayHeaders } from './pipeline-types'
+import { RecordSessionEventStepInput } from './record-session-event-step'
+import { createMarkSeenStep } from './session-batch-mark-seen-step'
+import { createResolveRetentionStep } from './session-batch-resolve-retention-step'
+import { createTrackAndGateStep } from './session-batch-track-and-gate-step'
+import type { SessionReplayPipelineConfig, SessionReplayPipelineInput } from './session-replay-pipeline'
+import { createResolveKeyStep } from './session-resolve-key-step'
+import { RetentionPeriod } from './shared/constants'
+import { createTeamFilterStep } from './team-filter-step'
+import { TeamForReplay } from './teams/types'
+import { createValidateSessionReplayHeadersStep } from './validate-headers-step'
+
+type ValidatedReplayInput = SessionReplayPipelineInput & { headers: SessionReplayHeaders; team: TeamForReplay }
+
+export function addSessionReplayPreprocessing<C>(
+ builder: StartPipelineBuilder<SessionReplayPipelineInput, C>,
+ config: Pick<SessionReplayPipelineConfig, 'eventIngestionRestrictionManager' | 'overflowMode' | 'teamService'>
+): PipelineBuilder<SessionReplayPipelineInput, ValidatedReplayInput, C, OverflowOutput> {
+ const { eventIngestionRestrictionManager, overflowMode, teamService } = config
+ return (
+ builder
+ // Parse headers and apply restrictions (drop/overflow)
+ .pipe(createParseHeadersStep())
+ .pipe(
+ createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {
+ overflowMode,
+ preservePartitionLocality: true, // Sessions must stay on the same partition
+ // Replay never reads or writes persons. The line above pins
+ // locality either way, so this only records the fact.
+ pipelineWritesPersons: false,
+ })
+ )
+ // Validate the headers capture guarantees (DLQ if missing) and narrow the type
+ .pipe(createValidateSessionReplayHeadersStep())
+ // Validate team ownership and enrich with team context
+ .pipe(createTeamFilterStep(teamService))
+ )
+}
+
+export function addSessionReplaySessionResolution<
+ TInput,
+ T extends ValidatedReplayInput,
+ CInput,
+ COutput,
+ R extends string,
+ D,
+>(
+ builder: ChunkPipelineBuilder<TInput, T, CInput, COutput, R, D>,
+ config: Pick<
+ SessionReplayPipelineConfig,
+ 'retentionService' | 'sessionTracker' | 'sessionFilter' | 'keyStore' | 'sessionKeyResolutionMaxConcurrency'
+ >
+): ChunkPipelineBuilder<
+ TInput,
+ Recordable<T & { retentionPeriod: RetentionPeriod } & NewSessionFlag>,
+ CInput,
+ COutput,
+ R,
+ D
+> {
+ const { retentionService, sessionTracker, sessionFilter, keyStore, sessionKeyResolutionMaxConcurrency } = config
+ return (
+ builder
+ .pipeChunk(createResolveRetentionStep(retentionService), {
+ retry: { tries: 3, sleepMs: 100 },
+ })
+ // Track sessions and rate-limit new ones for the whole batch, tagging the survivors with
+ // isNewSession and dropping the blocked ones right here (they carry no key, so nothing
+ // downstream acts on them). Its own retry scope means a later key-resolution failure never
+ // re-runs the rate limiter and double-charges the budget.
+ .pipeChunk(createTrackAndGateStep(sessionTracker, sessionFilter), {
+ retry: { tries: 3, sleepMs: 100 },
+ })
+ // Resolve each session's encryption key. Grouped by session so it runs once per session
+ // (the cached keystore fans the key to its other messages) and concurrently across
+ // sessions, capped to bound KMS/DynamoDB fan-out. Per-session retry isolates a transient
+ // keystore blip to that one session. Deleted sessions are dropped here.
+ .concurrentlyPerGroup(
+ (element) => `${element.team.teamId}:${element.headers.session_id}`,
+ (group) =>
+ group.sequentially((b) =>
+ b.pipe(createResolveKeyStep(keyStore), {
+ retry: { name: 'resolve_session_key', tries: 3, sleepMs: 100 },
+ })
+ ),
+ { maxConcurrency: sessionKeyResolutionMaxConcurrency }
+ )
+ // Re-collect the per-session groups into one batch — both to mark the whole batch seen
+ // in a single Redis write and as the barrier that guarantees every key is resolved first.
+ .gather()
+ // Mark the surviving new sessions seen, now that every key is durably resolved.
+ .pipeChunk(createMarkSeenStep(sessionTracker))
+ )
+}
+
+export function withSessionReplayRecordingMetrics<T extends RecordSessionEventStepInput>(
+ topHog: TopHogRegistry,
+ step: ProcessingStep<T, T>
+): ProcessingStep<T, T> {
+ return createTopHogWrapper(topHog)(step, [
+ sum(
+ 'message_size_by_session_id',
+ (input) => ({
+ token: input.parsedMessage.token ?? 'unknown',
+ session_id: input.parsedMessage.session_id,
+ }),
+ (input) => input.parsedMessage.metadata.rawSize
+ ),
+ timer('consume_time_ms_by_session_id', (input) => ({
+ token: input.parsedMessage.token ?? 'unknown',
+ session_id: input.parsedMessage.session_id,
+ })),
+ ])
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts
index cd9e3cd670b4..c59c0b2a2355 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts
@@ -5,11 +5,10 @@ import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'
import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
-import { createApplyEventRestrictionsStep, createParseHeadersStep } from '~/ingestion/common/steps/event-preprocessing'
import { IngestionOverflowMode } from '~/ingestion/config'
import { BatchingContext, BatchingPipeline } from '~/ingestion/framework/batching-pipeline'
import { newBatchingPipeline } from '~/ingestion/framework/builders'
-import { TopHogRegistry, createTopHogWrapper, sum, timer } from '~/ingestion/framework/extensions/tophog'
+import { TopHogRegistry, createTopHogWrapper, timer } from '~/ingestion/framework/extensions/tophog'
import { aggregateKafkaDebugContexts, createBatch } from '~/ingestion/framework/helpers'
import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'
import { isOkResult, ok } from '~/ingestion/framework/results'
@@ -28,13 +27,12 @@ import { createParseMessageStep } from './parse-message-step'
import { MessageContext } from './pipeline-types'
import { createRecordSessionEventStep } from './record-session-event-step'
import { SessionBatchContext } from './session-batch-context'
-import { createMarkSeenStep } from './session-batch-mark-seen-step'
-import { createResolveRetentionStep } from './session-batch-resolve-retention-step'
-import { createTrackAndGateStep } from './session-batch-track-and-gate-step'
-import { createResolveKeyStep } from './session-resolve-key-step'
+import {
+ addSessionReplayPreprocessing,
+ addSessionReplaySessionResolution,
+ withSessionReplayRecordingMetrics,
+} from './session-replay-pipeline-stages'
import { createRecordSessionUsageStep, trackUnbilledNewSessions } from './session-usage-step'
-import { createTeamFilterStep } from './team-filter-step'
-import { createValidateSessionReplayHeadersStep } from './validate-headers-step'
export interface SessionReplayPipelineInput extends SessionBatchContext {
message: Message
@@ -95,21 +93,7 @@ export interface SessionReplayPipelineConfig {
* 5. Record - Record parsed messages to the batch's recorder
*/
export function createSessionReplayPipeline(config: SessionReplayPipelineConfig): SessionReplayPipeline {
- const {
- outputs,
- eventIngestionRestrictionManager,
- overflowMode,
- promiseScheduler,
- teamService,
- retentionService,
- sessionTracker,
- sessionFilter,
- keyStore,
- sessionKeyResolutionMaxConcurrency,
- topHog,
- isDebugLoggingEnabled,
- usageBatch,
- } = config
+ const { outputs, promiseScheduler, topHog, isDebugLoggingEnabled, usageBatch } = config
const pipelineConfig: PipelineConfig<OverflowOutput> = {
outputs,
@@ -133,58 +117,15 @@ export function createSessionReplayPipeline(config: SessionReplayPipelineConfig)
(batch) =>
batch
.messageAware((b) =>
- b
- .sequentially((b) =>
- b
- // Parse headers and apply restrictions (drop/overflow)
- .pipe(createParseHeadersStep())
- .pipe(
- createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {
- overflowMode,
- preservePartitionLocality: true, // Sessions must stay on the same partition
- // Replay never reads or writes persons. The line above pins
- // locality either way, so this only records the fact.
- pipelineWritesPersons: false,
- })
- )
- // Validate the headers capture guarantees (DLQ if missing) and narrow the type
- .pipe(createValidateSessionReplayHeadersStep())
- // Validate team ownership and enrich with team context
- .pipe(createTeamFilterStep(teamService))
- )
- // Resolve retention for the whole batch in one call, before the message is parsed and
- // recorded — keyed on the (validated) session_id header. Sessions with unresolvable
- // retention are dropped before any parse or write.
- .gather()
- .pipeChunk(createResolveRetentionStep(retentionService), {
- retry: { tries: 3, sleepMs: 100 },
- })
- // Track sessions and rate-limit new ones for the whole batch, tagging the survivors with
- // isNewSession and dropping the blocked ones right here (they carry no key, so nothing
- // downstream acts on them). Its own retry scope means a later key-resolution failure never
- // re-runs the rate limiter and double-charges the budget.
- .pipeChunk(createTrackAndGateStep(sessionTracker, sessionFilter), {
- retry: { tries: 3, sleepMs: 100 },
- })
- // Resolve each session's encryption key. Grouped by session so it runs once per session
- // (the cached keystore fans the key to its other messages) and concurrently across
- // sessions, capped to bound KMS/DynamoDB fan-out. Per-session retry isolates a transient
- // keystore blip to that one session. Deleted sessions are dropped here.
- .concurrentlyPerGroup(
- (element) => `${element.team.teamId}:${element.headers.session_id}`,
- (group) =>
- group.sequentially((b) =>
- b.pipe(createResolveKeyStep(keyStore), {
- retry: { name: 'resolve_session_key', tries: 3, sleepMs: 100 },
- })
- ),
- { maxConcurrency: sessionKeyResolutionMaxConcurrency }
- )
- // Re-collect the per-session groups into one batch — both to mark the whole batch seen
- // in a single Redis write and as the barrier that guarantees every key is resolved first.
- .gather()
- // Mark the surviving new sessions seen, now that every key is durably resolved.
- .pipeChunk(createMarkSeenStep(sessionTracker))
+ addSessionReplaySessionResolution(
+ b
+ .sequentially((b) => addSessionReplayPreprocessing(b, config))
+ // Resolve retention for the whole batch in one call, before the message is parsed and
+ // recorded — keyed on the (validated) session_id header. Sessions with unresolvable
+ // retention are dropped before any parse or write.
+ .gather(),
+ config
+ )
// Map TeamForReplay.teamId to context.team.id for handleIngestionWarnings
.filterMap(
(element) => ({
@@ -214,24 +155,11 @@ export function createSessionReplayPipeline(config: SessionReplayPipelineConfig)
// Monitor library version and emit warnings for old versions
.pipe(createLibVersionMonitorStep())
.pipe(
- topHogWrapper(
+ withSessionReplayRecordingMetrics(
+ topHog,
createRecordSessionEventStep({
isDebugLoggingEnabled,
- }),
- [
- sum(
- 'message_size_by_session_id',
- (input) => ({
- token: input.parsedMessage.token ?? 'unknown',
- session_id: input.parsedMessage.session_id,
- }),
- (input) => input.parsedMessage.metadata.rawSize
- ),
- timer('consume_time_ms_by_session_id', (input) => ({
- token: input.parsedMessage.token ?? 'unknown',
- session_id: input.parsedMessage.session_id,
- })),
- ]
+ })
)
)
.pipe(createRecordSessionUsageStep(usageBatch))
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
index 17d337a53d6b..182223f163a4 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
@@ -237,7 +237,7 @@ export class IngestionSessionReplayMlImageFetchServer extends MlMirrorConsumerSe
await legacyCrawlHistory.validateAccess(Date.now())
let crawlHistory =
legacyCrawlHistory as import('~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history').CrawlHistoryStore
- if (this.config.AI_RESEARCH_REPLAY_PRIVACY_TABLE) {
+ if (this.config.AI_RESEARCH_REPLAY_KEY_TABLE) {
if (
!this.config.AI_RESEARCH_REPLAY_IMAGE_FETCH_V2_DYNAMODB_TABLE ||
this.config.AI_RESEARCH_REPLAY_IMAGE_FETCH_V2_DYNAMODB_TABLE === tableName
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.test.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.test.ts
index 9a0ae175fad0..d36cb54b57be 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.test.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.test.ts
@@ -11,7 +11,7 @@ describe('image scrub server startup', () => {
'rejects privacy configuration without a DLQ before starting dependencies (%p)',
async (topic) => {
const server = new TestImageScrubServer({
- AI_RESEARCH_REPLAY_PRIVACY_TABLE: 'privacy-table',
+ AI_RESEARCH_REPLAY_KEY_TABLE: 'privacy-table',
AI_RESEARCH_REPLAY_KMS_KEY_ARN: '',
SESSION_RECORDING_ML_IMAGE_SCRUB_DLQ_TOPIC: topic,
})
@@ -21,7 +21,7 @@ describe('image scrub server startup', () => {
it('allows a disabled DLQ without privacy and continues to the S3 configuration check', async () => {
const server = new TestImageScrubServer({
- AI_RESEARCH_REPLAY_PRIVACY_TABLE: '',
+ AI_RESEARCH_REPLAY_KEY_TABLE: '',
SESSION_RECORDING_ML_IMAGE_SCRUB_DLQ_TOPIC: '',
SESSION_RECORDING_V2_S3_BUCKET: '',
})
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.ts
index 7fb86625381e..2b8a086d8d55 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.ts
@@ -52,12 +52,12 @@ export class IngestionSessionReplayMlImageScrubServer extends MlMirrorConsumerSe
protected async startServices(): Promise<void> {
if (
- this.config.AI_RESEARCH_REPLAY_PRIVACY_TABLE &&
+ this.config.AI_RESEARCH_REPLAY_KEY_TABLE &&
!this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_DLQ_TOPIC.trim()
) {
throw new Error('ML privacy-enabled image scrubber requires SESSION_RECORDING_ML_IMAGE_SCRUB_DLQ_TOPIC')
}
- if (this.config.AI_RESEARCH_REPLAY_PRIVACY_TABLE) {
+ if (this.config.AI_RESEARCH_REPLAY_KEY_TABLE) {
this.privacy = new MlPrivacyRuntime(this.config)
await this.privacy.start()
}
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.test.ts b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.test.ts
index 6eeefc4aacaa..defa2a4a7549 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.test.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.test.ts
@@ -1,7 +1,10 @@
import { KAFKA_SESSION_REPLAY_ML_BLOCK_METADATA } from '~/common/config/kafka-topics'
import { getDefaultSessionRecordingConfig } from '~/ingestion/pipelines/sessionreplay/config'
-import { buildMlMirrorServerConfig } from './ingestion-session-replay-ml-mirror-server'
+import {
+ IngestionSessionReplayMlMirrorServer,
+ buildMlMirrorServerConfig,
+} from './ingestion-session-replay-ml-mirror-server'
describe('buildMlMirrorServerConfig', () => {
it.each(['S3_PREFIX', 'PSEUDONYM_SECRET', 'PSEUDONYM_KMS_REGION', 'PSEUDONYM_KEY_FINGERPRINT'] as const)(
@@ -21,6 +24,19 @@ describe('buildMlMirrorServerConfig', () => {
}
}
)
+ it.each([
+ ['', ''],
+ ['privacy-table', ''],
+ ['', 'kms-key'],
+ ])('rejects missing privacy configuration before starting services (%s, %s)', (table, kmsKey) => {
+ expect(
+ () =>
+ new IngestionSessionReplayMlMirrorServer({
+ AI_RESEARCH_REPLAY_KEY_TABLE: table,
+ AI_RESEARCH_REPLAY_KMS_KEY_ARN: kmsKey,
+ })
+ ).toThrow('ML privacy requires a DynamoDB table and a KMS key ARN')
+ })
it('defaults the mirror to its own consumer group, distinct from the primary ingester', () => {
const config = buildMlMirrorServerConfig({})
@@ -37,11 +53,16 @@ describe('buildMlMirrorServerConfig', () => {
KAFKA_SESSION_REPLAY_ML_BLOCK_METADATA
)
expect(config.SESSION_RECORDING_ML_METADATA_PREFIX).toBe('block-metadata')
+ expect(config.AI_RESEARCH_REPLAY_S3_PREFIX).toBe('rrweb_2')
expect(config.SESSION_RECORDING_ML_PARQUET_FLUSH_INTERVAL_MS).toBeLessThan(300_000)
})
it('lets an explicit override win over the mirror default', () => {
- const config = buildMlMirrorServerConfig({ INGESTION_SESSION_REPLAY_CONSUMER_GROUP_ID: 'custom-group' })
+ const config = buildMlMirrorServerConfig({
+ INGESTION_SESSION_REPLAY_CONSUMER_GROUP_ID: 'custom-group',
+ SESSION_RECORDING_V2_S3_PREFIX: 'rrweb',
+ })
expect(config.INGESTION_SESSION_REPLAY_CONSUMER_GROUP_ID).toBe('custom-group')
+ expect(config.AI_RESEARCH_REPLAY_S3_PREFIX).toBe('rrweb_2')
})
})
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
index 8662ff9062bf..80c3e61c82c2 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
@@ -20,18 +20,18 @@ import {
} from '~/ingestion/pipelines/sessionreplay/ml-mirror/config'
import { MlBlockMetadataSink } from '~/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink'
import { createMlMirrorReplayPipeline } from '~/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline'
+import { MlPrivacyRuntime } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/runtime'
import { resolvePseudonymKey } from '~/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key'
+import { SessionFormatFileStorage } from '~/ingestion/pipelines/sessionreplay/ml-mirror/session-format-file-storage'
import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'
import { createOutputsRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/registry'
import { BlackholeSessionBatchFileStorage } from '~/ingestion/pipelines/sessionreplay/sessions/blackhole-session-batch-writer'
import { S3SessionBatchFileStorage } from '~/ingestion/pipelines/sessionreplay/sessions/s3-session-batch-writer'
import { SessionConsoleLogStore } from '~/ingestion/pipelines/sessionreplay/sessions/session-console-log-store'
-import { CleartextRecordingEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/crypto/cleartext-encryptor'
import { SessionFeatureStore } from '~/ingestion/pipelines/sessionreplay/shared/features/session-feature-store'
-import { CleartextKeyStore } from '~/ingestion/pipelines/sessionreplay/shared/keystore/cleartext-keystore'
import { buildSessionRecordingS3Client } from '~/ingestion/pipelines/sessionreplay/shared/s3-client'
+import { RedisPool } from '~/types'
-import { RedisPool } from '../types'
import { CleanupResources } from './base-server'
import { buildSessionReplayRedisPools } from './ingestion-session-replay-server'
import { MlMirrorConsumerServer } from './ml-mirror-consumer-server'
@@ -56,6 +56,7 @@ async function assertAnonymizerHealthy(anonymizer: typeof import('@posthog/repla
}
export class IngestionSessionReplayMlMirrorServer extends MlMirrorConsumerServer {
+ private readonly privacy = new MlPrivacyRuntime(this.config)
private postgres?: PostgresRouter
private producerRegistry?: KafkaProducerRegistry<SessionReplayProducerName>
private crawlHistoryClient?: DynamoDBClient
@@ -74,13 +75,27 @@ export class IngestionSessionReplayMlMirrorServer extends MlMirrorConsumerServer
const s3Client = buildSessionRecordingS3Client(this.config)
const bucket = this.config.SESSION_RECORDING_V2_S3_BUCKET
- const prefix = this.config.SESSION_RECORDING_V2_S3_PREFIX
+ const prefix = this.config.AI_RESEARCH_REPLAY_S3_PREFIX
const pseudonymSecret = await resolvePseudonymKey(this.config)
- // Anonymized blocks are written unencrypted, in a single prefix (no retention sharding).
+ // A session keeps its storage prefix across flushes and late arrivals.
const fileStorage = s3Client
- ? new S3SessionBatchFileStorage(s3Client, bucket, prefix, this.config.SESSION_RECORDING_V2_S3_TIMEOUT_MS)
+ ? new SessionFormatFileStorage(
+ new S3SessionBatchFileStorage(
+ s3Client,
+ bucket,
+ this.config.SESSION_RECORDING_V2_S3_PREFIX,
+ this.config.SESSION_RECORDING_V2_S3_TIMEOUT_MS
+ ),
+ (month) =>
+ new S3SessionBatchFileStorage(
+ s3Client,
+ bucket,
+ month ? `${prefix}/${month}` : prefix,
+ this.config.SESSION_RECORDING_V2_S3_TIMEOUT_MS
+ )
+ )
: new BlackholeSessionBatchFileStorage()
const allow = await loadAllowLists(this.buildAllowListFetcher(s3Client, bucket))
@@ -94,14 +109,14 @@ export class IngestionSessionReplayMlMirrorServer extends MlMirrorConsumerServer
logger.info('🦀', 'ml_mirror_rust_anonymizer_initialized')
// Block metadata is produced to Kafka; the dedicated Parquet-sink deployment writes it to the ML bucket.
- const metadataStore = new MlBlockMetadataSink(outputs, pseudonymSecret)
+ await this.privacy.start()
+ const metadataStore = new MlBlockMetadataSink(outputs, pseudonymSecret, this.privacy.reader)
const urlProducerEnabled =
this.config.SESSION_RECORDING_ML_URL_COLLECTION_ENABLED &&
this.config.SESSION_RECORDING_ML_URL_PRODUCER_ENABLED
const urlCrawlHistory = urlProducerEnabled ? this.buildUrlCrawlHistory() : undefined
- // Cleartext crypto: no encryption, deletions not honored (every session stays cleartext).
- const keyStore = new CleartextKeyStore()
+ const privacy = this.privacy.controller
const collaborators: SessionRecordingIngesterCollaborators = {
fileStorage,
metadataStore,
@@ -111,12 +126,13 @@ export class IngestionSessionReplayMlMirrorServer extends MlMirrorConsumerServer
enabled: false,
}),
featureStore: new SessionFeatureStore(outputs, false),
- keyStore,
- encryptor: new CleartextRecordingEncryptor(keyStore),
+ keyStore: privacy,
+ encryptor: privacy,
createPipeline: (pipelineConfig) =>
createMlMirrorReplayPipeline(
pipelineConfig,
{
+ privacy,
anonymizeMaxConcurrency: resolveMlAnonymizeMaxConcurrency(
this.config.SESSION_RECORDING_ML_ANONYMIZE_MAX_CONCURRENCY
),
@@ -202,6 +218,7 @@ export class IngestionSessionReplayMlMirrorServer extends MlMirrorConsumerServer
redisPools: [this.redisPool, this.restrictionRedisPool].filter(Boolean) as RedisPool[],
postgres: this.postgres,
additionalCleanup: async () => {
+ this.privacy.stop()
this.crawlHistoryClient?.destroy()
await this.producerRegistry?.disconnectAll()
},
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-parquet-sink-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-parquet-sink-server.ts
index 18044e5dc97e..a378af3bb72f 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-parquet-sink-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-parquet-sink-server.ts
@@ -38,7 +38,7 @@ export class IngestionSessionReplayMlParquetSinkServer extends MlMirrorConsumerS
private privacy?: MlPrivacyRuntime
protected async startServices(): Promise<void> {
- if (this.config.AI_RESEARCH_REPLAY_PRIVACY_TABLE) {
+ if (this.config.AI_RESEARCH_REPLAY_KEY_TABLE) {
this.privacy = new MlPrivacyRuntime(this.config)
await this.privacy.start()
}
diff --git a/posthog/settings/ingestion.py b/posthog/settings/ingestion.py
index 2d88039789cd..b83424e773da 100644
--- a/posthog/settings/ingestion.py
+++ b/posthog/settings/ingestion.py
@@ -152,7 +152,7 @@ BILLING_USAGE_RECORDS_HOGQL_ORGANIZATION_IDS: set[UUID | Literal["*"]] = {
if organization_id
}
-AI_RESEARCH_REPLAY_PRIVACY_TABLE = os.getenv("AI_RESEARCH_REPLAY_PRIVACY_TABLE", "")
+AI_RESEARCH_REPLAY_KEY_TABLE = os.getenv("AI_RESEARCH_REPLAY_KEY_TABLE", "")
AI_RESEARCH_REPLAY_AWS_REGION = os.getenv("AI_RESEARCH_REPLAY_AWS_REGION", "us-east-1")
AI_RESEARCH_REPLAY_DYNAMODB_ENDPOINT = os.getenv("AI_RESEARCH_REPLAY_DYNAMODB_ENDPOINT", "")
AI_RESEARCH_REPLAY_KMS_KEY_ARN = os.getenv("AI_RESEARCH_REPLAY_KMS_KEY_ARN", "")
diff --git a/posthog/tasks/test/test_scheduled.py b/posthog/tasks/test/test_scheduled.py
index d61c72afdba4..7f3a6e1c4d57 100644
--- a/posthog/tasks/test/test_scheduled.py
+++ b/posthog/tasks/test/test_scheduled.py
@@ -23,7 +23,7 @@ class TestPrivacyTaskScheduling(SimpleTestCase):
@parameterized.expand([("disabled", "", 0), ("enabled", "test-table", 1)])
def test_privacy_schedule_requires_configured_worker(self, _name: str, table: str, expected_count: int) -> None:
sender = MagicMock()
- with self.settings(AI_RESEARCH_REPLAY_PRIVACY_TABLE=table):
+ with self.settings(AI_RESEARCH_REPLAY_KEY_TABLE=table):
setup_periodic_tasks(sender)
calls = [
call
diff --git a/products/ai_training/backend/config.py b/products/ai_training/backend/config.py
index 848ca41dba40..9a4918b38a13 100644
--- a/products/ai_training/backend/config.py
+++ b/products/ai_training/backend/config.py
@@ -1,5 +1,9 @@
from django.conf import settings
+def key_table_name() -> str:
+ return str(getattr(settings, "AI_RESEARCH_REPLAY_KEY_TABLE", ""))
+
+
def privacy_enabled() -> bool:
- return bool(getattr(settings, "AI_RESEARCH_REPLAY_PRIVACY_TABLE", ""))
+ return bool(key_table_name())
diff --git a/products/ai_training/backend/management/commands/delete_ai_training_month.py b/products/ai_training/backend/management/commands/delete_ai_training_month.py
index b7617fea1d46..9396093b06b1 100644
--- a/products/ai_training/backend/management/commands/delete_ai_training_month.py
+++ b/products/ai_training/backend/management/commands/delete_ai_training_month.py
@@ -1,9 +1,9 @@
from argparse import ArgumentParser
from typing import Any
-from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
+from products.ai_training.backend.config import key_table_name
from products.ai_training.backend.privacy.reader import KEY_READ_LEASE_SECONDS
from products.ai_training.backend.privacy.store import AITrainingPrivacyStore
@@ -15,8 +15,8 @@ class Command(BaseCommand):
parser.add_argument("session_month", help="UTC session start month, in YYYY-MM format")
def handle(self, *args: Any, **options: Any) -> None:
- if not settings.AI_RESEARCH_REPLAY_PRIVACY_TABLE:
- raise CommandError("AI_RESEARCH_REPLAY_PRIVACY_TABLE is not configured")
+ if not key_table_name():
+ raise CommandError("AI_RESEARCH_REPLAY_KEY_TABLE is not configured")
try:
count = AITrainingPrivacyStore.from_settings().delete_month(options["session_month"])
except ValueError as error:
diff --git a/products/ai_training/backend/privacy/store.py b/products/ai_training/backend/privacy/store.py
index d7c067be1ff1..647ec27cd373 100644
--- a/products/ai_training/backend/privacy/store.py
+++ b/products/ai_training/backend/privacy/store.py
@@ -13,6 +13,7 @@ import boto3
import structlog
from botocore.config import Config
+from products.ai_training.backend.config import key_table_name
from products.ai_training.backend.models import AITrainingDeletionRequest
from products.ai_training.backend.privacy.reader import KEY_READ_LEASE_SECONDS
@@ -68,7 +69,7 @@ class AITrainingPrivacyStore:
endpoint_url=settings.AI_RESEARCH_REPLAY_DYNAMODB_ENDPOINT or None,
config=Config(connect_timeout=5, read_timeout=5, retries={"max_attempts": 4, "mode": "standard"}),
)
- return cls(cast(PrivacyDynamoClient, client), settings.AI_RESEARCH_REPLAY_PRIVACY_TABLE)
+ return cls(cast(PrivacyDynamoClient, client), key_table_name())
def block(self, team_id: int) -> None:
self.client.put_item(
diff --git a/products/ai_training/backend/tests/test_deletion.py b/products/ai_training/backend/tests/test_deletion.py
index 750dbd9b1c29..a9249ecbe35a 100644
--- a/products/ai_training/backend/tests/test_deletion.py
+++ b/products/ai_training/backend/tests/test_deletion.py
@@ -15,7 +15,7 @@ from products.ai_training.backend.facade.api import queue_person_training_deleti
from products.ai_training.backend.models import AITrainingDeletionRequest
-@override_settings(AI_RESEARCH_REPLAY_PRIVACY_TABLE="test-table")
+@override_settings(AI_RESEARCH_REPLAY_KEY_TABLE="test-table")
class TestAITrainingDeletionOutbox(TestCase):
def test_queue_filters_invalid_session_ids_and_batches_valid_sessions(self) -> None:
session_id = "01a09f92-e780-7000-8000-000000000001"
diff --git a/products/ai_training/backend/tests/test_privacy_store.py b/products/ai_training/backend/tests/test_privacy_store.py
index fe6e895c8222..ad1d13f6f801 100644
--- a/products/ai_training/backend/tests/test_privacy_store.py
+++ b/products/ai_training/backend/tests/test_privacy_store.py
@@ -18,7 +18,7 @@ class TestAITrainingPrivacyStore(SimpleTestCase):
self, _name: str, table: str, enabled: bool
) -> None:
with (
- self.settings(AI_RESEARCH_REPLAY_PRIVACY_TABLE=table),
+ self.settings(AI_RESEARCH_REPLAY_KEY_TABLE=table),
patch("products.ai_training.backend.tasks.tasks.AITrainingPrivacyStore.from_settings") as store,
):
signature = process_ai_training_privacy_requests.signature()
diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.md
index 41a5b145f418..843ed52b5b5a 100644
--- a/products/ai_training/docs/replay-data.md
+++ b/products/ai_training/docs/replay-data.md
@@ -9,12 +9,12 @@ Its storage and deletion implementation is separate from production session repl
## Session versions
-The cutoff is **Tuesday, 2026-09-15 at 10:00 UTC**, which is 11:00 in Europe/London.
+The cutoff is **Tuesday, 2026-09-15 at 12:00 UTC**, which is 13:00 in Europe/London.
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.
-- An invalid UUIDv7 timestamp or a start year beyond 9999 selects v1.
+- 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.
Both versions can occur in one ingestion batch.
@@ -181,6 +181,9 @@ New privacy settings use `AI_RESEARCH_REPLAY_*`:
- `IMAGE_FETCH_V2_DYNAMODB_TABLE` selects the fresh v2 frontier.
- `S3_PREFIX` selects v2 replay storage and defaults to `rrweb_2`.
+The v2 producer requires `AI_RESEARCH_REPLAY_KEY_TABLE` and `AI_RESEARCH_REPLAY_KMS_KEY_ARN` at startup.
+Missing values stop startup before it consumes Kafka messages.
+
Established HMAC settings retain their transition aliases.
When both aliases are set, the `AI_RESEARCH_REPLAY_*` value takes precedence, including an explicit empty value.
The wrapped HMAC secret keeps the single name `SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY` in both the environment and secret store.
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 119e8f741992..67792abedfb7 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -9343,7 +9343,7 @@ dependencies = [
[[package]]
name = "posthog-replay-anonymizer"
-version = "0.7.0"
+version = "0.7.1"
dependencies = [
"ahash 0.8.12",
"anyhow",
diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.toml
index 4ce401501ffc..f7679717796c 100644
--- a/rust/replay-anonymizer/Cargo.toml
+++ b/rust/replay-anonymizer/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "posthog-replay-anonymizer"
-version = "0.7.0"
+version = "0.7.1"
edition = "2021"
description = "PII scrubber for rrweb session-replay events: text/URL redaction, native image blur, and canvas/cv neutralization"
license = "MIT"