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): accept encrypted ml replay data (#98648)

Robbie8038d937d2fb
diff --git a/bin/lint_duplication.py b/bin/lint_duplication.py
index dcbddf2e9f28..896c21c656a7 100644
--- a/bin/lint_duplication.py
+++ b/bin/lint_duplication.py
@@ -164,7 +164,7 @@ def clone_key(clone: dict) -> tuple[frozenset, str]:
return pair, hashlib.sha256(clone["fragment"].encode()).hexdigest()
-def mark_new_clones(current: list[dict], baseline: list[dict]) -> None:
+def mark_new_clones(current: list[dict], baseline: list[dict], changed_files: set[str]) -> None:
"""Flag clones the baseline cannot account for, counting occurrences.
A fragment already copied once between two files is grandfathered only
@@ -174,7 +174,9 @@ def mark_new_clones(current: list[dict], baseline: list[dict]) -> None:
available = collections.Counter(clone_key(clone) for clone in baseline)
for clone in current:
key = clone_key(clone)
- if available[key] > 0:
+ if key[0].isdisjoint(changed_files):
+ clone["isNew"] = False
+ elif available[key] > 0:
available[key] -= 1
clone["isNew"] = False
else:
@@ -268,7 +270,15 @@ def main() -> int:
if scan_failed:
return 2
- mark_new_clones(current_clones, baseline_clones)
+ changed_files = set(
+ subprocess.check_output(["git", "diff", "--name-only", "-z", baseline], cwd=repo, text=True).split("\0")
+ )
+ changed_files.update(
+ subprocess.check_output(["git", "ls-files", "--others", "--exclude-standard", "-z"], cwd=repo, text=True).split(
+ "\0"
+ )
+ )
+ mark_new_clones(current_clones, baseline_clones, changed_files)
print(
f"{len(current_clones)} clones in this tree, {sum(1 for c in current_clones if c['isNew'])} not in the baseline"
)
diff --git a/bin/test/test_lint_duplication.py b/bin/test/test_lint_duplication.py
index cf256d27d41d..d6ec8025f835 100644
--- a/bin/test/test_lint_duplication.py
+++ b/bin/test/test_lint_duplication.py
@@ -173,7 +173,7 @@ class TestMarkNewClones(unittest.TestCase):
) -> None:
baseline = [make_clone("a.py", "b.py", 100) for _ in range(baseline_copies)]
current = [make_clone("a.py", "b.py", 100, is_new=False) for _ in range(current_copies)]
- mark_new_clones(current, baseline)
+ mark_new_clones(current, baseline, {"a.py"})
self.assertEqual([clone["isNew"] for clone in current], expected_is_new)
def test_an_edited_fragment_is_new_even_when_the_pair_has_a_baseline_clone(self) -> None:
@@ -181,9 +181,24 @@ class TestMarkNewClones(unittest.TestCase):
edited = make_clone("a.py", "b.py", 100)
edited["fragment"] = "y = 2\n" * 10
current = [make_clone("a.py", "b.py", 100), edited]
- mark_new_clones(current, baseline)
+ mark_new_clones(current, baseline, {"a.py"})
self.assertEqual([clone["isNew"] for clone in current], [False, True])
+ @parameterized.expand(
+ [
+ ("removed_third_copy", {"c.py"}, False),
+ ("first_copy_changed", {"a.py", "c.py"}, True),
+ ("second_copy_changed", {"b.py", "c.py"}, True),
+ ]
+ )
+ def test_changed_pairing_only_counts_when_a_copy_changed(
+ self, _name: str, changed_files: set[str], expected_is_new: bool
+ ) -> None:
+ baseline = [make_clone("a.py", "c.py", 100), make_clone("b.py", "c.py", 100)]
+ current = [make_clone("a.py", "b.py", 100)]
+ mark_new_clones(current, baseline, changed_files)
+ self.assertEqual(current[0]["isNew"], expected_is_new)
+
if __name__ == "__main__":
unittest.main()
diff --git a/docs/internal/duplication-lint.md b/docs/internal/duplication-lint.md
new file mode 100644
index 000000000000..b158911b308b
--- /dev/null
+++ b/docs/internal/duplication-lint.md
@@ -0,0 +1,12 @@
+# Duplication lint
+
+Run `python3 bin/lint_duplication.py --base origin/master` to check for new Python and TypeScript duplication.
+The check compares the working tree with the branch's merge base.
+It includes uncommitted changes and untracked files that Git does not ignore.
+
+A reported pair must include at least one changed file to count as new duplication.
+Removing a third copy can make the scanner pair two unchanged files differently, which must not fail the check.
+For pairs that include a changed file, the check still compares the fragment and its occurrence count with the baseline.
+
+The thresholds are in `bin/lint-duplication.limits.json`.
+When a new pair exceeds its threshold, extract the shared code into a helper.
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 1928b508943e..9f5b7db72ff5 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
@@ -11,10 +11,13 @@ describe('ai-training-optin-filter-step', () => {
aiTrainingOptedIn,
})
- it('passes through a team that opted into AI training', async () => {
- const input = { team: team(true) }
- const result = await step(input)
- expect(result.type).toBe(PipelineResultType.OK)
+ it('resumes the same session after the team opts in again', async () => {
+ const input = { team: team(true), sessionId: '01a0a482-5500-7000-8000-000000000001' }
+ expect((await step(input)).type).toBe(PipelineResultType.OK)
+ input.team.aiTrainingOptedIn = false
+ expect((await step(input)).type).toBe(PipelineResultType.DROP)
+ input.team.aiTrainingOptedIn = true
+ expect((await step(input)).type).toBe(PipelineResultType.OK)
})
it('drops a team that did not opt in', async () => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts
index ce1b5bcd389e..8cfb72fc8492 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts
@@ -2,6 +2,8 @@ import type { UrlPolicyDecline } from '@posthog/replay-anonymizer'
import { parseJSON } from '~/common/utils/json-parse'
import { parseImageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'
+import type { MlDataKey } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/crypto'
+import { identityDigest } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/schema'
import { ImageFetchBlockReason, isImageFetchBlockReason } from './block-reason'
import { tryCanonicalizeUrl } from './politeness-key'
@@ -29,6 +31,7 @@ export type StoredRepublishReason =
export type RepublishReason = StoredRepublishReason
export interface FetchCandidate {
+ privacyKey?: MlDataKey
originalRef: string
currentUrl: string
host: string
@@ -294,3 +297,9 @@ export function serializeFrontierRecord(candidates: FetchCandidate[]): Buffer {
}
return Buffer.from(JSON.stringify(record))
}
+
+export function fetchCandidateHistoryKey(candidate: FetchCandidate): string {
+ return candidate.privacyKey?.identity.sessionId
+ ? `${candidate.originalRef}:session:${identityDigest(candidate.privacyKey.identity.sessionId)}`
+ : candidate.originalRef
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.ts
index c79e8e10903e..f4696ce715ff 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.ts
@@ -1,3 +1,4 @@
+import { fetchCandidateHistoryKey } from './collected-urls-record'
import { FetchCandidate } from './collected-urls-record'
export interface FetchCandidateLease {
@@ -143,12 +144,15 @@ export function deduplicateFetchCandidates(candidates: FetchCandidate[]): Dedupl
const candidatesByCanonicalRef = new Map<string, FetchCandidate>()
let duplicateCount = 0
for (const candidate of candidates) {
- const existing = candidatesByCanonicalRef.get(candidate.originalRef)
+ const existing = candidatesByCanonicalRef.get(fetchCandidateHistoryKey(candidate))
if (existing) {
duplicateCount += 1
- candidatesByCanonicalRef.set(candidate.originalRef, mergeDuplicateFetchCandidates(existing, candidate))
+ candidatesByCanonicalRef.set(
+ fetchCandidateHistoryKey(candidate),
+ mergeDuplicateFetchCandidates(existing, candidate)
+ )
} else {
- candidatesByCanonicalRef.set(candidate.originalRef, candidate)
+ candidatesByCanonicalRef.set(fetchCandidateHistoryKey(candidate), candidate)
}
}
return { candidates: [...candidatesByCanonicalRef.values()], duplicateCount }
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.ts
index 3a97a0db014c..0b50532fbd88 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.ts
@@ -719,6 +719,22 @@ describe('FetchRunner', () => {
expect(attempt.history?.cache?.lastModified).toBeUndefined()
})
+ it.each([
+ ['2023-11', undefined, Date.UTC(2023, 11, 9)],
+ ['2024-02', undefined, Date.UTC(2024, 2, 9)],
+ ['2023-11', 'max-age=60', NOW_MS + 60_000],
+ ['2023-11', 'max-age=99999999', Date.UTC(2023, 11, 9)],
+ ['2023-11', 'no-store', NOW_MS],
+ ])('expires month %s history with cache control %s', async (month, cacheControl, expiresAt) => {
+ const harness = build({ cache: { requestTimeMs: NOW_MS, responseTimeMs: NOW_MS, cacheControl } })
+ const [attempt] = await harness.runner.run(
+ [candidate({ originalRef: `imageurl:v2:7:${month}:${'a'.repeat(22)}` })],
+ new Map()
+ )
+ expect(attempt.history?.nextFetchAtMs).toBe(expiresAt)
+ expect(attempt.history?.storageExpiresAtMs).toBe(expiresAt)
+ })
+
it('extends URL history to the end of explicit freshness', async () => {
const fortyDaysMs = 40 * 24 * 60 * 60 * 1000
const harness = build({
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.ts
index f312969e67c5..208eae0e1b5b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.ts
@@ -2,12 +2,9 @@ import { ConcurrencyController } from '~/common/utils/concurrencyController'
import { logger } from '~/common/utils/logger'
import type { ImageFetchBlockReason } from './block-reason'
+import { fetchCandidateHistoryKey } from './collected-urls-record'
import { FetchCandidate, MAX_HOPS, RepublishReason } from './collected-urls-record'
-import {
- ConfigurationPolicyPass,
- ConfigurationPolicyService,
- explicitFreshnessLifetimeMs,
-} from './configuration-policy'
+import { ConfigurationPolicyPass, ConfigurationPolicyService } from './configuration-policy'
import { ConfigurationCacheItem, CrawlHistoryItem, HttpCacheMetadata, UrlCrawlHistoryItem } from './crawl-history'
import { FetchCandidateLease, FetchCandidateQueue } from './fetch-candidate-queue'
import { FrontierPublisher, RepublishBatch, RepublishResult } from './frontier-publisher'
@@ -24,6 +21,7 @@ import { OriginRequestScheduler } from './origin-request-scheduler'
import { canonicalizeUrl } from './politeness-key'
import { ImageFetchProcessingMetrics } from './processing-metrics'
import { ImageFetchTopHogMetrics } from './tophog-metrics'
+import { urlHistoryExpiresAtMs } from './url-history-expiry'
export type ShedReason =
| 'breaker_open'
@@ -353,7 +351,7 @@ export class FetchRunner implements FetchPass {
)
}
- const previous = stored.get(candidate.originalRef)
+ const previous = stored.get(fetchCandidateHistoryKey(candidate))
const previousUrl = previous?.kind === 'url' ? previous : undefined
const result = await ImageFetchProcessingMetrics.measure('candidate_fetch', () =>
this.fetcher.fetch(candidate.currentUrl, {
@@ -609,9 +607,7 @@ export class FetchRunner implements FetchPass {
refusalReason: FetchRefusalReason | 'none' = 'none'
): FetchAttempt {
const nowMs = Date.now()
- const minimumNextFetchAtMs = nowMs + this.options.seenTtlSeconds * 1000
- const explicitNextFetchAtMs = cache ? nowMs + explicitFreshnessLifetimeMs(cache, nowMs) : 0
- const nextFetchAtMs = Math.max(minimumNextFetchAtMs, explicitNextFetchAtMs)
+ const nextFetchAtMs = urlHistoryExpiresAtMs(candidate.originalRef, nowMs, this.options.seenTtlSeconds, cache)
ImageFetchRequestMetrics.observeCompletedUrl(
outcome,
refusalReason,
@@ -627,7 +623,7 @@ export class FetchRunner implements FetchPass {
lost: false,
history: {
kind: 'url',
- key: candidate.originalRef,
+ key: fetchCandidateHistoryKey(candidate),
nextFetchAtMs,
storageExpiresAtMs: nextFetchAtMs,
outcome: String(outcome),
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-dead-letter-sink.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-dead-letter-sink.ts
index fabe1655cdc0..39235282c040 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-dead-letter-sink.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-dead-letter-sink.ts
@@ -1,5 +1,6 @@
import { Message } from 'node-rdkafka'
+import { parseKafkaHeaders } from '~/common/kafka/consumer/consumer-v1'
import { KafkaProducerWrapper } from '~/common/kafka/producer'
import { parseJSON } from '~/common/utils/json-parse'
@@ -29,6 +30,7 @@ export class KafkaFrontierDeadLetterSink implements FrontierDeadLetterSink {
key: message.key ?? null,
value: message.value,
headers: {
+ ...parseKafkaHeaders(message.headers),
'dlq-reason': reason,
'frontier-record-version': classifyFrontierRecordVersion(message.value),
'source-topic': message.topic,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.test.ts
index 04d8ae8075a2..4e210fc7b4c6 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.test.ts
@@ -422,6 +422,7 @@ describe('FrontierPublisher', () => {
key: `imageurl:${'a'.repeat(22)}`,
value: Buffer.from('image'),
headers: {
+ ai_research_ingestion_version: '1',
'content-type': 'image/png',
'content-encoding': 'gzip',
'capture-timestamp-ms': '1700000000000',
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts
index b3e55f1c4a8e..f550165b5787 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts
@@ -2,6 +2,7 @@ import { KafkaProducerWrapper } from '~/common/kafka/producer'
import { ConcurrencyController } from '~/common/utils/concurrencyController'
import { logger } from '~/common/utils/logger'
import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport'
+import { encryptedKafkaValue } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/transport'
import {
FetchCandidate,
@@ -110,7 +111,7 @@ export class FrontierPublisher {
if (!result.bytes || !result.contentType) {
throw new Error('an image publish needs response bytes and a content type')
}
- const bytes = result.bytes
+ const encrypted = encryptedKafkaValue(candidate.privacyKey, 'image-source', result.bytes, candidate.originalRef)
const headers: Record<string, string> = {
'content-type': result.contentType,
[CAPTURE_TIMESTAMP_HEADER]: String(candidate.firstSeenAtMs),
@@ -128,8 +129,8 @@ export class FrontierPublisher {
this.producer.produce({
topic: this.options.scrubTopic,
key: Buffer.from(candidate.originalRef),
- value: bytes,
- headers,
+ value: encrypted.value,
+ headers: { ...headers, ...encrypted.headers },
}),
}
)
@@ -229,7 +230,7 @@ class BufferedRepublishBatch implements RepublishBatch {
private planMessages(): PlannedRepublishMessage[] {
const groups = new Map<string, PendingRepublish[]>()
for (const item of this.pending) {
- const key = `${item.destination.topic}\0${item.candidate.registrableDomain}`
+ const key = `${item.destination.topic}\0${item.candidate.registrableDomain}\0${JSON.stringify(item.candidate.privacyKey?.identity ?? null)}`
const group = groups.get(key)
if (group) {
group.push(item)
@@ -303,7 +304,11 @@ class BufferedRepublishBatch implements RepublishBatch {
await this.producer.produce({
topic: plan.topic,
key: Buffer.from(plan.registrableDomain),
- value: serializeFrontierRecord(plan.candidates),
+ ...encryptedKafkaValue(
+ plan.candidates[0].privacyKey,
+ 'image-frontier',
+ serializeFrontierRecord(plan.candidates)
+ ),
})
return 'published'
} catch {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer.ts
index 2f812046d8a9..518253e8813a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer.ts
@@ -1,5 +1,6 @@
import { Message } from 'node-rdkafka'
+import { parseKafkaHeaders } from '~/common/kafka/consumer/consumer-v1'
import { KafkaProducerWrapper } from '~/common/kafka/producer'
import { logger } from '~/common/utils/logger'
import { delay } from '~/common/utils/utils'
@@ -119,6 +120,7 @@ export class RetryDelayConsumer {
topic: this.options.frontierTopic,
key: message.key,
value: message.value,
+ headers: parseKafkaHeaders(message.headers),
})
} catch (error) {
logger.warn('🌐', 'ml_image_fetch_retry_release_failed', {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts
index decf4c86223a..90a5aa69d020 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts
@@ -1,6 +1,7 @@
import { Message } from 'node-rdkafka'
import { register } from 'prom-client'
+import { INGESTION_VERSION_HEADER } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/schema'
import { RecordedTopHogMetric, createRecordingTopHog } from '~/tests/helpers/tophog'
import { FetchCandidate, MAX_HOPS, serializeFrontierRecord } from './collected-urls-record'
@@ -124,6 +125,21 @@ function build(dryRun = false, deadLettersEnabled = true): Harness {
describe('UrlFetchConsumer', () => {
afterEach(() => jest.restoreAllMocks())
+ it('dead-letters an unsupported version while processing valid records in the same batch', async () => {
+ const harness = build()
+ const invalid = { ...message([candidate('a')]), headers: [{ [INGESTION_VERSION_HEADER]: Buffer.from('3') }] }
+ await harness.consumer.handleBatch([invalid, message([candidate('b')])], NOW_MS)
+ expect(harness.park).toHaveBeenCalledWith(invalid, 'malformed')
+ expect(harness.run.mock.calls[0][0].map((item) => item.originalRef)).toEqual([candidate('b').originalRef])
+ })
+
+ it('fails on v2 without privacy configuration instead of dead-lettering the record', async () => {
+ const harness = build()
+ const v2 = { ...message([candidate('a')]), headers: [{ [INGESTION_VERSION_HEADER]: Buffer.from('2') }] }
+ await expect(harness.consumer.handleBatch([v2], NOW_MS)).rejects.toThrow('requires privacy configuration')
+ expect(harness.park).not.toHaveBeenCalled()
+ })
+
it.each([Number.NaN, 0, 3_599, 3_600.5])('refuses an invalid crawl-history TTL of %p', (seenTtlSeconds) => {
expect(
() =>
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts
index 2f993bed6b6f..4fcba989d554 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts
@@ -2,7 +2,13 @@ import { Message } from 'node-rdkafka'
import pLimit from 'p-limit'
import { logger } from '~/common/utils/logger'
+import {
+ MlKafkaEncryption,
+ ingestionVersion,
+ validateImageOwner,
+} from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/transport'
+import { fetchCandidateHistoryKey } from './collected-urls-record'
import {
FetchCandidate,
MAX_HOPS,
@@ -25,6 +31,7 @@ import { FrontierPublisher, RepublishBatch } from './frontier-publisher'
import { ImageFetchConsumerMetrics, ImageFetchRequestMetrics } from './metrics'
import { ImageFetchProcessingMetrics } from './processing-metrics'
import { ImageFetchTopHogMetrics } from './tophog-metrics'
+import { urlHistoryExpiresAtMs } from './url-history-expiry'
const ONE_HOUR_MS = 60 * 60 * 1000
const REPUBLISH_DEADLINE_FROM_BATCH_START_MS = 200_000
@@ -48,7 +55,8 @@ export class UrlFetchConsumer {
private readonly options: UrlFetchConsumerOptions,
private readonly runner?: FetchPass,
private readonly deadLetters: FrontierDeadLetterSink | null = null,
- private readonly topHogMetrics?: ImageFetchTopHogMetrics
+ private readonly topHogMetrics?: ImageFetchTopHogMetrics,
+ private readonly privacy?: MlKafkaEncryption
) {
if (!Number.isInteger(options.seenTtlSeconds) || options.seenTtlSeconds < 60 * 60) {
throw new Error('AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS must be at least 3600')
@@ -60,6 +68,23 @@ export class UrlFetchConsumer {
}
public async handleBatch(messages: Message[], nowMs: number): Promise<void> {
+ const decoded = this.privacy
+ ? await this.privacy.read(messages, 'image-frontier')
+ : messages.map((message) => {
+ let version: 1 | 2
+ try {
+ version = ingestionVersion(message)
+ } catch (error) {
+ if (error instanceof Error && error.message === 'Unsupported ML ingestion version') {
+ return { message, original: message, key: undefined, invalid: true }
+ }
+ throw error
+ }
+ if (version === 2) {
+ throw new Error('ML v2 frontier requires privacy configuration')
+ }
+ return { message, original: message, key: undefined, invalid: undefined }
+ })
const startedAt = process.hrtime.bigint()
const republishDeadlineAtMonotonicMs = performance.now() + REPUBLISH_DEADLINE_FROM_BATCH_START_MS
const drops = new Map<UrlDropReason, number>()
@@ -75,10 +100,14 @@ export class UrlFetchConsumer {
const stage = ImageFetchProcessingMetrics.start('batch_parse')
try {
- for (const message of messages) {
+ for (const { message, original, key, invalid } of decoded) {
+ if (invalid) {
+ rejectedRecords.push({ message: original, reasons: ['malformed'] })
+ continue
+ }
const parsed = this.parse(message)
if (!parsed.ok) {
- rejectedRecords.push({ message, reasons: [parsed.reason] })
+ rejectedRecords.push({ message: original, reasons: [parsed.reason] })
continue
}
ImageFetchConsumerMetrics.observeRecord(parsed.urlCount)
@@ -89,24 +118,32 @@ export class UrlFetchConsumer {
)
if (parsed.rejected.length > 0) {
rejectedRecords.push({
- message,
+ message: original,
reasons: parsed.rejected.map((rejected) => rejected.reason),
})
}
for (const { reason } of parsed.skipped) {
skips.set(reason, (skips.get(reason) ?? 0) + 1)
}
+ try {
+ for (const candidate of parsed.candidates) {
+ validateImageOwner(candidate.originalRef, key)
+ }
+ } catch {
+ rejectedRecords.push({ message: original, reasons: ['bad_ref'] })
+ continue
+ }
for (const candidate of parsed.candidates) {
- const partitionCandidate = { ...candidate, sourcePartitions: [message.partition] }
- const existing = candidatesByRef.get(partitionCandidate.originalRef)
+ const partitionCandidate = { ...candidate, privacyKey: key, sourcePartitions: [message.partition] }
+ const existing = candidatesByRef.get(fetchCandidateHistoryKey(partitionCandidate))
if (existing) {
dedupedInBatch += 1
candidatesByRef.set(
- partitionCandidate.originalRef,
+ fetchCandidateHistoryKey(partitionCandidate),
mergeDuplicateFetchCandidates(existing, partitionCandidate)
)
} else {
- candidatesByRef.set(partitionCandidate.originalRef, partitionCandidate)
+ candidatesByRef.set(fetchCandidateHistoryKey(partitionCandidate), partitionCandidate)
}
}
}
@@ -149,7 +186,7 @@ export class UrlFetchConsumer {
}
const keys = [
- ...candidates.map((candidate) => candidate.originalRef),
+ ...candidates.map(fetchCandidateHistoryKey),
...[...origins.keys()].flatMap((origin) => [
configurationCacheKey(origin, 'robots'),
configurationCacheKey(origin, 'tdmrep'),
@@ -162,7 +199,7 @@ export class UrlFetchConsumer {
const fetchable: FetchCandidate[] = []
const notReady: FetchCandidate[] = []
for (const candidate of candidates) {
- const history = stored.get(candidate.originalRef)
+ const history = stored.get(fetchCandidateHistoryKey(candidate))
if (history?.kind === 'url' && history.nextFetchAtMs > nowMs) {
ImageFetchConsumerMetrics.incDeduped('store', 1)
for (const sourcePartition of candidate.sourcePartitions ?? []) {
@@ -421,10 +458,10 @@ export class UrlFetchConsumer {
}
private terminalHistory(candidate: FetchCandidate, outcome: AttemptOutcome, nowMs: number): UrlCrawlHistoryItem {
- const nextFetchAtMs = nowMs + this.options.seenTtlSeconds * 1000
+ const nextFetchAtMs = urlHistoryExpiresAtMs(candidate.originalRef, nowMs, this.options.seenTtlSeconds)
return {
kind: 'url',
- key: candidate.originalRef,
+ key: fetchCandidateHistoryKey(candidate),
nextFetchAtMs,
storageExpiresAtMs: nextFetchAtMs,
outcome,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-history-expiry.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-history-expiry.ts
new file mode 100644
index 000000000000..046da5e3b0f5
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-history-expiry.ts
@@ -0,0 +1,29 @@
+import { parseImageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'
+
+import { explicitFreshnessLifetimeMs } from './configuration-policy'
+import { HttpCacheMetadata } from './crawl-history'
+
+export function urlHistoryExpiresAtMs(
+ ref: string,
+ nowMs: number,
+ seenTtlSeconds: number,
+ cache?: HttpCacheMetadata
+): number {
+ const minimumNextFetchAtMs = nowMs + seenTtlSeconds * 1000
+ const explicitNextFetchAtMs = cache ? nowMs + explicitFreshnessLifetimeMs(cache, nowMs) : 0
+ const month = parseImageRef(ref)?.sessionMonth
+ const partitionExpiresAtMs = month ? Date.parse(`${month}-01T00:00:00Z`) : undefined
+ let nextFetchAtMs = Math.max(minimumNextFetchAtMs, explicitNextFetchAtMs)
+ if (partitionExpiresAtMs !== undefined) {
+ const end = new Date(partitionExpiresAtMs)
+ end.setUTCMonth(end.getUTCMonth() + 1)
+ end.setUTCDate(end.getUTCDate() + 8)
+ const hasExplicitFreshness =
+ cache?.expires !== undefined ||
+ /(?:^|,)\s*(?:s-maxage|max-age|no-cache|no-store|private|must-revalidate)(?:\s*(?:=|,|$))/i.test(
+ cache?.cacheControl ?? ''
+ )
+ nextFetchAtMs = Math.min(end.getTime(), hasExplicitFreshness ? explicitNextFetchAtMs : Infinity)
+ }
+ return nextFetchAtMs
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/versioned-crawl-history.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/versioned-crawl-history.test.ts
new file mode 100644
index 000000000000..2796a3a8dc6d
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/versioned-crawl-history.test.ts
@@ -0,0 +1,49 @@
+import { CrawlHistoryItem, CrawlHistoryStore, configurationCacheKey } from './crawl-history'
+import { VersionedCrawlHistory } from './versioned-crawl-history'
+
+class MemoryHistory implements CrawlHistoryStore {
+ readonly items = new Map<string, CrawlHistoryItem>()
+ read(keys: string[]): Promise<Map<string, CrawlHistoryItem>> {
+ return Promise.resolve(
+ new Map(keys.flatMap((key) => (this.items.has(key) ? [[key, this.items.get(key)!] as const] : [])))
+ )
+ }
+ write(items: CrawlHistoryItem[]): Promise<void> {
+ for (const item of items) {
+ this.items.set(item.key, item)
+ }
+ return Promise.resolve()
+ }
+}
+
+describe('VersionedCrawlHistory', () => {
+ it('isolates monthly image history while sharing robots and tdmrep by origin', async () => {
+ const shared = new MemoryHistory()
+ const images = new MemoryHistory()
+ const history = new VersionedCrawlHistory(shared, images)
+ const september = 'imageurl:v2:7:2026-09:aaaaaaaaaaaaaaaaaaaaaa'
+ const october = september.replace('2026-09', '2026-10')
+ const origin = 'https://example.com'
+ const policies = (['robots', 'tdmrep'] as const).map((kind) => ({
+ kind,
+ key: configurationCacheKey(origin, kind),
+ origin,
+ status: 'available' as const,
+ fetchedAtMs: 1,
+ refreshAtMs: 100,
+ freshUntilMs: 100,
+ retryAtMs: 0,
+ storageExpiresAtMs: 1000,
+ }))
+ await history.write([
+ { kind: 'url', key: september, nextFetchAtMs: 100, storageExpiresAtMs: 1000, outcome: 'fetched' },
+ ...policies,
+ ])
+ const result = await history.read([september, october, ...policies.map((item) => item.key)])
+ expect(result.has(september)).toBe(true)
+ expect(result.has(october)).toBe(false)
+ expect([...shared.items.keys()]).toEqual(policies.map((item) => item.key))
+ expect(policies.every((item) => result.get(item.key) === item)).toBe(true)
+ expect([...images.items.keys()]).toEqual([september])
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/versioned-crawl-history.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/versioned-crawl-history.ts
new file mode 100644
index 000000000000..3ec863afceb6
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/versioned-crawl-history.ts
@@ -0,0 +1,22 @@
+import { CrawlHistoryItem, CrawlHistoryStore } from './crawl-history'
+
+export class VersionedCrawlHistory implements CrawlHistoryStore {
+ constructor(
+ private readonly legacy: CrawlHistoryStore,
+ private readonly v2: CrawlHistoryStore
+ ) {}
+
+ public async read(keys: string[]): Promise<Map<string, CrawlHistoryItem>> {
+ const scoped = keys.filter((key) => key.startsWith('imageurl:v2:'))
+ const legacy = keys.filter((key) => !key.startsWith('imageurl:v2:'))
+ const results = await Promise.all([this.legacy.read(legacy), this.v2.read(scoped)])
+ return new Map(results.flatMap((result) => [...result]))
+ }
+
+ public async write(items: CrawlHistoryItem[]): Promise<void> {
+ await Promise.all([
+ this.legacy.write(items.filter((item) => !item.key.startsWith('imageurl:v2:'))),
+ this.v2.write(items.filter((item) => item.key.startsWith('imageurl:v2:'))),
+ ])
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref.ts
index 331dcb5cdcd9..7d41e30db895 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref.ts
@@ -1,10 +1,9 @@
// The inline-image ref format shared by the producer, this consumer, and training joins.
-// pseudo_team is the non-reversible HMAC team pseudonym from ml-mirror/pseudonymize.ts. The hash
-// half is keyed with a per-team HMAC, derived alongside the pseudonym, so the
-// unencrypted bucket carries no unkeyed content digest — a plain sha256 would let a bucket reader
-// confirm whether specific known bytes appeared in a session, and correlate identical images across
-// teams. The consumer trusts the producer's ref (it is the only writer) and never recomputes the
-// hash; the Rust producer implementation is pinned to this one by the shared image-hash.json fixture.
+// The hash uses a per-team HMAC, so the unencrypted bucket carries no unkeyed content digest.
+// A plain sha256 would let a bucket reader confirm whether known bytes appeared in a session
+// and correlate identical images across teams. The consumer trusts the producer (the only writer)
+// and never recomputes the hash. The shared image-hash.json fixture pins the Rust construction.
+// Legacy refs retain their team pseudonym so queued images still join to their replay blocks.
import { createHmac } from 'node:crypto'
const PREFIX = 'image'
@@ -17,7 +16,7 @@ const PREFIX = 'image'
* silent mis-join rather than an error.
*/
const URL_PREFIX = 'imageurl'
-const CONTENT_REF_RE = /^image:([0-9a-f]{32}):([A-Za-z0-9_-]{22})$/
+const CONTENT_REF_RE = /^image:([1-9][0-9]{0,15}|[0-9a-f]{32}):([A-Za-z0-9_-]{22})$/
const GLOBAL_URL_REF_RE = /^imageurl:([A-Za-z0-9_-]{22})$/
const LEGACY_URL_REF_RE = /^imageurl:([0-9a-f]{32}):([A-Za-z0-9_-]{22})$/
@@ -25,8 +24,8 @@ export function hashImageBytes(contentKey: string | Buffer, bytes: Buffer): stri
return createHmac('sha256', contentKey).update(bytes).digest('base64url').slice(0, 22)
}
-export function imageRef(pseudoTeam: string, hash: string): string {
- return `${PREFIX}:${pseudoTeam}:${hash}`
+export function imageRef(teamId: string, hash: string): string {
+ return `${PREFIX}:${teamId}:${hash}`
}
export function urlRef(hash: string): string {
@@ -34,16 +33,38 @@ export function urlRef(hash: string): string {
}
export function isImageRef(s: string): boolean {
- return CONTENT_REF_RE.test(s) || GLOBAL_URL_REF_RE.test(s) || LEGACY_URL_REF_RE.test(s)
+ return parseImageRef(s) !== null
+}
+
+export function isRawTeamId(value: unknown): boolean {
+ return typeof value === 'string' && /^[1-9][0-9]{0,15}$/.test(value) && Number.isSafeInteger(Number(value))
}
/** Parses either kind of ref. `source` says which promise the hash carries. */
-export function parseImageRef(
- s: string
-): { pseudoTeam: string; hash: string; source: 'bytes' } | { pseudoTeam?: string; hash: string; source: 'url' } | null {
+export function parseImageRef(s: string): {
+ teamId?: string
+ pseudoTeam?: string
+ hash: string
+ source: 'bytes' | 'url'
+ version?: 2
+ sessionMonth?: string
+} | null {
+ const scoped = /^(image|imageurl):v2:([1-9][0-9]{0,15}):([0-9]{4}-(?:0[1-9]|1[0-2])):([A-Za-z0-9_-]{22})$/.exec(s)
+ if (scoped && isRawTeamId(scoped[2])) {
+ return {
+ teamId: scoped[2],
+ sessionMonth: scoped[3],
+ hash: scoped[4],
+ source: scoped[1] === 'image' ? 'bytes' : 'url',
+ version: 2,
+ }
+ }
const content = CONTENT_REF_RE.exec(s)
if (content) {
- return { pseudoTeam: content[1], hash: content[2], source: 'bytes' }
+ if (isRawTeamId(content[1])) {
+ return { teamId: content[1], hash: content[2], source: 'bytes' }
+ }
+ return content[1].length === 32 ? { pseudoTeam: content[1], hash: content[2], source: 'bytes' } : null
}
const globalUrl = GLOBAL_URL_REF_RE.exec(s)
if (globalUrl) {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.ts
index 71174fa66d2c..53b86862c560 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.ts
@@ -3,6 +3,7 @@ import { Message } from 'node-rdkafka'
import { parseKafkaHeaders } from '~/common/kafka/consumer/consumer-v1'
import { KafkaProducerWrapper } from '~/common/kafka/producer'
import { logger } from '~/common/utils/logger'
+import { INGESTION_VERSION_HEADER } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/schema'
import { REPLAY_COUNT_HEADER } from './image-batcher'
import { CAPTURE_TIMESTAMP_HEADER, CONTENT_ENCODING_HEADER, CONTENT_TYPE_HEADER } from './image-transport'
@@ -60,6 +61,11 @@ export async function replayBatch(
key: Buffer.from(ref),
value: message.value,
headers: {
+ ...Object.fromEntries(
+ [INGESTION_VERSION_HEADER]
+ .filter((header) => headers[header] !== undefined)
+ .map((header) => [header, headers[header]])
+ ),
...(headers[CONTENT_TYPE_HEADER] ? { [CONTENT_TYPE_HEADER]: headers[CONTENT_TYPE_HEADER] } : {}),
...(headers[CONTENT_ENCODING_HEADER]
? { [CONTENT_ENCODING_HEADER]: headers[CONTENT_ENCODING_HEADER] }
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts
index b2fc445f6512..f5be849ae434 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts
@@ -1,6 +1,11 @@
import { Message, MessageHeader, TopicPartitionOffset } from 'node-rdkafka'
import { gzipSync } from 'node:zlib'
+import { MlKeyReader } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/reader'
+import { MlPrivacyRuntime } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/runtime'
+import { INGESTION_VERSION_HEADER } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/schema'
+import { MlKafkaEncryption } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/transport'
+
import { hashImageBytes, imageRef, urlRef } from './content-ref'
import { ImageBatcher, OffsetStore } from './image-batcher'
import { ImageShardStore, ScrubbedImage, ScrubbedUrlImage, UrlImageWriteOutcome } from './image-shard-store'
@@ -80,7 +85,64 @@ const options = {
describe('ImageBatcher', () => {
afterEach(() => jest.restoreAllMocks())
- it('scrubs a multi-team batch into one shard for the flush, storing offsets after', async () => {
+ it.each([false, true])(
+ 'retries malformed encrypted image parking and supports shutdown (stop: %s)',
+ async (stop) => {
+ jest.useFakeTimers()
+ try {
+ const store = new FakeStore()
+ const offsets = new FakeOffsets()
+ const park = jest.fn().mockRejectedValueOnce(new Error('dlq unavailable')).mockResolvedValue(undefined)
+ const privacy = {
+ kafka: new MlKafkaEncryption({
+ read: jest.fn().mockResolvedValue(new Map()),
+ } as unknown as MlKeyReader),
+ } as MlPrivacyRuntime
+ const batcher = new ImageBatcher(
+ store as unknown as ImageShardStore,
+ offsets,
+ scrubClient,
+ options,
+ 0,
+ { park },
+ privacy
+ )
+ const invalid = msg(0, 0, pt(1), Buffer.from('invalid envelope'), undefined, [
+ { [INGESTION_VERSION_HEADER]: Buffer.from('2') },
+ ])
+ const batch = batcher.handleBatch([invalid], 1)
+ await jest.advanceTimersByTimeAsync(0)
+ expect(park).toHaveBeenCalledTimes(1)
+ expect(offsets.received).toEqual([])
+ if (stop) {
+ batcher.stop()
+ } else {
+ await jest.advanceTimersByTimeAsync(500)
+ }
+ await expect(batch).resolves.toBeUndefined()
+ expect(park).toHaveBeenCalledTimes(stop ? 1 : 2)
+ expect(park.mock.calls[0][0]).toEqual({
+ ref: invalid.key!.toString(),
+ bytes: invalid.value,
+ headers: { [INGESTION_VERSION_HEADER]: '2' },
+ detail: {
+ reason: 'invalid_encryption',
+ sourceTopic: invalid.topic,
+ sourcePartition: 0,
+ sourceOffset: 0,
+ },
+ })
+ expect(store.writes).toEqual([])
+ if (!stop) {
+ expect(offsets.received.flat().map((offset) => offset.offset)).toEqual([1])
+ }
+ } finally {
+ jest.useRealTimers()
+ }
+ }
+ )
+
+ it.each([false, true])('scrubs mixed teams and separates legacy records (mixed formats: %s)', async (mixed) => {
const store = new FakeStore()
const offsets = new FakeOffsets()
const observeCaptureToS3 = jest.spyOn(ImageScrubConsumerMetrics, 'observeCaptureToS3').mockImplementation()
@@ -90,13 +152,22 @@ describe('ImageBatcher', () => {
await batcher.handleBatch(
[
msg(0, 0, pt(1), Buffer.from('a'), undefined, captureHeader),
- msg(0, 1, pt(2), Buffer.from('b'), undefined, captureHeader),
+ msg(0, 1, mixed ? '42' : pt(2), Buffer.from('b'), undefined, captureHeader),
],
1
)
- expect(store.writes).toHaveLength(1)
- expect(store.writes[0].map((i) => i.pseudoTeam).sort()).toEqual([pt(1), pt(2)])
+ expect(store.writes).toHaveLength(mixed ? 2 : 1)
+ expect(
+ store.writes
+ .flat()
+ .map((i) => i.teamId ?? i.pseudoTeam)
+ .sort()
+ ).toEqual([pt(1), mixed ? '42' : pt(2)])
+ if (mixed) {
+ expect(store.writes.flat().find((image) => image.teamId === '42')).toBeDefined()
+ expect(store.writes.flat().find((image) => image.pseudoTeam === pt(1))).toBeDefined()
+ }
expect(offsets.stored).toBe(1)
expect(observeCaptureToS3).toHaveBeenCalledTimes(2)
expect(observeCaptureToS3).toHaveBeenNthCalledWith(1, 'inline', CAPTURED_AT, expect.any(Number))
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts
index b35d14f09ed7..5176a921799a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts
@@ -1,8 +1,16 @@
import { LibrdKafkaError, Message, TopicPartitionOffset } from 'node-rdkafka'
+import { setTimeout as waitForRetry } from 'node:timers/promises'
import { findOffsetsToCommit, parseKafkaHeaders } from '~/common/kafka/consumer/consumer-v1'
import { ConcurrencyController } from '~/common/utils/concurrencyController'
import { logger } from '~/common/utils/logger'
+import { MlPrivacyRuntime } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/runtime'
+import {
+ INGESTION_VERSION_HEADER,
+ imageKeyId,
+ tableKeyString,
+} from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/schema'
+import { ingestionVersion } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/transport'
import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'
import { parseImageRef } from './content-ref'
@@ -64,8 +72,11 @@ const REVOKED_PARTITION_CODES = new Set([
/** The batch index is what lets offsets advance across the messages planning skipped. */
interface PlannedScrub {
+ sessionMonth?: string
+ encryptedValue?: Buffer
index: number
ref: string
+ teamId?: string
pseudoTeam?: string
hash: string
source: 'bytes' | 'url'
@@ -155,7 +166,8 @@ export class ImageBatcher {
private readonly scrubClient: ScrubClient,
private readonly options: ImageBatcherOptions,
nowMs: number,
- private readonly deadLetters: DeadLetterSink | null = null
+ private readonly deadLetters: DeadLetterSink | null = null,
+ private readonly privacy?: MlPrivacyRuntime
) {
// 0 would admit nothing and spin the loop forever; NaN would skip it entirely, committing
// offsets for unprocessed messages. Fail at boot rather than either.
@@ -187,12 +199,66 @@ export class ImageBatcher {
if (this.stopping) {
return
}
+ const controller = new AbortController()
+ this.activeBatch = controller
+ this.partitionsRevoked = false
+ try {
+ await this.handleActiveBatch(messages, nowMs, controller)
+ } catch (error) {
+ if (!(this.stopping && error instanceof ScrubAborted)) {
+ throw error
+ }
+ } finally {
+ // Cleared here rather than on the success path: a throwing batch that left this set would
+ // have shutdown abort a controller belonging to a batch that is already over.
+ this.activeBatch = null
+ }
+ }
+
+ private async handleActiveBatch(messages: Message[], nowMs: number, controller: AbortController): Promise<void> {
// Skips resolve up front so the window only ever holds real work: a duplicate admitted into a
// slot would occupy it and complete instantly, spending the pod's concurrency on no-ops.
if (messages.length) {
ImageScrubConsumerMetrics.observeBatchMessages(messages.length)
}
- const planned = this.planBatch(messages)
+ const decoded = this.privacy
+ ? await this.privacy.kafka.read(messages, 'image-source', true)
+ : messages.map((message) => {
+ if (ingestionVersion(message) === 2) {
+ throw new Error('ML v2 images require privacy configuration')
+ }
+ return { message, original: message, invalid: undefined }
+ })
+ for (const entry of decoded.filter((entry) => entry.invalid)) {
+ if (!this.deadLetters) {
+ throw new Error('Invalid encrypted ML image requires a dead-letter destination')
+ }
+ await this.parkImageUntilAccepted(
+ {
+ ref: entry.original.key?.toString() ?? '',
+ bytes: entry.original.value ?? Buffer.alloc(0),
+ headers: parseKafkaHeaders(entry.original.headers),
+ detail: {
+ reason: 'invalid_encryption',
+ sourceTopic: entry.original.topic,
+ sourcePartition: entry.original.partition,
+ sourceOffset: entry.original.offset,
+ },
+ },
+ controller.signal
+ )
+ }
+ const byOriginal = new Map(
+ decoded.filter((entry) => !entry.invalid).map((entry) => [entry.original, entry.message])
+ )
+ const planned = this.planBatch(
+ messages.map((message) => byOriginal.get(message) ?? { ...message, value: null })
+ )
+ for (const item of planned) {
+ if (item.sessionMonth !== undefined) {
+ item.encryptedValue = messages[item.index].value ?? undefined
+ }
+ }
// A sliding window rather than fixed groups: every completion immediately admits the next
// image, so the sidecar never waits on the slowest member of a group before being given more
@@ -207,9 +273,6 @@ export class ImageBatcher {
// so the batch takes as long as the sidecar needs and the next consume() happens that much
// later, which is the whole backpressure mechanism. Every message this batch took is finished
// before any offset moves past it.
- const controller = new AbortController()
- this.activeBatch = controller
- this.partitionsRevoked = false
const startedAt = performance.now()
if (planned.length > 0) {
ImageScrubConsumerMetrics.startBatch()
@@ -227,9 +290,6 @@ export class ImageBatcher {
(performance.now() - startedAt) / 1000
)
}
- // Cleared here rather than on the success path: a throwing batch that left this set would
- // have shutdown abort a controller belonging to a batch that is already over.
- this.activeBatch = null
}
}
@@ -366,8 +426,8 @@ export class ImageBatcher {
const headers = parseKafkaHeaders(m.headers)
const allowedTransportHeaders =
parsed.source === 'url'
- ? [CONTENT_TYPE_HEADER, CONTENT_ENCODING_HEADER, CAPTURE_TIMESTAMP_HEADER]
- : [CAPTURE_TIMESTAMP_HEADER]
+ ? [CONTENT_TYPE_HEADER, CONTENT_ENCODING_HEADER, CAPTURE_TIMESTAMP_HEADER, INGESTION_VERSION_HEADER]
+ : [CAPTURE_TIMESTAMP_HEADER, INGESTION_VERSION_HEADER]
const transportHeaders = Object.fromEntries(
allowedTransportHeaders
.filter((header) => headers[header] !== undefined)
@@ -377,6 +437,8 @@ export class ImageBatcher {
const candidate: PlannedScrub = {
index,
ref,
+ teamId: parsed.teamId,
+ sessionMonth: parsed.sessionMonth,
pseudoTeam: parsed.pseudoTeam,
hash: parsed.hash,
source: parsed.source,
@@ -504,13 +566,21 @@ export class ImageBatcher {
ImageScrubConsumerMetrics.incScrubbed()
if (planned.source === 'url') {
return {
+ teamId: planned.teamId,
+ sessionMonth: planned.sessionMonth,
hash: planned.hash,
bytes,
sourcePartition: planned.sourcePartition,
sourceOffset: planned.sourceOffset,
}
}
- return { pseudoTeam: planned.pseudoTeam!, hash: planned.hash, bytes }
+ return {
+ sessionMonth: planned.sessionMonth,
+ teamId: planned.teamId,
+ pseudoTeam: planned.pseudoTeam,
+ hash: planned.hash,
+ bytes,
+ }
}
private rememberContentAddressedRef(planned: PlannedScrub): void {
@@ -533,38 +603,55 @@ export class ImageBatcher {
planned: PlannedScrub,
poisoned: ScrubPoisoned,
signal: AbortSignal
+ ): Promise<void> {
+ await this.parkImageUntilAccepted(
+ {
+ ref: planned.ref,
+ bytes: planned.encryptedValue ?? planned.value,
+ headers: planned.transportHeaders,
+ detail: {
+ ...poisoned.detail,
+ ...(planned.teamId ? { teamId: planned.teamId } : { pseudoTeam: planned.pseudoTeam }),
+ hash: planned.hash,
+ sourceTopic: planned.sourceTopic,
+ sourcePartition: planned.sourcePartition,
+ sourceOffset: planned.sourceOffset,
+ // Carried back out, or the count restarts on every pass and the cap that
+ // bounds replay round trips never binds.
+ [REPLAY_COUNT_HEADER]: planned.replayCount,
+ },
+ },
+ signal
+ )
+ }
+
+ private async parkImageUntilAccepted(
+ image: Parameters<DeadLetterSink['park']>[0],
+ signal: AbortSignal
): Promise<void> {
for (let attempt = 0; ; attempt++) {
if (signal.aborted) {
throw new ScrubAborted('scrub batch aborted')
}
try {
- await this.deadLetters!.park({
- ref: planned.ref,
- bytes: planned.value,
- headers: planned.transportHeaders,
- detail: {
- ...poisoned.detail,
- pseudoTeam: planned.pseudoTeam,
- hash: planned.hash,
- sourceTopic: planned.sourceTopic,
- sourcePartition: planned.sourcePartition,
- sourceOffset: planned.sourceOffset,
- // Carried back out, or the count restarts on every pass and the cap that
- // bounds replay round trips never binds.
- [REPLAY_COUNT_HEADER]: planned.replayCount,
- },
- })
+ await this.deadLetters!.park(image)
return
} catch (error) {
ImageScrubConsumerMetrics.incDeadLetterFailed()
logger.error('☠️', 'image_scrub_dead_letter_failed', {
- ref: planned.ref,
- bytes: planned.value.length,
+ ref: image.ref,
+ bytes: image.bytes.length,
attempts: attempt + 1,
error: String(error),
})
- await new Promise((resolve) => setTimeout(resolve, Math.min(30_000, 500 * 2 ** attempt)).unref())
+ try {
+ await waitForRetry(Math.min(30_000, 500 * 2 ** attempt), undefined, { signal, ref: false })
+ } catch (retryError) {
+ if (signal.aborted) {
+ throw new ScrubAborted('scrub batch aborted')
+ }
+ throw retryError
+ }
}
}
}
@@ -588,6 +675,20 @@ export class ImageBatcher {
public async flush(nowMs: number): Promise<void> {
this.lastFlushMs = nowMs
if (this.buffer.length > 0) {
+ const imageKeys = this.privacy
+ ? await this.privacy.reader.read(
+ this.buffer.flatMap(({ image }) =>
+ image.sessionMonth === undefined
+ ? []
+ : [imageKeyId(Number(image.teamId), image.sessionMonth!)]
+ )
+ )
+ : new Map()
+ this.buffer = this.buffer.filter(
+ ({ image }) =>
+ image.sessionMonth === undefined ||
+ imageKeys.has(tableKeyString(imageKeyId(Number(image.teamId), image.sessionMonth!)))
+ )
const inlineItems = this.buffer.filter(
(item): item is ScrubbedRef & { image: ScrubbedImage } => item.source === 'bytes'
)
@@ -598,22 +699,52 @@ export class ImageBatcher {
urlItems.map(async (item) => {
const outcome = await this.scrubConcurrency.run({
debugTag: item.image.hash,
- fn: () => this.store.writeUrlImage(item.image),
+ fn: () =>
+ this.store.writeUrlImage(
+ item.image,
+ item.image.sessionMonth === undefined
+ ? undefined
+ : imageKeys.get(
+ tableKeyString(
+ imageKeyId(Number(item.image.teamId), item.image.sessionMonth!)
+ )
+ )
+ ),
})
if (outcome === 'created' && item.capturedAtMs !== undefined) {
ImageScrubConsumerMetrics.observeCaptureToS3('url', item.capturedAtMs, Date.now())
}
})
)
- if (inlineItems.length > 0) {
- const { bytes } = await this.store.writeShard(inlineItems.map((item) => item.image))
+ const groups = new Map<string, typeof inlineItems>()
+ for (const item of inlineItems) {
+ const groupId =
+ item.image.sessionMonth === undefined
+ ? String(item.image.teamId !== undefined)
+ : `${item.image.teamId}:${item.image.sessionMonth}`
+ const group = groups.get(groupId) ?? []
+ group.push(item)
+ groups.set(groupId, group)
+ }
+ for (const items of groups.values()) {
+ if (items.length === 0) {
+ continue
+ }
+ const { bytes } = await this.store.writeShard(
+ items.map((item) => item.image),
+ items[0].image.sessionMonth === undefined
+ ? undefined
+ : imageKeys.get(
+ tableKeyString(imageKeyId(Number(items[0].image.teamId), items[0].image.sessionMonth!))
+ )
+ )
const storedAtMs = Date.now()
- for (const item of inlineItems) {
+ for (const item of items) {
if (item.capturedAtMs !== undefined) {
ImageScrubConsumerMetrics.observeCaptureToS3('inline', item.capturedAtMs, storedAtMs)
}
}
- ImageScrubConsumerMetrics.observeShard(inlineItems.length, bytes)
+ ImageScrubConsumerMetrics.observeShard(items.length, bytes)
}
this.buffer = []
this.bufferBytes = 0
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.ts
index 1d57d6e31c12..40e4fb3980b9 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.ts
@@ -1,4 +1,9 @@
import { DeleteObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3'
+import { ParquetReader } from '@dsnp/parquetjs'
+import sodium from 'libsodium-wrappers'
+
+import { parseJSON } from '~/common/utils/json-parse'
+import { MlDataKey, decryptEnvelope } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/crypto'
import { ImageShardStore } from './image-shard-store'
@@ -18,6 +23,135 @@ describe('ImageShardStore', () => {
)
const noSleep = () => Promise.resolve()
+ it.each([undefined, '42'])('writes the matching image index and prefers raw team ID %s', async (teamId) => {
+ const send = jest.fn().mockResolvedValue({})
+ const store = new ImageShardStore({ send } as unknown as S3Client, 'bucket', 'images', 1_000, 'node')
+ await store.writeShard([{ ...inlineImage, teamId }])
+ const prefix = teamId ? 'images/v2' : 'images'
+ const shard = send.mock.calls[0][0] as PutObjectCommand
+ const index = send.mock.calls[1][0] as PutObjectCommand
+ expect(shard.input.Key).toMatch(new RegExp(`^${prefix}/shards/`))
+ expect(index.input.Key).toMatch(new RegExp(`^${prefix}/index/`))
+ const reader = await ParquetReader.openBuffer(index.input.Body as Buffer)
+ try {
+ const row = await reader.getCursor().next()
+ expect(row).toMatchObject({
+ format_version: BigInt(teamId ? 2 : 1),
+ [teamId ? 'team_id' : 'pseudo_team']: teamId ?? inlineImage.pseudoTeam,
+ shard: shard.input.Key,
+ offset: BigInt(0),
+ length: BigInt(inlineImage.bytes.length),
+ })
+ expect(row).not.toHaveProperty(teamId ? 'pseudo_team' : 'team_id')
+ } finally {
+ await reader.close()
+ }
+ })
+
+ it.each([false, true])(
+ 'publishes encrypted hash lookups and preserves referenced shards on failure: %s',
+ async (failLookup) => {
+ await sodium.ready
+ const key: MlDataKey = {
+ identity: { teamId: 7, organizationId: 'test-org', sessionMonth: '2026-09' },
+ plaintext: Buffer.alloc(32, 7),
+ wrapped: Buffer.alloc(32, 8),
+ }
+ const send = jest.fn((command: PutObjectCommand | DeleteObjectCommand) => {
+ if (failLookup && command.input.Key?.includes('/lookup/')) {
+ return Promise.reject(s3Failure(403))
+ }
+ return Promise.resolve({})
+ })
+ const store = new ImageShardStore({ send } as unknown as S3Client, 'bucket', 'images', 1_000, 'node')
+ const write = store.writeShard(
+ [
+ {
+ teamId: '7',
+ sessionMonth: '2026-09',
+ hash: inlineImage.hash,
+ bytes: inlineImage.bytes,
+ },
+ ],
+ key
+ )
+ if (failLookup) {
+ await expect(write).rejects.toThrow('s3 rejected the write')
+ } else {
+ await write
+ const lookup = send.mock.calls
+ .map(([command]) => command)
+ .find((command) => command.input.Key?.includes('/lookup/')) as PutObjectCommand
+ const location = parseJSON(
+ decryptEnvelope(
+ key,
+ parseJSON((lookup.input.Body as Buffer).toString()),
+ 'image-location',
+ lookup.input.Key
+ ).toString()
+ )
+ expect(location).toEqual({ shard: send.mock.calls[0][0].input.Key, offset: 0, length: 3 })
+ expect(lookup.input.Key).toBe(`images/v2/2026-09/7/lookup/${inlineImage.hash}.encrypted`)
+ }
+ expect(send.mock.calls.every(([command]) => command instanceof PutObjectCommand)).toBe(true)
+ }
+ )
+
+ it('bounds the total time spent in queued image lookup uploads', async () => {
+ await sodium.ready
+ jest.useFakeTimers()
+ try {
+ const key: MlDataKey = {
+ identity: { teamId: 7, organizationId: 'test-org', sessionMonth: '2026-09' },
+ plaintext: Buffer.alloc(32, 7),
+ wrapped: Buffer.alloc(32, 8),
+ }
+ let signalStarted!: () => void
+ const started = new Promise<void>((resolve) => {
+ signalStarted = resolve
+ })
+ const send = jest.fn(
+ (command: PutObjectCommand | DeleteObjectCommand, options: { abortSignal: AbortSignal }) => {
+ if (!command.input.Key?.includes('/lookup/')) {
+ return Promise.resolve({})
+ }
+ signalStarted()
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => resolve({}), 29_000)
+ options.abortSignal.addEventListener('abort', () => {
+ clearTimeout(timer)
+ reject(new Error('aborted'))
+ })
+ })
+ }
+ )
+ const store = new ImageShardStore(
+ { send } as unknown as S3Client,
+ 'bucket',
+ 'images',
+ 30_000,
+ 'node',
+ noSleep
+ )
+ const write = store.writeShard(
+ Array.from({ length: 9 }, (_, index) => ({
+ teamId: '7',
+ sessionMonth: '2026-09',
+ hash: String(index).padStart(22, '0'),
+ bytes: inlineImage.bytes,
+ })),
+ key
+ )
+ const failed = expect(write).rejects.toThrow('aborted')
+ await started
+ await jest.advanceTimersByTimeAsync(45_000)
+ await failed
+ expect(send.mock.calls.every(([command]) => command instanceof PutObjectCommand)).toBe(true)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
it('retries a shard write that exceeds the timeout, then gives up so the flush replays', async () => {
const send = jest.fn(
(_cmd: unknown, opts: { abortSignal: AbortSignal }) =>
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.ts
index d6e4484627fa..15841ddb23c3 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.ts
@@ -1,17 +1,23 @@
import { DeleteObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3'
import { ParquetSchema } from '@dsnp/parquetjs'
import { randomUUID } from 'node:crypto'
+import pLimit from 'p-limit'
import { logger } from '~/common/utils/logger'
+import { MlDataKey, encryptEnvelope } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/crypto'
import { parquetRecordsToBuffer } from '~/ingestion/pipelines/sessionreplay/shared/parquet'
export interface ScrubbedImage {
- pseudoTeam: string
+ sessionMonth?: string
+ teamId?: string
+ pseudoTeam?: string
hash: string
bytes: Buffer
}
export interface ScrubbedUrlImage {
+ teamId?: string
+ sessionMonth?: string
hash: string
bytes: Buffer
sourcePartition: number
@@ -21,14 +27,14 @@ export interface ScrubbedUrlImage {
export type UrlImageWriteOutcome = 'created' | 'already_exists'
interface IndexRow {
- pseudoTeam: string
+ teamId?: string
+ pseudoTeam?: string
hash: string
shard: string
offset: number
length: number
}
-const INDEX_FORMAT_VERSION = 1
const URL_SOURCE_PARTITION_METADATA = 'source-partition'
const URL_SOURCE_OFFSET_METADATA = 'source-offset'
const URL_WRITE_MAX_ATTEMPTS = 8
@@ -44,21 +50,22 @@ const S3_WRITE_RETRY_BUDGET_MS = 45_000
const S3_WRITE_RETRY_BASE_MS = 100
const S3_WRITE_RETRY_MAX_BACKOFF_MS = 2_000
-const INDEX_SCHEMA = new ParquetSchema({
+const INDEX_FIELDS = {
format_version: { type: 'INT64', compression: 'SNAPPY' },
- pseudo_team: { type: 'UTF8', compression: 'SNAPPY' },
hash: { type: 'UTF8', compression: 'SNAPPY' },
shard: { type: 'UTF8', compression: 'SNAPPY' },
offset: { type: 'INT64', compression: 'SNAPPY' },
length: { type: 'INT64', compression: 'SNAPPY' },
-})
+} as const
+const LEGACY_INDEX_SCHEMA = new ParquetSchema({ ...INDEX_FIELDS, pseudo_team: { type: 'UTF8', compression: 'SNAPPY' } })
+const INDEX_SCHEMA = new ParquetSchema({ ...INDEX_FIELDS, team_id: { type: 'UTF8', compression: 'SNAPPY' } })
-function indexRowsToParquet(rows: IndexRow[]): Promise<Buffer> {
+function indexRowsToParquet(rows: IndexRow[], rawTeamIds: boolean): Promise<Buffer> {
return parquetRecordsToBuffer(
- INDEX_SCHEMA,
+ rawTeamIds ? INDEX_SCHEMA : LEGACY_INDEX_SCHEMA,
rows.map((r) => ({
- format_version: BigInt(INDEX_FORMAT_VERSION),
- pseudo_team: r.pseudoTeam,
+ format_version: BigInt(rawTeamIds ? 2 : 1),
+ ...(rawTeamIds ? { team_id: r.teamId } : { pseudo_team: r.pseudoTeam }),
hash: r.hash,
shard: r.shard,
offset: BigInt(r.offset),
@@ -68,6 +75,7 @@ function indexRowsToParquet(rows: IndexRow[]): Promise<Buffer> {
}
export class ImageShardStore {
+ private readonly publishLookup = pLimit(8)
private seq = 0
private readonly nodeId: string
@@ -95,16 +103,23 @@ export class ImageShardStore {
* repeated request writes the same bytes to the same key, or reports the conflict that
* writeUrlImage already reads as a result. Retrying is therefore safe for all three commands.
*/
- private async send(command: PutObjectCommand | DeleteObjectCommand): Promise<void> {
+ private async send(command: PutObjectCommand | DeleteObjectCommand, deadlineMs = Infinity): Promise<void> {
const startedAtMs = performance.now()
for (let attempt = 1; ; attempt++) {
+ const remainingMs = deadlineMs - performance.now()
+ if (remainingMs <= 0) {
+ throw new Error('Image lookup upload budget exhausted')
+ }
const controller = new AbortController()
let timedOut = false
let failure: unknown
- const timer = setTimeout(() => {
- timedOut = true
- controller.abort()
- }, this.writeTimeoutMs)
+ const timer = setTimeout(
+ () => {
+ timedOut = true
+ controller.abort()
+ },
+ Math.min(this.writeTimeoutMs, remainingMs)
+ )
try {
await this.s3.send(command, { abortSignal: controller.signal })
return
@@ -115,6 +130,7 @@ export class ImageShardStore {
}
if (
attempt >= S3_WRITE_MAX_ATTEMPTS ||
+ performance.now() >= deadlineMs ||
performance.now() - startedAtMs >= S3_WRITE_RETRY_BUDGET_MS ||
!(timedOut || isTransientS3Failure(failure))
) {
@@ -133,28 +149,70 @@ export class ImageShardStore {
}
}
- public async writeShard(images: ScrubbedImage[]): Promise<{ shard: string; bytes: number }> {
+ public async writeShard(
+ images: ScrubbedImage[],
+ encryptionKey?: MlDataKey
+ ): Promise<{ shard: string; bytes: number }> {
+ const rawTeamIds = images[0]?.teamId !== undefined
+ if (
+ images.some((image) => (image.teamId !== undefined) !== rawTeamIds || !(image.teamId ?? image.pseudoTeam))
+ ) {
+ throw new Error('Inline image shards must use one team ID format')
+ }
+ if (
+ images.some(
+ (image) =>
+ image.sessionMonth !== undefined &&
+ (!encryptionKey ||
+ encryptionKey.identity.sessionId ||
+ image.teamId !== String(encryptionKey.identity.teamId) ||
+ image.sessionMonth !== encryptionKey.identity.sessionMonth)
+ )
+ ) {
+ throw new Error('Image shard encryption ownership mismatch')
+ }
+ const sessionMonth = images[0]?.sessionMonth
+ if (
+ encryptionKey &&
+ (!sessionMonth ||
+ !/^[0-9]{4}-(0[1-9]|1[0-2])$/.test(sessionMonth) ||
+ images.some((image) => image.sessionMonth !== sessionMonth))
+ ) {
+ throw new Error('Image shards require one valid session month')
+ }
+ const prefix = encryptionKey
+ ? `${this.prefix}/v2/${sessionMonth}/${encryptionKey.identity.teamId}`
+ : rawTeamIds
+ ? `${this.prefix}/v2`
+ : this.prefix
this.seq += 1
const stamp = `${this.nodeId}-${Date.now()}-${this.seq}`
- const shardKey = `${this.prefix}/shards/${stamp}.bin`
+ const shardKey = `${prefix}/shards/${stamp}.bin`
const rows: IndexRow[] = []
const parts: Buffer[] = []
let offset = 0
for (const img of images) {
- rows.push({ pseudoTeam: img.pseudoTeam, hash: img.hash, shard: shardKey, offset, length: img.bytes.length })
+ rows.push({
+ teamId: img.teamId,
+ pseudoTeam: img.pseudoTeam,
+ hash: img.hash,
+ shard: shardKey,
+ offset,
+ length: img.bytes.length,
+ })
parts.push(img.bytes)
offset += img.bytes.length
}
const shardBody = Buffer.concat(parts, offset)
- const indexBody = await indexRowsToParquet(rows)
+ const indexBody = await indexRowsToParquet(rows, rawTeamIds)
// Shard before index: an index pointing at a missing shard breaks reads; a dangling shard only wastes storage.
await this.send(
new PutObjectCommand({
Bucket: this.bucket,
Key: shardKey,
- Body: shardBody,
+ Body: encryptionKey ? encryptEnvelope(encryptionKey, 'image-shard', shardBody, shardKey) : shardBody,
ContentType: 'application/octet-stream',
})
)
@@ -162,9 +220,11 @@ export class ImageShardStore {
await this.send(
new PutObjectCommand({
Bucket: this.bucket,
- Key: `${this.prefix}/index/${stamp}.parquet`,
- Body: indexBody,
- ContentType: 'application/vnd.apache.parquet',
+ Key: `${prefix}/index/${stamp}.${encryptionKey ? 'encrypted' : 'parquet'}`,
+ Body: encryptionKey
+ ? encryptEnvelope(encryptionKey, 'image-index', indexBody, shardKey)
+ : indexBody,
+ ContentType: encryptionKey ? 'application/octet-stream' : 'application/vnd.apache.parquet',
})
)
} catch (e) {
@@ -172,10 +232,36 @@ export class ImageShardStore {
await this.send(new DeleteObjectCommand({ Bucket: this.bucket, Key: shardKey })).catch(() => {})
throw e
}
+ if (encryptionKey) {
+ const lookupDeadlineMs = performance.now() + S3_WRITE_RETRY_BUDGET_MS
+ await Promise.all(
+ rows.map((row) =>
+ this.publishLookup(async () => {
+ const lookupKey = `${prefix}/lookup/${row.hash}.encrypted`
+ await this.send(
+ new PutObjectCommand({
+ Bucket: this.bucket,
+ Key: lookupKey,
+ Body: encryptEnvelope(
+ encryptionKey,
+ 'image-location',
+ Buffer.from(
+ JSON.stringify({ shard: shardKey, offset: row.offset, length: row.length })
+ ),
+ lookupKey
+ ),
+ ContentType: 'application/octet-stream',
+ }),
+ lookupDeadlineMs
+ )
+ })
+ )
+ )
+ }
return { shard: shardKey, bytes: offset }
}
- public async writeUrlImage(image: ScrubbedUrlImage): Promise<UrlImageWriteOutcome> {
+ public async writeUrlImage(image: ScrubbedUrlImage, encryptionKey?: MlDataKey): Promise<UrlImageWriteOutcome> {
if (
!Number.isSafeInteger(image.sourcePartition) ||
image.sourcePartition < 0 ||
@@ -184,14 +270,30 @@ export class ImageShardStore {
) {
throw new Error('URL image source position must contain non-negative safe integers')
}
- const key = `${this.prefix}/url/${image.hash}`
+ if (
+ image.sessionMonth !== undefined &&
+ (!encryptionKey ||
+ encryptionKey.identity.sessionId ||
+ image.teamId !== String(encryptionKey.identity.teamId) ||
+ image.sessionMonth !== encryptionKey.identity.sessionMonth)
+ ) {
+ throw new Error('URL image encryption ownership mismatch')
+ }
+ if (encryptionKey && (!image.sessionMonth || !/^[0-9]{4}-(0[1-9]|1[0-2])$/.test(image.sessionMonth))) {
+ throw new Error('URL images require a valid session month')
+ }
+ const key = encryptionKey
+ ? `${this.prefix}/v2/${image.sessionMonth}/${encryptionKey.identity.teamId}/url/${image.hash}`
+ : `${this.prefix}/url/${image.hash}`
for (let attempt = 0; attempt < URL_WRITE_MAX_ATTEMPTS; attempt++) {
try {
await this.send(
new PutObjectCommand({
Bucket: this.bucket,
Key: key,
- Body: image.bytes,
+ Body: encryptionKey
+ ? encryptEnvelope(encryptionKey, 'image-url', image.bytes, key)
+ : image.bytes,
ContentType: 'application/octet-stream',
Metadata: {
[URL_SOURCE_PARTITION_METADATA]: String(image.sourcePartition),
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 e0c3eec624ba..e1f019dd6631 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
@@ -1,13 +1,21 @@
+import { S3Client } from '@aws-sdk/client-s3'
+import { ParquetReader } from '@dsnp/parquetjs'
+import sodium from 'libsodium-wrappers'
import { Message } from 'node-rdkafka'
+import { parseJSON } from '~/common/utils/json-parse'
+
import { BlockMetadataBatcher, OffsetStore } from './block-metadata-batcher'
import { BlockMetadataParquetStore } from './block-metadata-parquet-store'
import { MlBlockMetadataRow } from './block-metadata-row'
+import { MlDataKey, decryptEnvelope } from './privacy/crypto'
+import { MlKeyReader } from './privacy/reader'
+import { sessionKeyId, tableKeyString } from './privacy/schema'
+import { MlKafkaEncryption, encryptedKafkaValue } from './privacy/transport'
const row = (sessionId: string): MlBlockMetadataRow => ({
session_id: sessionId,
team_id: 't1',
- distinct_id: 'd1',
block_url: 's3://b/k?range=bytes=0-9',
block_s3_key: 's3://b/k',
block_byte_start: 0,
@@ -101,6 +109,65 @@ describe('BlockMetadataBatcher', () => {
expect(offsets.offsetsStore).not.toHaveBeenCalled()
})
+ 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 key: MlDataKey = {
+ identity: { teamId: 7, organizationId: 'test-org', sessionId },
+ plaintext: Buffer.alloc(32, 7),
+ wrapped: Buffer.from('wrapped'),
+ }
+ const reader = {
+ read: jest.fn(() => Promise.resolve(new Map([[tableKeyString(sessionKeyId(7, sessionId)), key]]))),
+ } as unknown as MlKeyReader
+ const metadata: MlBlockMetadataRow = {
+ ...row(sessionId),
+ team_id: '7',
+ format_version: 2,
+ first_ts_ms: timestamp,
+ last_ts_ms: timestamp,
+ replay_index_entries: [
+ { kind: 'json_ld', eventIndex: 0, eventTimestamp: timestamp, windowId: 'w1', rootTypes: ['Product'] },
+ ],
+ }
+ const encrypted = encryptedKafkaValue(
+ key,
+ 'metadata',
+ Buffer.from(JSON.stringify({ ...metadata, distinct_id: 'legacy-user', distinctId: 'unexpected-user' }))
+ )
+ const message = {
+ ...msg(0),
+ value: encrypted.value,
+ headers: Object.entries(encrypted.headers).map(([name, value]) => ({ [name]: Buffer.from(value) })),
+ }
+ const s3 = {
+ send: jest.fn().mockRejectedValueOnce(new Error('index upload failed')).mockResolvedValue({}),
+ } as unknown as S3Client
+ const batcher = new BlockMetadataBatcher(
+ new BlockMetadataParquetStore(s3, 'bucket', 'block-metadata'),
+ offsets,
+ { flushIntervalMs: 1000, maxRows: 1 },
+ 0,
+ new MlKafkaEncryption(reader)
+ )
+ await expect(batcher.handleBatch([message], 0)).rejects.toThrow('index upload failed')
+ expect(offsets.offsetsStore).not.toHaveBeenCalled()
+ await batcher.flush(1)
+ expect(offsets.offsetsStore).toHaveBeenCalledWith([{ topic: 'ml_block_metadata', partition: 0, offset: 1 }])
+ const body = (jest.mocked(s3.send).mock.calls.at(-1)![0].input as { Body: Buffer }).Body
+ const parquet = await ParquetReader.openBuffer(body)
+ const stored = (await parquet.getCursor().next()) as { payload: Buffer }
+ const payload = parseJSON(decryptEnvelope(key, parseJSON(stored!.payload.toString()), 'metadata').toString())
+ expect(payload).toEqual(metadata)
+ await parquet.close()
+ expect(jest.mocked(s3.send).mock.calls.map(([command]) => (command.input as { Key: string }).Key)).toEqual([
+ expect.stringContaining('block-metadata-replay-index/v2/2026-09/kind=json_ld/'),
+ expect.stringContaining('block-metadata-replay-index/v2/2026-09/kind=json_ld/'),
+ expect.stringContaining('block-metadata/v2/2026-09/'),
+ ])
+ })
+
it('starts a fresh window after flushing', async () => {
const batcher = makeBatcher(1_000, 1_000_000, 0)
await batcher.handleBatch([msg(0)], 1_000) // flushes (interval elapsed)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.ts
index 8de4f310833b..1f50a20e29d0 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.ts
@@ -2,11 +2,16 @@
import { Message, TopicPartitionOffset } from 'node-rdkafka'
import { findOffsetsToCommit } from '~/common/kafka/consumer/consumer-v1'
+import { parseJSON } from '~/common/utils/json-parse'
+import { isWellFormedRow, selectBlockMetadataFields } from './block-metadata-columns'
import { parseBlockMetadataMessages } from './block-metadata-message'
import { BlockMetadataParquetStore } from './block-metadata-parquet-store'
import { MlBlockMetadataRow } from './block-metadata-row'
import { MlParquetSinkMetrics } from './metrics'
+import { MlEncryptedEnvelope, encryptEnvelope } from './privacy/crypto'
+import { MlKafkaEncryption, ingestionVersion } from './privacy/transport'
+import { EncryptedReplayIndex, encryptReplayIndex } from './replay-index'
/** The subset of the Kafka consumer the batcher needs: storing offsets it has durably written. */
export interface OffsetStore {
@@ -20,6 +25,8 @@ export interface BlockMetadataBatcherOptions {
}
export class BlockMetadataBatcher {
+ private encrypted: MlEncryptedEnvelope[] = []
+ private encryptedIndex: EncryptedReplayIndex[] = []
private buffer: MlBlockMetadataRow[] = []
private bufferedBytes = 0
private pendingOffsets = new Map<string, TopicPartitionOffset>()
@@ -29,7 +36,8 @@ export class BlockMetadataBatcher {
private readonly store: BlockMetadataParquetStore,
private readonly offsetStore: OffsetStore,
private readonly options: BlockMetadataBatcherOptions,
- nowMs: number
+ nowMs: number,
+ private readonly privacy?: MlKafkaEncryption
) {
this.lastFlushMs = nowMs
}
@@ -39,8 +47,51 @@ export class BlockMetadataBatcher {
for (const message of messages) {
this.bufferedBytes += message.value?.length ?? 0
}
- for (const row of parseBlockMetadataMessages(messages)) {
- this.buffer.push(row)
+ const decoded = this.privacy
+ ? await this.privacy.read(messages, 'metadata')
+ : messages.map((message) => {
+ if (ingestionVersion(message) === 2) {
+ throw new Error('ML v2 metadata requires privacy configuration')
+ }
+ return { message, original: message, key: undefined, invalid: undefined }
+ })
+ MlParquetSinkMetrics.incRowsRejected('privacy', messages.length - decoded.length)
+ let encryptedRows = 0
+ for (const { message, key, invalid } of decoded) {
+ if (invalid) {
+ MlParquetSinkMetrics.incRowsRejected('invalid_envelope')
+ }
+ if (key) {
+ let row: unknown
+ try {
+ row = parseJSON(message.value!.toString())
+ } catch {
+ MlParquetSinkMetrics.incRowsRejected('parse_failed')
+ continue
+ }
+ if (isWellFormedRow(row)) {
+ const selected = selectBlockMetadataFields(row)
+ this.encrypted.push(
+ parseJSON(
+ encryptEnvelope(key, 'metadata', Buffer.from(JSON.stringify(selected))).toString()
+ ) as MlEncryptedEnvelope
+ )
+ encryptedRows++
+ const index = encryptReplayIndex(selected, key)
+ this.encryptedIndex.push(...index)
+ this.bufferedBytes += index.reduce((size, item) => size + JSON.stringify(item.envelope).length, 0)
+ } else {
+ MlParquetSinkMetrics.incRowsRejected('invalid')
+ }
+ }
+ }
+ MlParquetSinkMetrics.incRowsParsed(encryptedRows)
+ for (const row of parseBlockMetadataMessages(
+ decoded.filter(({ key, invalid }) => !key && !invalid).map(({ message }) => message)
+ )) {
+ if (row.format_version !== 2) {
+ this.buffer.push(row)
+ }
}
// Track the next offset to read per partition (highest seen + 1), accumulated across batches.
for (const offset of findOffsetsToCommit(messages)) {
@@ -53,7 +104,7 @@ export class BlockMetadataBatcher {
private shouldFlush(nowMs: number): boolean {
if (
- this.buffer.length >= this.options.maxRows ||
+ this.buffer.length + this.encrypted.length >= this.options.maxRows ||
this.bufferedBytes >= (this.options.maxBytes ?? 32 * 1024 * 1024)
) {
return true
@@ -70,8 +121,16 @@ export class BlockMetadataBatcher {
*/
public async flush(nowMs: number): Promise<void> {
this.lastFlushMs = nowMs
- const wroteObject = this.buffer.length > 0
- if (wroteObject) {
+ const wroteObject = this.buffer.length > 0 || this.encrypted.length > 0
+ if (this.encryptedIndex.length > 0) {
+ await this.store.writeEncryptedReplayIndex(this.encryptedIndex)
+ this.encryptedIndex = []
+ }
+ if (this.encrypted.length > 0) {
+ await this.store.writeEncrypted(this.encrypted)
+ this.encrypted = []
+ }
+ if (this.buffer.length > 0) {
await this.store.write(this.buffer)
this.buffer = []
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-columns.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-columns.ts
index e2bfb47a3954..6e3214f0d617 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-columns.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-columns.ts
@@ -1,6 +1,8 @@
/** Single source of truth for the ML block-metadata columns: drives the Parquet schema, the row→record
* mapping (in parquet-writer.ts), and the poison-row validator below. Kept free of the Parquet dependency
* so the message-parsing path doesn't pull it in. */
+import { isRawTeamId } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'
+
import { MlBlockMetadataRow } from './block-metadata-row'
export type ParquetType = 'UTF8' | 'INT32' | 'INT64' | 'TIMESTAMP_MILLIS'
@@ -20,7 +22,6 @@ export interface BlockMetadataColumn {
export const COLUMNS: BlockMetadataColumn[] = [
{ row: 'session_id', parquet: 'session_id', type: 'UTF8' },
{ row: 'team_id', parquet: 'team_id', type: 'UTF8' },
- { row: 'distinct_id', parquet: 'distinct_id', type: 'UTF8' },
{ row: 'block_url', parquet: 'block_url', type: 'UTF8' },
{ row: 'block_s3_key', parquet: 'block_s3_key', type: 'UTF8' },
{ row: 'block_byte_start', parquet: 'block_byte_start', type: 'INT64', optional: true },
@@ -51,6 +52,9 @@ export function isWellFormedRow(row: unknown): row is MlBlockMetadataRow {
return false
}
const r = row as Record<string, unknown>
+ if (r.format_version !== undefined && (r.format_version !== 2 || !isRawTeamId(r.team_id))) {
+ return false
+ }
for (const col of COLUMNS) {
if (col.optional) {
continue
@@ -70,3 +74,17 @@ export function isWellFormedRow(row: unknown): row is MlBlockMetadataRow {
}
return true
}
+
+export function selectBlockMetadataFields(row: MlBlockMetadataRow): MlBlockMetadataRow {
+ return Object.fromEntries(
+ [
+ ...COLUMNS.map(({ row: field }) => field),
+ 'format_version',
+ 'session_start_ts_ms',
+ 'replay_index_entries',
+ 'replay_index_truncated',
+ ]
+ .filter((field) => Object.hasOwn(row, field))
+ .map((field) => [field, row[field as keyof MlBlockMetadataRow]])
+ ) as unknown as MlBlockMetadataRow
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-message.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-message.test.ts
index a90714845678..964aa4c28dca 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-message.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-message.test.ts
@@ -4,7 +4,6 @@ import { MlBlockMetadataRow } from './block-metadata-row'
const fullRow = (over: Partial<MlBlockMetadataRow> = {}): MlBlockMetadataRow => ({
session_id: 's1',
team_id: 't1',
- distinct_id: 'd1',
block_url: 's3://b/k?range=bytes=0-9',
block_s3_key: 's3://b/k',
block_byte_start: 0,
@@ -36,9 +35,13 @@ const msg = (value: unknown): { value: Buffer | null } => ({
describe('parseBlockMetadataMessages', () => {
it('parses well-formed rows and preserves their fields', () => {
- const rows = parseBlockMetadataMessages([msg(fullRow({ session_id: 'a', event_count: 3 })), msg(fullRow())])
+ const rows = parseBlockMetadataMessages([
+ msg(fullRow({ session_id: 'a', event_count: 3, team_id: '42', format_version: 2 })),
+ msg({ ...fullRow(), distinct_id: 'legacy-user', distinctId: 'unexpected-user' }),
+ ])
expect(rows).toHaveLength(2)
- expect(rows[0]).toMatchObject({ session_id: 'a', event_count: 3 })
+ expect(rows[1]).toEqual(fullRow())
+ expect(rows[0]).toMatchObject({ session_id: 'a', event_count: 3, team_id: '42', format_version: 2 })
})
it('skips null values and malformed JSON without throwing', () => {
@@ -49,9 +52,12 @@ describe('parseBlockMetadataMessages', () => {
it('skips shape-invalid rows (poison-pill guard) without throwing', () => {
const rows = parseBlockMetadataMessages([
- msg({ session_id: 'a', event_count: 3 }), // missing required numeric fields + urls
+ msg({ session_id: 'a', event_count: 3, team_id: '42', format_version: 2 }), // missing required numeric fields + urls
msg(fullRow({ event_count: 'oops' as unknown as number })), // wrong type
msg(fullRow({ urls: 'not-an-array' as unknown as string[] })),
+ msg(fullRow({ format_version: 2, team_id: 'a'.repeat(32) })),
+ msg(fullRow({ format_version: 2, team_id: '9007199254740992' })),
+ msg({ ...fullRow(), format_version: 3 }),
msg(fullRow({ session_id: 'good' })),
])
expect(rows).toHaveLength(1)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-message.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-message.ts
index 9c9da1ea6fc6..f7b472d98067 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-message.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-message.ts
@@ -2,7 +2,7 @@
import { parseJSON } from '~/common/utils/json-parse'
import { logger } from '~/common/utils/logger'
-import { isWellFormedRow } from './block-metadata-columns'
+import { isWellFormedRow, selectBlockMetadataFields } from './block-metadata-columns'
import { MlBlockMetadataRow } from './block-metadata-row'
import { MlParquetSinkMetrics } from './metrics'
@@ -26,7 +26,7 @@ export function parseBlockMetadataMessages(messages: readonly { value: Buffer |
MlParquetSinkMetrics.incRowsRejected('invalid')
continue
}
- rows.push(row)
+ rows.push(selectBlockMetadataFields(row))
}
MlParquetSinkMetrics.incRowsParsed(rows.length)
return rows
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.test.ts
index d368bfb3fb0e..52e175849a2b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.test.ts
@@ -1,14 +1,19 @@
import { PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'
import { ParquetReader } from '@dsnp/parquetjs'
+import sodium from 'libsodium-wrappers'
+import { register } from 'prom-client'
+
+import { parseJSON } from '~/common/utils/json-parse'
import { BlockMetadataParquetStore } from './block-metadata-parquet-store'
import { MlBlockMetadataRow } from './block-metadata-row'
-import { replayIndexPartitions } from './replay-index'
+import { MlDataKey, decryptEnvelope } from './privacy/crypto'
+import { TrainingEncryptionVector } from './privacy/test-vectors'
+import { encryptReplayIndex, replayIndexPartitions } from './replay-index'
const row = (sessionId: string, teamId: string): MlBlockMetadataRow => ({
session_id: sessionId,
team_id: teamId,
- distinct_id: 'did-pseudo',
block_url: `s3://ml-bucket/key-${sessionId}?range=bytes=0-9`,
block_s3_key: `s3://ml-bucket/key-${sessionId}`,
block_byte_start: 0,
@@ -50,6 +55,7 @@ describe('BlockMetadataParquetStore', () => {
let s3: S3Client
beforeEach(() => {
+ register.resetMetrics()
puts = []
s3 = {
send: jest.fn((cmd: { input: PutObjectCommandInput }) => {
@@ -59,6 +65,100 @@ describe('BlockMetadataParquetStore', () => {
} as unknown as S3Client
})
+ it('splits encrypted metadata by session month rather than upload time', async () => {
+ const envelopes = ['2026-09-30T23:59:59.999Z', '2026-10-01T00:00:00Z'].map((date) => {
+ const hex = Date.parse(date).toString(16).padStart(12, '0')
+ return {
+ ...TrainingEncryptionVector.envelope,
+ context: {
+ ...TrainingEncryptionVector.envelope.context,
+ sessionId: `${hex.slice(0, 8)}-${hex.slice(8)}-7000-8000-000000000007`,
+ },
+ }
+ })
+ await new BlockMetadataParquetStore(s3, 'ml-bucket', 'block-metadata', 'pod').writeEncrypted(envelopes)
+ expect(puts.map((put) => put.Key?.split('/').slice(0, 3).join('/'))).toEqual([
+ 'block-metadata/v2/2026-09',
+ 'block-metadata/v2/2026-10',
+ ])
+ for (const [index, put] of puts.entries()) {
+ const records = await readRows(put.Body)
+ expect(records.map((record) => record.session_id)).toEqual([envelopes[index].context.sessionId])
+ }
+ })
+
+ it('stores encrypted eval indexes by session month with raw team IDs across late blocks', async () => {
+ await sodium.ready
+ const starts = ['2026-09-30T23:59:59.999Z', '2026-10-01T00:00:00Z']
+ const eventTimestamp = Date.parse('2026-10-01T00:00:01Z')
+ const store = new BlockMetadataParquetStore(s3, 'ml-bucket', 'block-metadata', 'pod')
+ for (const [index, start] of starts.entries()) {
+ const hex = Date.parse(start).toString(16).padStart(12, '0')
+ const sessionId = `${hex.slice(0, 8)}-${hex.slice(8)}-7000-8000-000000000007`
+ const key: MlDataKey = {
+ identity: { teamId: 7, organizationId: 'test-org', sessionId },
+ plaintext: Buffer.alloc(32, 7),
+ wrapped: Buffer.from('wrapped'),
+ }
+ const metadata: MlBlockMetadataRow = {
+ ...row(sessionId, '7'),
+ format_version: 2,
+ first_ts_ms: eventTimestamp,
+ last_ts_ms: eventTimestamp,
+ replay_index_entries: [
+ { kind: 'full_snapshot', windowId: 'w1', eventTimestamp, eventIndex: 0 },
+ { kind: 'json_ld', windowId: 'w1', eventTimestamp, eventIndex: 1, rootTypes: ['Product'] },
+ { kind: 'page', windowId: 'w1', eventTimestamp, eventIndex: 1, url: 'https://example.com/product' },
+ ],
+ }
+ await store.writeEncryptedReplayIndex(encryptReplayIndex(metadata, key))
+ const month = start.slice(0, 7)
+ const objects = puts.filter((put) => put.Key!.startsWith(`block-metadata-replay-index/v2/${month}/`))
+ expect(objects).toHaveLength(2)
+ const labels = await readRows(objects.find((put) => put.Key!.includes('/kind=json_ld/'))!.Body)
+ expect(labels).toHaveLength(1)
+ expect(labels[0]).toMatchObject({ team_id: '7', session_id: sessionId })
+ expect(labels[0].url).toBeUndefined()
+ expect(labels[0].root_types).toBeUndefined()
+ const envelope = parseJSON(labels[0].payload.toString())
+ const decoded = parseJSON(decryptEnvelope(key, envelope, 'replay-index', 'json_ld').toString())
+ expect(decoded).toEqual([
+ expect.objectContaining({
+ team_id: '7',
+ session_id: sessionId,
+ session_start_ts_ms: Date.parse(starts[index]),
+ event_ts_ms: eventTimestamp,
+ kind: 'json_ld',
+ root_types: ['Product'],
+ url: 'https://example.com/product',
+ }),
+ ])
+ expect(() => decryptEnvelope(key, envelope, 'replay-index', 'full_snapshot')).toThrow()
+ }
+ })
+
+ it.each([false, true])('counts encrypted uploads and failures: %s', async (failed) => {
+ if (failed) {
+ jest.mocked(s3.send).mockImplementationOnce(() => Promise.reject(new Error('upload failed')))
+ }
+ const store = new BlockMetadataParquetStore(s3, 'ml-bucket', 'block-metadata', 'pod-1')
+ const write = store.writeEncrypted([TrainingEncryptionVector.envelope])
+ if (failed) {
+ await expect(write).rejects.toThrow('upload failed')
+ } else {
+ await write
+ }
+ const rows = await register.getSingleMetric('ml_mirror_parquet_sink_rows_written_total')!.get()
+ const failures = await register.getSingleMetric('ml_mirror_parquet_sink_write_errors_total')!.get()
+ expect(rows.values[0].value).toBe(failed ? 0 : 1)
+ expect(failures.values[0].value).toBe(failed ? 1 : 0)
+ if (!failed) {
+ expect((await readRows(puts[0].Body))[0].payload).toEqual(
+ Buffer.from(JSON.stringify(TrainingEncryptionVector.envelope))
+ )
+ }
+ })
+
it.each([
{ name: 'adjacent URL', pageIndex: 0, pageTime: 1000, window: 'w1', expected: 'https://example.com/page' },
{ name: 'same timestamp', pageIndex: 0, pageTime: 1100, window: 'w1', expected: 'https://example.com/page' },
@@ -121,6 +221,12 @@ describe('BlockMetadataParquetStore', () => {
expect(entries.find((entry) => entry.kind === 'full_snapshot')?.url).toBeNull()
})
+ it('rejects plaintext v2 metadata before writing any objects', async () => {
+ const store = new BlockMetadataParquetStore(s3, 'ml-bucket', 'block-metadata', 'pod-1')
+ await expect(store.write([{ ...row('session', '42'), format_version: 2 }])).rejects.toThrow('encrypted storage')
+ expect(puts).toHaveLength(0)
+ })
+
it('writes one dt-partitioned Parquet object that round-trips', async () => {
const store = new BlockMetadataParquetStore(s3, 'ml-bucket', 'block-metadata', 'pod-1')
await store.write([row('s1', 't1'), row('s2', 't1')])
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.ts
index 0cb05ee8f132..dd917bf20b90 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.ts
@@ -1,13 +1,17 @@
/** Sorts, encodes, and uploads a batch of block-metadata rows as one dt-partitioned Parquet object in the ML bucket. */
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3'
+import { ParquetSchema } from '@dsnp/parquetjs'
import { randomUUID } from 'crypto'
import { logger } from '~/common/utils/logger'
+import { parquetRecordsToBuffer } from '~/ingestion/pipelines/sessionreplay/shared/parquet'
import { MlBlockMetadataRow } from './block-metadata-row'
import { MlParquetSinkMetrics } from './metrics'
import { rowsToParquetBuffer } from './parquet-writer'
-import { replayIndexPartitions, replayIndexToParquetBuffer } from './replay-index'
+import { MlEncryptedEnvelope } from './privacy/crypto'
+import { EncryptedReplayIndex, replayIndexPartitions, replayIndexToParquetBuffer } from './replay-index'
+import { sessionStartMonth } from './session-identifier-format'
const cmp = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0)
@@ -34,6 +38,86 @@ export class BlockMetadataParquetStore {
if (rows.length === 0) {
return
}
+ if (rows.some((row) => row.format_version === 2)) {
+ throw new Error('ML v2 metadata must use encrypted storage')
+ }
+ await this.writeDataset(rows, this.prefix, `${this.prefix}-replay-index/v1`)
+ }
+
+ public async writeEncrypted(envelopes: MlEncryptedEnvelope[]): Promise<void> {
+ if (envelopes.length === 0) {
+ return
+ }
+ const months = new Map<string, MlEncryptedEnvelope[]>()
+ for (const envelope of envelopes) {
+ const month = sessionStartMonth(envelope.context.sessionId ?? '')
+ const group = months.get(month) ?? []
+ group.push(envelope)
+ months.set(month, group)
+ }
+ for (const [month, group] of months) {
+ const bytes = await this.writeEncryptedPartition(`${this.prefix}/v2/${month}`, group)
+ MlParquetSinkMetrics.observeWrite(group.length, bytes)
+ }
+ }
+
+ public async writeEncryptedReplayIndex(indexes: EncryptedReplayIndex[]): Promise<void> {
+ const partitions = new Map<string, EncryptedReplayIndex[]>()
+ for (const index of indexes) {
+ const { kind, envelope } = index
+ const month = sessionStartMonth(envelope.context.sessionId ?? '')
+ const partition = `${this.prefix}-replay-index/v2/${month}/kind=${kind}`
+ const group = partitions.get(partition) ?? []
+ group.push(index)
+ partitions.set(partition, group)
+ }
+ for (const [partition, group] of partitions) {
+ await this.writeEncryptedPartition(
+ partition,
+ group.map((index) => index.envelope)
+ )
+ MlParquetSinkMetrics.incReplayIndexRows(
+ group[0].kind,
+ group.reduce((count, index) => count + index.rowCount, 0)
+ )
+ }
+ }
+
+ private async writeEncryptedPartition(prefix: string, envelopes: MlEncryptedEnvelope[]): Promise<number> {
+ let body: Buffer
+ try {
+ const schema = new ParquetSchema({
+ format_version: { type: 'INT64' },
+ team_id: { type: 'UTF8' },
+ session_id: { type: 'UTF8' },
+ payload: { type: 'BYTE_ARRAY' },
+ })
+ body = await parquetRecordsToBuffer(
+ schema,
+ envelopes.map((envelope) => ({
+ format_version: 2n,
+ team_id: String(envelope.context.teamId),
+ session_id: envelope.context.sessionId,
+ payload: Buffer.from(JSON.stringify(envelope)),
+ }))
+ )
+ await this.s3Client.send(
+ new PutObjectCommand({
+ Bucket: this.bucket,
+ Key: `${prefix}/part-${this.nodeId}-${Date.now()}-${++this.seq}.parquet`,
+ Body: body,
+ ContentType: 'application/vnd.apache.parquet',
+ }),
+ { abortSignal: AbortSignal.timeout(30_000) }
+ )
+ } catch (error) {
+ MlParquetSinkMetrics.incWriteError()
+ throw error
+ }
+ return body.length
+ }
+
+ private async writeDataset(rows: MlBlockMetadataRow[], prefix: string, indexPrefix: string): Promise<void> {
// Sorting clusters a recording's blocks together for better compression and reads.
rows.sort((a, b) => cmp(a.team_id, b.team_id) || cmp(a.session_id, b.session_id))
let body: Buffer
@@ -48,7 +132,7 @@ export class BlockMetadataParquetStore {
await this.s3Client.send(
new PutObjectCommand({
Bucket: this.bucket,
- Key: `${this.prefix}-replay-index/v1/${partition}/part-${this.nodeId}-${Date.now()}-${this.seq}.parquet`,
+ Key: `${indexPrefix}/${partition}/part-${this.nodeId}-${Date.now()}-${this.seq}.parquet`,
Body: indexBody,
ContentType: 'application/vnd.apache.parquet',
})
@@ -57,7 +141,7 @@ export class BlockMetadataParquetStore {
}
body = await rowsToParquetBuffer(rows)
bounds = eventTimeBounds(rows)
- key = this.objectKey(new Date(bounds.minMs).toISOString().slice(0, 10))
+ key = this.objectKey(prefix, new Date(bounds.minMs).toISOString().slice(0, 10))
await this.s3Client.send(
new PutObjectCommand({
Bucket: this.bucket,
@@ -81,9 +165,9 @@ export class BlockMetadataParquetStore {
}
/** Partition by event date (`dt=`), but keep a write-time stamp + seq + pod id in the name for uniqueness. */
- private objectKey(dt: string): string {
+ private objectKey(prefix: string, dt: string): string {
this.seq += 1
- return `${this.prefix}/dt=${dt}/part-${this.nodeId}-${Date.now()}-${this.seq}.parquet`
+ return `${prefix}/dt=${dt}/part-${this.nodeId}-${Date.now()}-${this.seq}.parquet`
}
}
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 3cfdd3db4319..6172b44d98c8 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
@@ -50,7 +50,7 @@ describe('ml-mirror block-metadata-row', () => {
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.distinct_id).not.toContain('[email protected]')
+ expect(row).not.toHaveProperty('distinct_id')
expect(row.session_id).not.toBe('sess-1')
})
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 5af119fb9a2a..14c3379cffed 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,16 +1,16 @@
-/** One anonymized block's metadata for the ML Parquet datasets; ids are pseudonyms. */
+/** 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_DISTINCT_ID, PSEUDONYM_SESSION, PSEUDONYM_TEAM, pseudonymize } from './pseudonymize'
+import { PSEUDONYM_SESSION, PSEUDONYM_TEAM, pseudonymize } from './pseudonymize'
export interface MlBlockMetadataRow {
+ format_version?: 2
session_start_ts_ms?: number
replay_index_entries?: ReplayIndexEntry[]
replay_index_truncated?: boolean
session_id: string
team_id: string
- distinct_id: string
block_url: string
block_s3_key: string
block_byte_start: number | null
@@ -67,7 +67,6 @@ export function toBlockMetadataRow(block: SessionBlockMetadata, secret: string |
}),
session_id: pseudonymize(secret, PSEUDONYM_SESSION, block.sessionId),
team_id: pseudonymize(secret, PSEUDONYM_TEAM, String(block.teamId)),
- distinct_id: pseudonymize(secret, PSEUDONYM_DISTINCT_ID, block.distinctId),
block_url: block.blockUrl,
block_s3_key: key,
block_byte_start: start,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.test.ts
index 6d28b129dbdf..ed4012990323 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.test.ts
@@ -1,6 +1,22 @@
-import { resolveMlAnonymizeMaxConcurrency, resolveMlMirrorRedisConnection } from './config'
+import { getMlMirrorConfig, resolveMlAnonymizeMaxConcurrency, resolveMlMirrorRedisConnection } from './config'
describe('ml-mirror config', () => {
+ it.each(['S3_PREFIX', 'PSEUDONYM_SECRET', 'PSEUDONYM_KMS_REGION', 'PSEUDONYM_KEY_FINGERPRINT'] as const)(
+ 'resolves %s from either environment name with canonical precedence',
+ (suffix) => {
+ const canonical = `AI_RESEARCH_REPLAY_${suffix}` as const
+ const legacy = `SESSION_RECORDING_ML_${suffix}`
+ for (const [env, expected] of [
+ [{ [legacy]: 'legacy' }, 'legacy'],
+ [{ [canonical]: 'canonical' }, 'canonical'],
+ [{ [legacy]: 'legacy', [canonical]: 'canonical' }, 'canonical'],
+ [{ [legacy]: 'legacy', [canonical]: '' }, ''],
+ ] as const) {
+ expect(getMlMirrorConfig(env)[canonical]).toBe(expected)
+ }
+ }
+ )
+
describe('resolveMlAnonymizeMaxConcurrency', () => {
it.each([
['explicit value passes through verbatim, even above the pool', 8, 3, 4, 8],
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
index deea0a15a22a..6dc735b14793 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
@@ -1,21 +1,30 @@
import os from 'node:os'
+import { overrideConfigWithEnv } from '~/common/config/config'
import { KAFKA_SESSION_REPLAY_IMAGE_SCRUB_DLQ } from '~/common/config/kafka-topics'
import { RedisConnectionConfig } from '~/common/utils/db/redis'
export type MlMirrorConfig = {
+ AI_RESEARCH_REPLAY_PRIVACY_TABLE: string
+ AI_RESEARCH_REPLAY_KMS_KEY_ARN: string
+ AI_RESEARCH_REPLAY_AWS_REGION: string
+ AI_RESEARCH_REPLAY_KMS_REQUESTS_PER_SECOND: number
+ AI_RESEARCH_REPLAY_KEY_CACHE_MAX: number
+ AI_RESEARCH_REPLAY_KEY_CACHE_LIFETIME_MS: number
+ AI_RESEARCH_REPLAY_IMAGE_FETCH_V2_DYNAMODB_TABLE: string
+ AI_RESEARCH_REPLAY_S3_PREFIX: string
/** S3 key prefix under the bucket for the block-metadata Parquet dataset (used by the sink). */
SESSION_RECORDING_ML_METADATA_PREFIX: string
/** Optional S3 key of the `{ text, url }` allow-list document; empty → in-binary defaults. */
SESSION_RECORDING_ML_ALLOW_LIST_S3_KEY: string
- /** Plaintext HMAC secret to pseudonymize ids; for local dev only — prod uses the KMS-wrapped key below. */
- SESSION_RECORDING_ML_PSEUDONYM_SECRET: string
+ /** Plaintext root key for legacy identifiers and image hashes; local development only. Production uses the KMS-wrapped key below. */
+ AI_RESEARCH_REPLAY_PSEUDONYM_SECRET: string
/** Base64 KMS-encrypted pseudonym key (envelope); decrypted once at startup, never persisted. Preferred over the plaintext secret. */
SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY: string
/** AWS region for the KMS Decrypt call; empty → the SDK default credential/region chain. */
- SESSION_RECORDING_ML_PSEUDONYM_KMS_REGION: string
+ AI_RESEARCH_REPLAY_PSEUDONYM_KMS_REGION: string
/** Expected key fingerprint; if set, startup fails when the resolved key's fingerprint differs (enforces never-rotate). */
- SESSION_RECORDING_ML_PSEUDONYM_KEY_FINGERPRINT: string
+ AI_RESEARCH_REPLAY_PSEUDONYM_KEY_FINGERPRINT: string
/** Consumer group id for the Parquet-sink deployment that drains the metadata topic. */
SESSION_RECORDING_ML_PARQUET_SINK_GROUP_ID: string
/**
@@ -39,7 +48,7 @@ export type MlMirrorConfig = {
/**
* Produce collected original images to the scrub topic. Enabling changes the mirrored JSONL
- * shape: image fields carry `image:<pseudoTeam>:<hash>` refs instead of blurred data URIs, so
+ * shape: image fields carry `image:<teamId>:<hash>` refs instead of blurred data URIs, so
* both the scrub consumer lane AND ref-aware downstream readers must be live first.
*/
SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED: boolean
@@ -209,12 +218,20 @@ export type MlMirrorConfig = {
export function getDefaultMlMirrorConfig(): MlMirrorConfig {
return {
+ AI_RESEARCH_REPLAY_PRIVACY_TABLE: '',
+ AI_RESEARCH_REPLAY_KMS_KEY_ARN: '',
+ AI_RESEARCH_REPLAY_AWS_REGION: 'us-east-1',
+ AI_RESEARCH_REPLAY_KMS_REQUESTS_PER_SECOND: 100,
+ AI_RESEARCH_REPLAY_KEY_CACHE_MAX: 10_000,
+ AI_RESEARCH_REPLAY_KEY_CACHE_LIFETIME_MS: 60_000,
+ AI_RESEARCH_REPLAY_IMAGE_FETCH_V2_DYNAMODB_TABLE: '',
+ AI_RESEARCH_REPLAY_S3_PREFIX: 'rrweb_2',
SESSION_RECORDING_ML_METADATA_PREFIX: 'block-metadata',
SESSION_RECORDING_ML_ALLOW_LIST_S3_KEY: '',
- SESSION_RECORDING_ML_PSEUDONYM_SECRET: '',
+ AI_RESEARCH_REPLAY_PSEUDONYM_SECRET: '',
SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY: '',
- SESSION_RECORDING_ML_PSEUDONYM_KMS_REGION: '',
- SESSION_RECORDING_ML_PSEUDONYM_KEY_FINGERPRINT: '',
+ AI_RESEARCH_REPLAY_PSEUDONYM_KMS_REGION: '',
+ AI_RESEARCH_REPLAY_PSEUDONYM_KEY_FINGERPRINT: '',
SESSION_RECORDING_ML_PARQUET_SINK_GROUP_ID: 'session-replay-ml-parquet-sink',
SESSION_RECORDING_ML_PARQUET_FLUSH_INTERVAL_MS: 60 * 1000,
SESSION_RECORDING_ML_PARQUET_MAX_ROWS: 250_000,
@@ -270,6 +287,19 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {
}
}
+export function getMlMirrorConfig(env: Record<string, string | undefined> = process.env): MlMirrorConfig {
+ return overrideConfigWithEnv(getDefaultMlMirrorConfig(), {
+ ...env,
+ AI_RESEARCH_REPLAY_S3_PREFIX: env.AI_RESEARCH_REPLAY_S3_PREFIX ?? env.SESSION_RECORDING_ML_S3_PREFIX,
+ AI_RESEARCH_REPLAY_PSEUDONYM_SECRET:
+ env.AI_RESEARCH_REPLAY_PSEUDONYM_SECRET ?? env.SESSION_RECORDING_ML_PSEUDONYM_SECRET,
+ AI_RESEARCH_REPLAY_PSEUDONYM_KMS_REGION:
+ env.AI_RESEARCH_REPLAY_PSEUDONYM_KMS_REGION ?? env.SESSION_RECORDING_ML_PSEUDONYM_KMS_REGION,
+ AI_RESEARCH_REPLAY_PSEUDONYM_KEY_FINGERPRINT:
+ env.AI_RESEARCH_REPLAY_PSEUDONYM_KEY_FINGERPRINT ?? env.SESSION_RECORDING_ML_PSEUDONYM_KEY_FINGERPRINT,
+ })
+}
+
const DEFAULT_UV_THREADPOOL_SIZE = 4
/**
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 e7a0b1d55a83..6680de6c68a6 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
@@ -13,7 +13,7 @@ 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 { PSEUDONYM_DISTINCT_ID, PSEUDONYM_SESSION, PSEUDONYM_TEAM, pseudonymize } from './pseudonymize'
+import { PSEUDONYM_SESSION, PSEUDONYM_TEAM, pseudonymize } from './pseudonymize'
const SECRET = 'roundtrip-secret'
const SESSION_A = '018bcfe5-6800-7000-8000-000000000001'
@@ -132,7 +132,7 @@ describe('ML metadata producer → sink round-trip', () => {
const a = bySession.get(pseudonymize(SECRET, PSEUDONYM_SESSION, SESSION_A))!
expect(a).toBeDefined()
expect(a.team_id).toBe(pseudonymize(SECRET, PSEUDONYM_TEAM, '1'))
- expect(a.distinct_id).toBe(pseudonymize(SECRET, PSEUDONYM_DISTINCT_ID, 'person-1'))
+ 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))
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
index 4ddab906cdc3..74dd8cb1e0f6 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
@@ -264,8 +264,11 @@ export class MlParquetSinkMetrics {
public static incRowsParsed(count: number): void {
this.rowsParsed.inc(count)
}
- public static incRowsRejected(reason: 'parse_failed' | 'invalid'): void {
- this.rowsRejected.labels(reason).inc()
+ public static incRowsRejected(
+ reason: 'parse_failed' | 'invalid' | 'invalid_envelope' | 'privacy',
+ count = 1
+ ): void {
+ this.rowsRejected.labels(reason).inc(count)
}
public static observeWrite(rows: number, bytes: number): void {
this.objectsWritten.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 8b4fc8750d5a..fa83354185e6 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
@@ -46,7 +46,7 @@ describe('MlBlockMetadataSink', () => {
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.distinct_id).not.toContain('[email protected]')
+ expect(row).not.toHaveProperty('distinct_id')
expect(row.block_byte_end).toBe(9)
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/batch-controller.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/batch-controller.ts
new file mode 100644
index 000000000000..b1a6a6cf97e2
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/batch-controller.ts
@@ -0,0 +1,134 @@
+import pLimit from 'p-limit'
+
+import { PipelineResult, PipelineResultType, ok } from '~/ingestion/framework/results'
+import { usesRawSessionIdentifiers } from '~/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format'
+import {
+ DeleteKeyResult,
+ EncryptResult,
+ KeyStore,
+ RecordingEncryptor,
+ SessionKey,
+} from '~/ingestion/pipelines/sessionreplay/shared/types'
+
+import { MlKeyEncryption, encryptEnvelope } from './crypto'
+import { MlKeyBatch, MlSessionKeyStore, MlSessionKeys } from './key-store'
+import { MlKeyIdentity, MlSessionIdentity } from './schema'
+
+export interface MlRecordingKey extends SessionKey {
+ mlIdentity: MlKeyIdentity
+}
+
+export class MlPrivacyBatchController implements KeyStore, RecordingEncryptor {
+ private readonly publish = pLimit(8)
+ private batch?: MlKeyBatch
+ private deferred: Array<() => Promise<void>> = []
+
+ constructor(
+ private readonly store: MlSessionKeyStore,
+ private readonly encryption: MlKeyEncryption
+ ) {}
+
+ public async start(): Promise<void> {
+ await this.encryption.start()
+ }
+
+ public stop(): void {
+ this.encryption.clear()
+ }
+
+ public reset(): void {
+ this.batch = undefined
+ this.deferred = []
+ }
+
+ public async prepare(identities: MlSessionIdentity[]): Promise<void> {
+ this.deferred = []
+ this.batch = await this.store.prepare(
+ identities.filter((identity) => usesRawSessionIdentifiers(identity.sessionId))
+ )
+ }
+
+ public keys(teamId: number, sessionId: string): MlSessionKeys | undefined {
+ return this.batch?.get(teamId, sessionId)
+ }
+
+ public defer<T extends { team: { teamId: number }; headers: { session_id: string }; sessionKey: SessionKey }>(
+ input: T,
+ action: (input: T) => Promise<PipelineResult<T>>
+ ): Promise<PipelineResult<T>> {
+ this.deferred.push(async () => {
+ const key = await this.getKey(input.headers.session_id, input.team.teamId)
+ if (key.sessionState !== 'deleted') {
+ const result = await action({ ...input, sessionKey: key })
+ if (result.type === PipelineResultType.OK) {
+ await Promise.all(result.sideEffects ?? [])
+ }
+ }
+ })
+ return Promise.resolve(ok(input))
+ }
+
+ public async commit(): Promise<void> {
+ if (!this.batch) {
+ return
+ }
+ await this.batch.commit()
+ await Promise.all(this.deferred.map((action) => this.publish(action)))
+ this.deferred = []
+ }
+
+ public getKey(sessionId: string, teamId: number): Promise<SessionKey> {
+ if (!usesRawSessionIdentifiers(sessionId)) {
+ return Promise.resolve({
+ sessionState: 'cleartext',
+ plaintextKey: Buffer.alloc(0),
+ encryptedKey: Buffer.alloc(0),
+ })
+ }
+ const keys = this.keys(teamId, sessionId)
+ if (!keys) {
+ return Promise.resolve({
+ sessionState: 'deleted',
+ plaintextKey: Buffer.alloc(0),
+ encryptedKey: Buffer.alloc(0),
+ })
+ }
+ const key: MlRecordingKey = {
+ sessionState: 'ciphertext',
+ plaintextKey: keys.session.plaintext,
+ encryptedKey: keys.session.wrapped,
+ mlIdentity: keys.session.identity,
+ }
+ return Promise.resolve(key)
+ }
+
+ public generateKey(sessionId: string, teamId: number): Promise<SessionKey> {
+ return this.getKey(sessionId, teamId)
+ }
+
+ public deleteKey(): Promise<DeleteKeyResult> {
+ return Promise.reject(new Error('ML deletion requires the durable deletion workflow'))
+ }
+
+ public async encryptBlock(sessionId: string, teamId: number, data: Buffer): Promise<EncryptResult> {
+ return this.encryptBlockWithKey(sessionId, teamId, data, await this.getKey(sessionId, teamId))
+ }
+
+ public encryptBlockWithKey(_sessionId: string, _teamId: number, data: Buffer, key: SessionKey): EncryptResult {
+ if (key.sessionState === 'cleartext') {
+ return { data, sessionState: 'cleartext' }
+ }
+ if (key.sessionState !== 'ciphertext' || !('mlIdentity' in key)) {
+ throw new Error('ML block has no active encryption key')
+ }
+ const mlKey = key as MlRecordingKey
+ return {
+ data: encryptEnvelope(
+ { identity: mlKey.mlIdentity, plaintext: key.plaintextKey, wrapped: key.encryptedKey },
+ 'rrweb',
+ data
+ ),
+ sessionState: 'ciphertext',
+ }
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/crypto.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/crypto.test.ts
new file mode 100644
index 000000000000..4120b9ea2bf8
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/crypto.test.ts
@@ -0,0 +1,85 @@
+import { KMSClient } from '@aws-sdk/client-kms'
+
+import { parseJSON } from '~/common/utils/json-parse'
+
+import { MlDataKey, MlKeyEncryption, decryptEnvelope, encryptEnvelope } from './crypto'
+import { TrainingEncryptionVector } from './test-vectors'
+import { validateImageOwner } from './transport'
+
+const key: MlDataKey = {
+ identity: {
+ teamId: 7,
+ organizationId: '00000000-0000-4000-8000-000000000007',
+ sessionId: '01994569-4380-7000-8000-000000000007',
+ },
+ plaintext: Buffer.alloc(32, 7),
+ wrapped: Buffer.from('wrapped-test-key'),
+}
+
+describe('ML payload encryption', () => {
+ beforeAll(async () => {
+ await new MlKeyEncryption({ send: jest.fn() } as unknown as KMSClient, 'test-key').start()
+ })
+
+ it.each(['rrweb', 'metadata', 'image-source', 'image-frontier', 'image-shard', 'image-index', 'score'])(
+ 'binds %s payloads to their purpose and owner',
+ (kind) => {
+ const data = Buffer.from('private test payload')
+ const encoded = encryptEnvelope(key, kind, data)
+ expect(encoded.toString()).not.toContain(data.toString())
+ const envelope = parseJSON(encoded.toString())
+ expect(decryptEnvelope(key, envelope, kind)).toEqual(data)
+ expect(() => decryptEnvelope(key, envelope, 'wrong-purpose')).toThrow()
+ expect(() =>
+ decryptEnvelope({ ...key, identity: { ...key.identity, teamId: 8 } }, envelope, kind)
+ ).toThrow()
+ expect(() =>
+ decryptEnvelope(key, { ...envelope, context: { ...envelope.context, teamId: 8 } }, kind)
+ ).toThrow()
+ const corrupted = Buffer.from(envelope.ciphertext, 'base64')
+ corrupted[0] ^= 1
+ expect(() =>
+ decryptEnvelope(key, { ...envelope, ciphertext: corrupted.toString('base64') }, kind)
+ ).toThrow()
+ }
+ )
+
+ it('binds image months to the encrypted session start month', () => {
+ const timestamp = Date.parse('2026-09-30T23:59:59.999Z').toString(16).padStart(12, '0')
+ const sessionKey = {
+ ...key,
+ identity: {
+ ...key.identity,
+ sessionId: `${timestamp.slice(0, 8)}-${timestamp.slice(8)}-7000-8000-000000000007`,
+ },
+ }
+ const ref = `imageurl:v2:${key.identity.teamId}:2026-09:aaaaaaaaaaaaaaaaaaaaaa`
+ expect(() => validateImageOwner(ref, sessionKey)).not.toThrow()
+ expect(() => validateImageOwner(ref.replace('2026-09', '2026-10'), sessionKey)).toThrow('ownership mismatch')
+ })
+
+ it('decrypts the shared Python encryption vector', () => {
+ expect(
+ decryptEnvelope(
+ {
+ ...key,
+ identity: TrainingEncryptionVector.context,
+ plaintext: Buffer.from(TrainingEncryptionVector.key, 'base64'),
+ },
+ TrainingEncryptionVector.envelope,
+ 'rrweb'
+ )
+ ).toEqual(Buffer.from(TrainingEncryptionVector.data, 'base64'))
+ })
+
+ it('fits the largest fetched image in the ML Kafka transport budget', () => {
+ expect(
+ encryptEnvelope(
+ key,
+ 'image-source',
+ Buffer.alloc(20 * 1024 * 1024),
+ 'imageurl:v2:7:2026-09:aaaaaaaaaaaaaaaaaaaaaa'
+ ).length
+ ).toBeLessThan(40 * 1024 * 1024 + 64 * 1024)
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/crypto.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/crypto.ts
new file mode 100644
index 000000000000..311e8f788cf5
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/crypto.ts
@@ -0,0 +1,170 @@
+import { DecryptCommand, GenerateDataKeyCommand, KMSClient } from '@aws-sdk/client-kms'
+import sodium from 'libsodium-wrappers'
+import { LRUCache } from 'lru-cache'
+import { isDeepStrictEqual } from 'node:util'
+import pLimit from 'p-limit'
+
+import { parseJSON } from '~/common/utils/json-parse'
+
+import { MlKeyIdentity, wrappingContext } from './schema'
+
+export const KEY_READ_LEASE_MS = 300_000
+
+export class MlKeyReadExpiredError extends Error {}
+
+export interface MlDataKey {
+ identity: MlKeyIdentity
+ plaintext: Buffer
+ wrapped: Buffer
+ decryptUntil?: number
+}
+
+export interface MlEncryptedEnvelope {
+ v: 2
+ context: MlKeyIdentity & { kind: string; ref?: string }
+ nonce: string
+ ciphertext: string
+}
+
+export class MlKeyEncryption {
+ private readonly cache: LRUCache<string, Buffer>
+ private readonly pending = new Map<string, Promise<Buffer>>()
+ private readonly concurrency: ReturnType<typeof pLimit>
+ private nextRequestAt = 0
+
+ constructor(
+ private readonly kms: Pick<KMSClient, 'send'>,
+ private readonly masterKeyArn: string,
+ maxKeys = 10_000,
+ cacheLifetimeMs = 60_000,
+ concurrency = 8,
+ private readonly requestsPerSecond = 100
+ ) {
+ this.cache = new LRUCache({ max: maxKeys, ttl: cacheLifetimeMs })
+ this.concurrency = pLimit(concurrency)
+ if (requestsPerSecond <= 0) {
+ throw new Error('ML KMS request rate must be positive')
+ }
+ }
+
+ public async start(): Promise<void> {
+ await sodium.ready
+ }
+
+ private async request<T>(operation: () => Promise<T>): Promise<T> {
+ return this.concurrency(async () => {
+ const now = Date.now()
+ const scheduledAt = Math.max(now, this.nextRequestAt)
+ this.nextRequestAt = scheduledAt + 1000 / this.requestsPerSecond
+ if (scheduledAt > now) {
+ await new Promise((resolve) => setTimeout(resolve, scheduledAt - now))
+ }
+ return operation()
+ })
+ }
+
+ public async generate(identity: MlKeyIdentity): Promise<MlDataKey> {
+ const result = await this.request(() =>
+ this.kms.send(
+ new GenerateDataKeyCommand({
+ KeyId: this.masterKeyArn,
+ KeySpec: 'AES_256',
+ EncryptionContext: wrappingContext(identity),
+ }),
+ { abortSignal: AbortSignal.timeout(5000) }
+ )
+ )
+ if (result.Plaintext?.length !== 32 || !result.CiphertextBlob?.length) {
+ throw new Error('KMS returned an invalid ML data key')
+ }
+ return { identity, plaintext: Buffer.from(result.Plaintext), wrapped: Buffer.from(result.CiphertextBlob) }
+ }
+
+ public rememberCommitted(key: MlDataKey): void {
+ this.cache.set(this.cacheId(key.identity, key.wrapped), key.plaintext)
+ }
+
+ private cacheId(identity: MlKeyIdentity, wrapped: Buffer): string {
+ return JSON.stringify([wrappingContext(identity), wrapped.toString('base64')])
+ }
+
+ public async decrypt(identity: MlKeyIdentity, wrapped: Buffer): Promise<MlDataKey> {
+ const id = this.cacheId(identity, wrapped)
+ const cached = this.cache.get(id)
+ if (cached) {
+ return { identity, wrapped, plaintext: cached }
+ }
+ let pending = this.pending.get(id)
+ if (!pending) {
+ pending = this.request(async () => {
+ const result = await this.kms.send(
+ new DecryptCommand({
+ KeyId: this.masterKeyArn,
+ CiphertextBlob: wrapped,
+ EncryptionContext: wrappingContext(identity),
+ }),
+ { abortSignal: AbortSignal.timeout(5000) }
+ )
+ if (result.Plaintext?.length !== 32) {
+ throw new Error('KMS returned an invalid ML plaintext key')
+ }
+ const plaintext = Buffer.from(result.Plaintext)
+ this.cache.set(id, plaintext)
+ return plaintext
+ })
+ this.pending.set(id, pending)
+ }
+ try {
+ return { identity, wrapped, plaintext: await pending }
+ } finally {
+ if (this.pending.get(id) === pending) {
+ this.pending.delete(id)
+ }
+ }
+ }
+
+ public clear(): void {
+ this.cache.clear()
+ }
+}
+
+export function encryptEnvelope(key: MlDataKey, kind: string, data: Buffer, ref?: string): Buffer {
+ const context = { ...key.identity, kind, ...(ref ? { ref } : {}) }
+ const nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES)
+ const authenticated = Buffer.from(JSON.stringify({ context, data: data.toString('base64') }))
+ const envelope: MlEncryptedEnvelope = {
+ v: 2,
+ context,
+ nonce: Buffer.from(nonce).toString('base64'),
+ ciphertext: Buffer.from(sodium.crypto_secretbox_easy(authenticated, nonce, key.plaintext)).toString('base64'),
+ }
+ return Buffer.from(JSON.stringify(envelope))
+}
+
+export function decryptEnvelope(key: MlDataKey, envelope: MlEncryptedEnvelope, kind: string, ref?: string): Buffer {
+ if (key.decryptUntil !== undefined && performance.now() >= key.decryptUntil) {
+ throw new MlKeyReadExpiredError('ML key read lease expired; read the key again')
+ }
+ const decoded: unknown = parseJSON(
+ Buffer.from(
+ sodium.crypto_secretbox_open_easy(
+ Buffer.from(envelope.ciphertext, 'base64'),
+ Buffer.from(envelope.nonce, 'base64'),
+ key.plaintext
+ )
+ ).toString('utf8')
+ )
+ if (!decoded || typeof decoded !== 'object' || !('context' in decoded) || !('data' in decoded)) {
+ throw new Error('Invalid authenticated ML envelope')
+ }
+ const context = { ...key.identity, kind, ...(ref ? { ref } : {}) }
+ if (
+ envelope.v !== 2 ||
+ !isDeepStrictEqual(decoded.context, context) ||
+ !isDeepStrictEqual(envelope.context, context) ||
+ typeof decoded.data !== 'string'
+ ) {
+ throw new Error('ML envelope context mismatch')
+ }
+ return Buffer.from(decoded.data, 'base64')
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/dynamodb.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/dynamodb.ts
new file mode 100644
index 000000000000..a068d6cc3ad4
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/dynamodb.ts
@@ -0,0 +1,99 @@
+import {
+ AttributeValue,
+ BatchGetItemCommand,
+ DynamoDBClient,
+ TransactWriteItem,
+ TransactWriteItemsCommand,
+} from '@aws-sdk/client-dynamodb'
+import pLimit from 'p-limit'
+
+import { TableKey, tableKeyString } from './schema'
+
+export type DynamoItem = Record<string, AttributeValue>
+
+export function encodeKey(key: TableKey): DynamoItem {
+ return { pk: { S: key.pk }, sk: { S: key.sk } }
+}
+
+export function decodeKey(item: DynamoItem): TableKey {
+ if (!item.pk?.S || !item.sk?.S) {
+ throw new Error('Invalid ML privacy item key')
+ }
+ return { pk: item.pk.S, sk: item.sk.S }
+}
+
+export class MlPrivacyDynamoDB {
+ private readonly concurrency = pLimit(4)
+
+ constructor(
+ private readonly client: Pick<DynamoDBClient, 'send'>,
+ readonly tableName: string,
+ private readonly requestTimeoutMs = 5_000,
+ private readonly attempts = 5
+ ) {}
+
+ public async read(keys: TableKey[]): Promise<Map<string, DynamoItem>> {
+ const unique = [...new Map(keys.map((key) => [tableKeyString(key), key])).values()]
+ const result = new Map<string, DynamoItem>()
+ const chunks: TableKey[][] = []
+ for (let offset = 0; offset < unique.length; offset += 100) {
+ chunks.push(unique.slice(offset, offset + 100))
+ }
+ await Promise.all(
+ chunks.map((chunk) =>
+ this.concurrency(async () => {
+ let pending = chunk.map(encodeKey)
+ for (let attempt = 0; pending.length && attempt < this.attempts; attempt++) {
+ const response = await this.client.send(
+ new BatchGetItemCommand({
+ RequestItems: { [this.tableName]: { Keys: pending, ConsistentRead: true } },
+ }),
+ { abortSignal: AbortSignal.timeout(this.requestTimeoutMs) }
+ )
+ for (const item of response.Responses?.[this.tableName] ?? []) {
+ result.set(tableKeyString(decodeKey(item)), item)
+ }
+ pending = response.UnprocessedKeys?.[this.tableName]?.Keys ?? []
+ if (pending.length) {
+ await this.backoff(attempt)
+ }
+ }
+ if (pending.length) {
+ throw new Error('ML privacy bulk read exhausted retries')
+ }
+ })
+ )
+ )
+ return result
+ }
+
+ public async write(transactions: TransactWriteItem[][]): Promise<void> {
+ await Promise.all(
+ transactions.map((items) =>
+ this.concurrency(async () => {
+ if (!items.length || items.length > 100) {
+ throw new Error('Invalid ML privacy transaction size')
+ }
+ await this.client.send(new TransactWriteItemsCommand({ TransactItems: items }), {
+ abortSignal: AbortSignal.timeout(this.requestTimeoutMs),
+ })
+ })
+ )
+ )
+ }
+
+ public async backoff(attempt: number): Promise<void> {
+ await new Promise((resolve) => setTimeout(resolve, Math.min(1000, 50 * 2 ** attempt) + Math.random() * 50))
+ }
+
+ public check(key: TableKey, condition: string, values?: DynamoItem): TransactWriteItem {
+ return {
+ ConditionCheck: {
+ TableName: this.tableName,
+ Key: encodeKey(key),
+ ConditionExpression: condition,
+ ...(values ? { ExpressionAttributeValues: values } : {}),
+ },
+ }
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/encryption-vector.json b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/encryption-vector.json
new file mode 100644
index 000000000000..0695dc8aa88e
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/encryption-vector.json
@@ -0,0 +1,20 @@
+{
+ "context": {
+ "teamId": 7,
+ "organizationId": "00000000-0000-4000-8000-000000000007",
+ "sessionId": "01994569-4380-7000-8000-000000000007"
+ },
+ "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=",
+ "data": "c3ludGhldGljIGludGVyb3BlcmFiaWxpdHkgcGF5bG9hZA==",
+ "envelope": {
+ "v": 2,
+ "context": {
+ "teamId": 7,
+ "organizationId": "00000000-0000-4000-8000-000000000007",
+ "sessionId": "01994569-4380-7000-8000-000000000007",
+ "kind": "rrweb"
+ },
+ "nonce": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMD",
+ "ciphertext": "J7ZDxBv0xIHU+NbDMakk4Zfw4/QVzp9N/3Nou2Fw5EHMoFUnJlmLR1uMpdNQ9RzghmLG2IQZxuytZzl6nXIwDjThieTFFxsTD88iry/Q3f/IUXtrfO8AwN71Edwmw5cQe4BWZiI1F3lmYLi3SqiwWWOgDAQcaFAy95e9dIaB2uMh74M1617MqtZLMQnnvLwoDUSk60ovZhTwL5spBFy02JOaAOxpazluT8+qeuQEzfgI+/54rUzdJPg6gScSOBIAQWp3Jbk9xVOrxtdqLB4BtPKAPYwqFwIJtuS/UQ=="
+ }
+}
diff --git a/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
new file mode 100644
index 000000000000..4e984be00f64
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.test.ts
@@ -0,0 +1,343 @@
+import { BatchGetItemCommand, DynamoDBClient, TransactWriteItemsCommand } from '@aws-sdk/client-dynamodb'
+import { GenerateDataKeyCommand, KMSClient } from '@aws-sdk/client-kms'
+import { S3Client } from '@aws-sdk/client-s3'
+import { Message } from 'node-rdkafka'
+import { register } from 'prom-client'
+
+import { parseJSON } from '~/common/utils/json-parse'
+import { ok } from '~/ingestion/framework/results'
+import { BlockMetadataBatcher } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher'
+import { BlockMetadataParquetStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store'
+import { toBlockMetadataRow } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-row'
+import { createNoopBlockMetadata } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata'
+
+import { MlPrivacyBatchController } from './batch-controller'
+import { MlKeyEncryption } from './crypto'
+import { DynamoItem, MlPrivacyDynamoDB, encodeKey } from './dynamodb'
+import { MlSessionKeyStore } from './key-store'
+import { MlKeyReader } from './reader'
+import { MlSessionIdentity, imageKeyId, monthBlockId, monthKeyIndexId, sessionKeyId, tableKeyString } from './schema'
+import { MlKafkaEncryption, encryptedKafkaValue } from './transport'
+
+const session: MlSessionIdentity = {
+ teamId: 7,
+ organizationId: 'organization-test',
+ sessionId: '01994569-4380-7000-8000-000000000007',
+}
+const table = 'ml-privacy-test'
+
+class DynamoBoundary {
+ public readonly items = new Map<string, DynamoItem>()
+ public readSizes: number[] = []
+ public writeSizes: number[] = []
+ public transactionConflicts = 0
+ private readonly pendingWrites = new Set<string>()
+
+ public async send(command: BatchGetItemCommand | TransactWriteItemsCommand): Promise<object> {
+ if (command instanceof BatchGetItemCommand) {
+ const keys = command.input.RequestItems![table].Keys!
+ if (keys.some((key) => Buffer.byteLength(key.sk.S!) > 1024)) {
+ throw new Error('DynamoDB sort key exceeds 1024 bytes')
+ }
+ this.readSizes.push(keys.length)
+ return Promise.resolve({
+ Responses: {
+ [table]: keys.flatMap((key) => {
+ const value = this.items.get(JSON.stringify([key.pk.S, key.sk.S]))
+ return value ? [value] : []
+ }),
+ },
+ })
+ }
+ const actions = command.input.TransactItems!
+ const writes = actions.flatMap((action) =>
+ action.Put ? [JSON.stringify([action.Put.Item!.pk.S, action.Put.Item!.sk.S])] : []
+ )
+ if (writes.some((key) => this.pendingWrites.has(key))) {
+ this.transactionConflicts += 1
+ throw new Error('Conflicting transaction write')
+ }
+ writes.forEach((key) => this.pendingWrites.add(key))
+ try {
+ await Promise.resolve()
+ this.writeSizes.push(actions.length)
+ for (const action of actions) {
+ const operation = action.ConditionCheck ?? action.Put!
+ const key = 'Item' in operation ? operation.Item! : operation.Key!
+ const current = this.items.get(JSON.stringify([key.pk.S, key.sk.S]))
+ const condition = operation.ConditionExpression
+ const valid =
+ !condition ||
+ (condition === 'attribute_not_exists(pk)'
+ ? !current
+ : condition === 'attribute_exists(wrapped_key) AND attribute_not_exists(deleted)'
+ ? current?.wrapped_key?.B && !current?.deleted
+ : false)
+ if (!valid) {
+ throw new Error('Conditional transaction failed')
+ }
+ }
+ for (const action of actions) {
+ if (action.Put) {
+ const item = action.Put.Item!
+ this.items.set(JSON.stringify([item.pk.S, item.sk.S]), item)
+ }
+ }
+ return {}
+ } finally {
+ writes.forEach((key) => this.pendingWrites.delete(key))
+ }
+ }
+}
+
+describe('ML session key batches', () => {
+ let boundary: DynamoBoundary
+ let encryption: MlKeyEncryption
+ let store: MlSessionKeyStore
+ let reader: MlKeyReader
+ let generated: number
+
+ beforeEach(async () => {
+ boundary = new DynamoBoundary()
+ generated = 0
+ encryption = new MlKeyEncryption(
+ {
+ send: jest.fn((command) => {
+ if (command instanceof GenerateDataKeyCommand) {
+ const bytes = Buffer.alloc(32, ++generated)
+ return Promise.resolve({ Plaintext: bytes, CiphertextBlob: bytes })
+ }
+ return Promise.resolve({ Plaintext: command.input.CiphertextBlob })
+ }),
+ } as unknown as KMSClient,
+ 'test-key',
+ 1000,
+ 60000,
+ 8,
+ 1_000_000_000
+ )
+ await encryption.start()
+ const db = new MlPrivacyDynamoDB(boundary as unknown as DynamoDBClient, table)
+ store = new MlSessionKeyStore(db, encryption)
+ reader = new MlKeyReader(db, encryption)
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ it('deduplicates repeated sessions and stores only keys and month indexes', async () => {
+ const identities = Array.from({ length: 120 }, () => ({ ...session }))
+ const batch = await store.prepare(identities)
+ expect(generated).toBe(2)
+ await batch.commit()
+ expect(boundary.items.size).toBe(4)
+ expect(Math.max(...boundary.readSizes)).toBeLessThanOrEqual(100)
+ expect(Math.max(...boundary.writeSizes)).toBeLessThanOrEqual(100)
+ expect((await reader.read([sessionKeyId(session.teamId, session.sessionId)])).size).toBe(1)
+ })
+
+ it('commits concurrent new sessions in bounded transactions', async () => {
+ await (await store.prepare([session])).commit()
+ const identities = Array.from({ length: 120 }, (_, index) => ({
+ ...session,
+ sessionId: `01994569-4380-7000-8000-${(index + 100).toString(16).padStart(12, '0')}`,
+ }))
+ const batches = await Promise.all([store.prepare(identities.slice(0, 60)), store.prepare(identities.slice(60))])
+ jest.useFakeTimers()
+ const committed = Promise.all(batches.map((batch) => batch.commit()))
+ await jest.runAllTimersAsync()
+ await committed
+ const keys = await reader.read(identities.map((identity) => sessionKeyId(identity.teamId, identity.sessionId)))
+ expect(keys.size).toBe(identities.length)
+ expect(boundary.transactionConflicts).toBe(0)
+ })
+
+ it('indexes monthly keys atomically and blocks a month during a competing batch', async () => {
+ const october = { ...session, sessionId: '0199a13b-c000-7000-8000-000000000007' }
+ const first = await store.prepare([session, october])
+ await first.commit()
+ const septemberKeys = first.get(session.teamId, session.sessionId)!
+ const octoberKeys = first.get(october.teamId, october.sessionId)!
+ expect(septemberKeys.image.plaintext).not.toEqual(octoberKeys.image.plaintext)
+ for (const key of [septemberKeys.session, septemberKeys.image, octoberKeys.session, octoberKeys.image]) {
+ const location = key.identity.sessionId
+ ? sessionKeyId(key.identity.teamId, key.identity.sessionId)
+ : imageKeyId(key.identity.teamId, key.identity.sessionMonth!)
+ expect(boundary.items.get(tableKeyString(monthKeyIndexId(key.identity, location)))).toMatchObject({
+ key_pk: { S: location.pk },
+ key_sk: { S: location.sk },
+ })
+ }
+ const inFlight = await store.prepare([session])
+ const blocked = monthBlockId('2025-09')
+ boundary.items.set(tableKeyString(blocked), { ...encodeKey(blocked), deleted: { BOOL: true } })
+ jest.useFakeTimers()
+ const committing = inFlight.commit()
+ await jest.runAllTimersAsync()
+ await committing
+ expect(inFlight.get(session.teamId, session.sessionId)).toBeUndefined()
+ const locations = [
+ sessionKeyId(session.teamId, session.sessionId),
+ imageKeyId(session.teamId, '2025-09'),
+ sessionKeyId(october.teamId, october.sessionId),
+ imageKeyId(session.teamId, '2025-10'),
+ ]
+ expect([...(await reader.read(locations))].map(([id]) => id)).toEqual(locations.slice(2).map(tableKeyString))
+ })
+
+ it('adopts a competing writer key', async () => {
+ const first = await store.prepare([session])
+ const second = await store.prepare([session])
+ const provisional = second.get(session.teamId, session.sessionId)!.session.plaintext
+ await first.commit()
+ jest.useFakeTimers()
+ const committing = second.commit()
+ await jest.runAllTimersAsync()
+ await committing
+ expect(second.get(session.teamId, session.sessionId)!.session.plaintext).toEqual(
+ first.get(session.teamId, session.sessionId)!.session.plaintext
+ )
+ expect(second.get(session.teamId, session.sessionId)!.session.plaintext).not.toEqual(provisional)
+ })
+
+ it('blocks an existing session deleted during a batch', async () => {
+ const first = await store.prepare([session])
+ await first.commit()
+ const next = await store.prepare([session])
+ const blocked = sessionKeyId(session.teamId, session.sessionId)
+ boundary.items.set(tableKeyString(blocked), { ...encodeKey(blocked), deleted: { BOOL: true } })
+ jest.useFakeTimers()
+ const committed = next.commit()
+ await jest.runAllTimersAsync()
+ await committed
+ expect(next.get(session.teamId, session.sessionId)).toBeUndefined()
+ expect((await reader.read([sessionKeyId(session.teamId, session.sessionId)])).size).toBe(0)
+ expect((await reader.read([imageKeyId(session.teamId, '2025-09')])).size).toBe(1)
+ })
+
+ it('reuses the session and monthly image keys across batches', async () => {
+ const first = await store.prepare([session])
+ await first.commit()
+ const original = first.get(session.teamId, session.sessionId)!
+ const resumed = await store.prepare([session])
+ await resumed.commit()
+ const keys = resumed.get(session.teamId, session.sessionId)!
+ expect(keys.session.plaintext).toEqual(original.session.plaintext)
+ expect(keys.image.plaintext).toEqual(original.image.plaintext)
+ expect((await reader.read([sessionKeyId(session.teamId, session.sessionId)])).size).toBe(1)
+ expect(generated).toBe(2)
+ })
+
+ it('publishes a bounded concurrent batch only after privacy writes commit', async () => {
+ const identity = { ...session, sessionId: '01a0a482-5500-7000-8000-000000000001' }
+ const controller = new MlPrivacyBatchController(store, encryption)
+ await controller.prepare([identity])
+ let release!: () => void
+ const delivery = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ let started = 0
+ let firstWaveStarted!: () => void
+ const firstWave = new Promise<void>((resolve) => {
+ firstWaveStarted = resolve
+ })
+ const input = {
+ team: { teamId: identity.teamId },
+ headers: { session_id: identity.sessionId },
+ sessionKey: await controller.getKey(identity.sessionId, identity.teamId),
+ }
+ for (let index = 0; index < 20; index++) {
+ await controller.defer(input, (value) => {
+ expect(
+ boundary.items.get(tableKeyString(sessionKeyId(identity.teamId, identity.sessionId)))?.wrapped_key
+ ).toBeDefined()
+ if (++started === 8) {
+ firstWaveStarted()
+ }
+ return Promise.resolve(ok(value, [delivery]))
+ })
+ }
+ const committed = controller.commit()
+ await firstWave
+ expect(started).toBe(8)
+ release()
+ await committed
+ expect(started).toBe(20)
+ })
+ it.each(['invalid-json', 'oversized-session', 'invalid-session', 'invalid-month'])(
+ 'reports accepted, malformed (%s) and deleted encrypted metadata separately',
+ async (malformed) => {
+ register.resetMetrics()
+ const deleted = { ...session, sessionId: '01994569-4380-7000-8000-000000000008' }
+ const batch = await store.prepare([session, deleted])
+ await batch.commit()
+ const messages = [session, deleted].map((identity, offset) => {
+ const encoded = encryptedKafkaValue(
+ batch.get(identity.teamId, identity.sessionId)!.session,
+ 'metadata',
+ Buffer.from(
+ JSON.stringify({
+ ...toBlockMetadataRow(
+ {
+ ...createNoopBlockMetadata(identity.sessionId, identity.teamId),
+ blockUrl: 's3://bucket/block',
+ },
+ 'test'
+ ),
+ session_id: identity.sessionId,
+ team_id: String(identity.teamId),
+ format_version: 2,
+ })
+ )
+ )
+ return {
+ topic: 'metadata',
+ partition: 0,
+ offset,
+ value: encoded.value,
+ headers: Object.entries(encoded.headers).map(([name, value]) => ({ [name]: Buffer.from(value) })),
+ } as Message
+ })
+ boundary.items.delete(tableKeyString(sessionKeyId(deleted.teamId, deleted.sessionId)))
+ const invalidEnvelope = parseJSON(messages[0].value!.toString())
+ invalidEnvelope.context.sessionId =
+ malformed === 'oversized-session'
+ ? 'a'.repeat(1025)
+ : malformed === 'invalid-month'
+ ? 'ffffffff-ffff-7000-8000-000000000007'
+ : 'not-a-session'
+ messages.push({
+ ...messages[0],
+ offset: 2,
+ value: Buffer.from(malformed === 'invalid-json' ? 'invalid' : JSON.stringify(invalidEnvelope)),
+ })
+ const upload = jest.fn().mockResolvedValue({})
+ const offsetsStore = jest.fn()
+ const batcher = new BlockMetadataBatcher(
+ new BlockMetadataParquetStore(
+ { send: upload } as unknown as S3Client,
+ 'ml-bucket',
+ 'block-metadata',
+ 'pod'
+ ),
+ { offsetsStore },
+ { flushIntervalMs: 1000, maxRows: 1 },
+ 0,
+ new MlKafkaEncryption(reader)
+ )
+ await batcher.handleBatch(messages, 0)
+ expect(upload).toHaveBeenCalledTimes(1)
+ expect(offsetsStore).toHaveBeenCalledWith([{ topic: 'metadata', partition: 0, offset: 3 }])
+ const accepted = await register.getSingleMetric('ml_mirror_parquet_sink_rows_parsed_total')!.get()
+ expect(accepted.values[0].value).toBe(1)
+ const rejected = await register.getSingleMetric('ml_mirror_parquet_sink_rows_rejected_total')!.get()
+ expect(rejected.values).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ labels: { reason: 'privacy' }, value: 1 }),
+ expect.objectContaining({ labels: { reason: 'invalid_envelope' }, value: 1 }),
+ ])
+ )
+ }
+ )
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.ts
new file mode 100644
index 000000000000..22e4ece23946
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.ts
@@ -0,0 +1,249 @@
+import { TransactWriteItem } from '@aws-sdk/client-dynamodb'
+
+import { sessionStartMonth } from '~/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format'
+
+import { MlDataKey, MlKeyEncryption } from './crypto'
+import { DynamoItem, MlPrivacyDynamoDB, encodeKey } from './dynamodb'
+import {
+ MlKeyIdentity,
+ MlSessionIdentity,
+ TableKey,
+ imageKeyId,
+ keySessionMonth,
+ monthBlockId,
+ monthKeyIndexId,
+ sessionKeyId,
+ tableKeyString,
+ teamBlockId,
+} from './schema'
+
+export interface MlSessionKeys {
+ session: MlDataKey
+ image: MlDataKey
+}
+
+function storedKeyId(identity: MlKeyIdentity): TableKey {
+ return identity.sessionId
+ ? sessionKeyId(identity.teamId, identity.sessionId)
+ : imageKeyId(identity.teamId, keySessionMonth(identity))
+}
+
+function actionId(action: TransactWriteItem): string {
+ const operation = action.ConditionCheck ?? action.Put ?? action.Update ?? action.Delete
+ if (!operation) {
+ throw new Error('Empty ML privacy transaction action')
+ }
+ const key = 'Item' in operation ? operation.Item : 'Key' in operation ? operation.Key : undefined
+ if (!key?.pk?.S || !key.sk?.S) {
+ throw new Error('Missing ML privacy transaction key')
+ }
+ return JSON.stringify([key.pk.S, key.sk.S])
+}
+
+export function groupTransactions(units: TransactWriteItem[][]): TransactWriteItem[][] {
+ const transactions: TransactWriteItem[][] = []
+ let current = new Map<string, TransactWriteItem>()
+ for (const unit of units) {
+ const next = new Map(current)
+ for (const action of unit) {
+ const id = actionId(action)
+ const existing = next.get(id)
+ if (existing && JSON.stringify(existing) !== JSON.stringify(action)) {
+ throw new Error('Conflicting ML privacy transaction actions')
+ }
+ next.set(id, action)
+ }
+ if (next.size > 100 || Buffer.byteLength(JSON.stringify([...next.values()])) > 3_500_000) {
+ if (!current.size) {
+ throw new Error('ML privacy transaction unit exceeds limits')
+ }
+ transactions.push([...current.values()])
+ current = new Map(unit.map((action) => [actionId(action), action]))
+ } else {
+ current = next
+ }
+ }
+ if (current.size) {
+ transactions.push([...current.values()])
+ }
+ return transactions
+}
+
+export class MlSessionKeyStore {
+ constructor(
+ private readonly db: MlPrivacyDynamoDB,
+ private readonly encryption: MlKeyEncryption
+ ) {}
+
+ public async prepare(identities: MlSessionIdentity[]): Promise<MlKeyBatch> {
+ const eligible = identities.filter((identity) => {
+ try {
+ sessionStartMonth(identity.sessionId)
+ return true
+ } catch {
+ return false
+ }
+ })
+ const batch = new MlKeyBatch(this.db, this.encryption, eligible)
+ await batch.read()
+ return batch
+ }
+}
+
+export class MlKeyBatch {
+ private state = new Map<string, DynamoItem>()
+ private readonly candidates = new Map<string, MlDataKey>()
+ private readonly keys = new Map<string, MlDataKey>()
+ private committed = false
+
+ constructor(
+ private readonly db: MlPrivacyDynamoDB,
+ private readonly encryption: MlKeyEncryption,
+ private readonly identities: MlSessionIdentity[]
+ ) {}
+
+ public async read(): Promise<void> {
+ this.keys.clear()
+ const initial = this.identities.flatMap((identity) => [
+ monthBlockId(sessionStartMonth(identity.sessionId)),
+ teamBlockId(identity.teamId),
+ sessionKeyId(identity.teamId, identity.sessionId),
+ ])
+ this.state = await this.db.read(initial)
+ const keyIdentities = new Map<string, MlKeyIdentity>()
+ for (const identity of this.identities) {
+ const id = tableKeyString(sessionKeyId(identity.teamId, identity.sessionId))
+ if (
+ this.state.has(tableKeyString(teamBlockId(identity.teamId))) ||
+ this.state.has(tableKeyString(monthBlockId(sessionStartMonth(identity.sessionId)))) ||
+ this.state.get(id)?.deleted?.BOOL === true
+ ) {
+ continue
+ }
+ for (const sessionId of [identity.sessionId, undefined]) {
+ const keyIdentity = {
+ teamId: identity.teamId,
+ organizationId: identity.organizationId,
+ ...(sessionId ? { sessionId } : { sessionMonth: sessionStartMonth(identity.sessionId) }),
+ }
+ keyIdentities.set(tableKeyString(storedKeyId(keyIdentity)), keyIdentity)
+ }
+ }
+ const remaining = [...keyIdentities.values()].filter((identity) => !identity.sessionId).map(storedKeyId)
+ for (const [id, item] of await this.db.read(remaining)) {
+ this.state.set(id, item)
+ }
+ await Promise.all(
+ [...keyIdentities].map(async ([id, identity]) => {
+ const item = this.state.get(id)
+ if (item?.deleted?.BOOL === true) {
+ return
+ }
+ if (item) {
+ if (!item.wrapped_key?.B || item.organization_id?.S !== identity.organizationId) {
+ throw new Error('Invalid stored ML key identity')
+ }
+ this.keys.set(id, await this.encryption.decrypt(identity, Buffer.from(item.wrapped_key.B)))
+ } else {
+ let candidate = this.candidates.get(id)
+ if (!candidate) {
+ candidate = await this.encryption.generate(identity)
+ this.candidates.set(id, candidate)
+ }
+ this.keys.set(id, candidate)
+ }
+ })
+ )
+ }
+
+ public get(teamId: number, sessionId: string): MlSessionKeys | undefined {
+ const id = tableKeyString(sessionKeyId(teamId, sessionId))
+ const session = this.keys.get(id)
+ if (!session) {
+ return undefined
+ }
+ const image = this.keys.get(tableKeyString(imageKeyId(teamId, sessionStartMonth(sessionId))))
+ return image ? { session, image } : undefined
+ }
+
+ private guards(identity: MlKeyIdentity): TransactWriteItem[] {
+ return [
+ this.db.check(monthBlockId(keySessionMonth(identity)), 'attribute_not_exists(pk)'),
+ this.db.check(teamBlockId(identity.teamId), 'attribute_not_exists(pk)'),
+ ]
+ }
+
+ private put(key: TableKey, attributes: DynamoItem, condition?: string): TransactWriteItem {
+ return {
+ Put: {
+ TableName: this.db.tableName,
+ Item: { ...encodeKey(key), ...attributes },
+ ...(condition ? { ConditionExpression: condition } : {}),
+ },
+ }
+ }
+
+ private async persist(): Promise<void> {
+ const creations: TransactWriteItem[][] = []
+ for (const [id, key] of this.keys) {
+ if (this.state.has(id)) {
+ continue
+ }
+ creations.push([
+ ...this.guards(key.identity),
+ this.put(
+ storedKeyId(key.identity),
+ {
+ wrapped_key: { B: key.wrapped },
+ organization_id: { S: key.identity.organizationId },
+ team_id: { N: String(key.identity.teamId) },
+ session_month: { S: keySessionMonth(key.identity) },
+ },
+ 'attribute_not_exists(pk)'
+ ),
+ this.put(monthKeyIndexId(key.identity, storedKeyId(key.identity)), {
+ key_pk: { S: storedKeyId(key.identity).pk },
+ key_sk: { S: storedKeyId(key.identity).sk },
+ }),
+ ])
+ }
+ await this.db.write(groupTransactions(creations))
+ const validations: TransactWriteItem[][] = []
+ for (const identity of this.identities) {
+ const key = this.get(identity.teamId, identity.sessionId)?.session
+ if (!key) {
+ continue
+ }
+ validations.push([
+ ...this.guards(key.identity),
+ this.db.check(
+ sessionKeyId(identity.teamId, identity.sessionId),
+ 'attribute_exists(wrapped_key) AND attribute_not_exists(deleted)'
+ ),
+ ])
+ }
+ await this.db.write(groupTransactions(validations))
+ }
+
+ public async commit(): Promise<void> {
+ if (this.committed) {
+ throw new Error('ML batch already committed')
+ }
+ for (let attempt = 0; attempt < 5; attempt++) {
+ try {
+ await this.persist()
+ for (const key of this.keys.values()) {
+ this.encryption.rememberCommitted(key)
+ }
+ this.committed = true
+ return
+ } catch (error) {
+ if (attempt === 4) {
+ throw error
+ }
+ await this.db.backoff(attempt)
+ await this.read()
+ }
+ }
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/legacy-key-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/legacy-key-store.ts
new file mode 100644
index 000000000000..537330a9baa6
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/legacy-key-store.ts
@@ -0,0 +1,16 @@
+import { usesRawSessionIdentifiers } from '~/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format'
+import { CleartextKeyStore } from '~/ingestion/pipelines/sessionreplay/shared/keystore/cleartext-keystore'
+import { SessionKey } from '~/ingestion/pipelines/sessionreplay/shared/types'
+
+export class LegacyMlKeyStore extends CleartextKeyStore {
+ public override getKey(sessionId: string, teamId: number): Promise<SessionKey> {
+ if (usesRawSessionIdentifiers(sessionId)) {
+ throw new Error('ML v2 ingestion requires privacy configuration')
+ }
+ return super.getKey(sessionId, teamId)
+ }
+
+ public override generateKey(sessionId: string, teamId: number): Promise<SessionKey> {
+ return this.getKey(sessionId, teamId)
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/reader.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/reader.ts
new file mode 100644
index 000000000000..316a972fe46f
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/reader.ts
@@ -0,0 +1,54 @@
+import { KEY_READ_LEASE_MS, MlDataKey, MlKeyEncryption } from './crypto'
+import { MlPrivacyDynamoDB } from './dynamodb'
+import { MlKeyIdentity, TableKey, keySessionMonth, monthBlockId, tableKeyString, teamBlockId } from './schema'
+
+export class MlKeyReader {
+ constructor(
+ private readonly db: MlPrivacyDynamoDB,
+ private readonly encryption: MlKeyEncryption
+ ) {}
+
+ public async read(keys: TableKey[]): Promise<Map<string, MlDataKey>> {
+ const decryptUntil = performance.now() + KEY_READ_LEASE_MS
+ const stored = await this.db.read(keys)
+ const identities = new Map<string, MlKeyIdentity>()
+ for (const [id, item] of stored) {
+ if (!item.wrapped_key?.B || item.deleted?.BOOL === true) {
+ continue
+ }
+ const teamId = Number(item.team_id?.N)
+ const organizationId = item.organization_id?.S
+ if (!Number.isSafeInteger(teamId) || !organizationId) {
+ throw new Error('Invalid ML key record')
+ }
+ const sessionId = item.sk.S?.startsWith('session:') ? item.sk.S.slice('session:'.length) : undefined
+ identities.set(id, {
+ teamId,
+ organizationId,
+ ...(sessionId ? { sessionId } : { sessionMonth: item.session_month?.S }),
+ })
+ }
+ const state = await this.db.read(
+ [...identities.values()].flatMap((identity) => [
+ monthBlockId(keySessionMonth(identity)),
+ teamBlockId(identity.teamId),
+ ])
+ )
+ const result = new Map<string, MlDataKey>()
+ await Promise.all(
+ [...identities].map(async ([id, identity]) => {
+ if (
+ state.has(tableKeyString(monthBlockId(keySessionMonth(identity)))) ||
+ state.has(tableKeyString(teamBlockId(identity.teamId)))
+ ) {
+ return
+ }
+ result.set(id, {
+ ...(await this.encryption.decrypt(identity, Buffer.from(stored.get(id)!.wrapped_key.B!))),
+ decryptUntil,
+ })
+ })
+ )
+ return result
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/runtime.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/runtime.ts
new file mode 100644
index 000000000000..570628fa8525
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/runtime.ts
@@ -0,0 +1,62 @@
+import { DynamoDBClient } from '@aws-sdk/client-dynamodb'
+import { KMSClient } from '@aws-sdk/client-kms'
+
+import { MlPrivacyBatchController } from './batch-controller'
+import { MlKeyEncryption } from './crypto'
+import { MlPrivacyDynamoDB } from './dynamodb'
+import { MlSessionKeyStore } from './key-store'
+import { MlKeyReader } from './reader'
+import { MlKafkaEncryption } from './transport'
+
+export interface MlPrivacyConfig {
+ AI_RESEARCH_REPLAY_PRIVACY_TABLE: string
+ AI_RESEARCH_REPLAY_KMS_KEY_ARN: string
+ AI_RESEARCH_REPLAY_AWS_REGION: string
+ AI_RESEARCH_REPLAY_KEY_CACHE_MAX: number
+ AI_RESEARCH_REPLAY_KEY_CACHE_LIFETIME_MS: number
+ AI_RESEARCH_REPLAY_KMS_REQUESTS_PER_SECOND: number
+ SESSION_RECORDING_DYNAMODB_ENDPOINT?: string
+}
+
+export class MlPrivacyRuntime {
+ public readonly encryption: MlKeyEncryption
+ public readonly reader: MlKeyReader
+ public readonly controller: MlPrivacyBatchController
+ public readonly kafka: MlKafkaEncryption
+ private readonly dynamo: DynamoDBClient
+ private readonly kms: KMSClient
+
+ constructor(config: MlPrivacyConfig) {
+ if (!config.AI_RESEARCH_REPLAY_PRIVACY_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({
+ region: config.AI_RESEARCH_REPLAY_AWS_REGION,
+ endpoint: config.SESSION_RECORDING_DYNAMODB_ENDPOINT || undefined,
+ 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)
+ this.encryption = new MlKeyEncryption(
+ this.kms,
+ config.AI_RESEARCH_REPLAY_KMS_KEY_ARN,
+ config.AI_RESEARCH_REPLAY_KEY_CACHE_MAX,
+ config.AI_RESEARCH_REPLAY_KEY_CACHE_LIFETIME_MS,
+ 8,
+ config.AI_RESEARCH_REPLAY_KMS_REQUESTS_PER_SECOND
+ )
+ this.reader = new MlKeyReader(db, this.encryption)
+ this.controller = new MlPrivacyBatchController(new MlSessionKeyStore(db, this.encryption), this.encryption)
+ this.kafka = new MlKafkaEncryption(this.reader)
+ }
+
+ public start(): Promise<void> {
+ return this.encryption.start()
+ }
+
+ public stop(): void {
+ this.encryption.clear()
+ this.dynamo.destroy()
+ this.kms.destroy()
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/schema.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/schema.ts
new file mode 100644
index 000000000000..a51d2459816f
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/schema.ts
@@ -0,0 +1,77 @@
+import { createHash } from 'node:crypto'
+
+import { sessionStartMonth } from '~/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format'
+
+export const ML_KEY_SHARDS = 32
+export const INGESTION_VERSION_HEADER = 'ai_research_ingestion_version'
+
+export interface MlSessionIdentity {
+ teamId: number
+ organizationId: string
+ sessionId: string
+}
+
+export interface MlKeyIdentity {
+ teamId: number
+ organizationId: string
+ sessionId?: string
+ sessionMonth?: string
+}
+
+export interface TableKey {
+ pk: string
+ sk: string
+}
+
+export function identityDigest(value: string): string {
+ return createHash('sha256').update(value).digest('hex')
+}
+
+export function sessionShard(sessionId: string): number {
+ return Number.parseInt(identityDigest(sessionId).slice(0, 8), 16) % ML_KEY_SHARDS
+}
+
+export function sessionKeyId(teamId: number, sessionId: string): TableKey {
+ return { pk: `team:${teamId}:shard:${sessionShard(sessionId)}`, sk: `session:${sessionId}` }
+}
+
+export function imageKeyId(teamId: number, sessionMonth: string): TableKey {
+ return { pk: `team:${teamId}`, sk: `image:${sessionMonth}` }
+}
+
+export function keySessionMonth(identity: MlKeyIdentity): string {
+ if (identity.sessionId) {
+ return sessionStartMonth(identity.sessionId)
+ }
+ if (!identity.sessionMonth || !/^[0-9]{4}-(0[1-9]|1[0-2])$/.test(identity.sessionMonth)) {
+ throw new Error('ML image key requires a session month')
+ }
+ return identity.sessionMonth
+}
+
+export function monthBlockId(month: string): TableKey {
+ return { pk: `month:${month}`, sk: 'deleted' }
+}
+
+export function monthKeyIndexId(identity: MlKeyIdentity, key: TableKey): TableKey {
+ const id = tableKeyString(key)
+ return { pk: `month:${keySessionMonth(identity)}:shard:${sessionShard(id)}`, sk: `key:${id}` }
+}
+
+export function teamBlockId(teamId: number): TableKey {
+ return { pk: `team:${teamId}`, sk: 'deleted' }
+}
+
+export function tableKeyString(key: TableKey): string {
+ return JSON.stringify([key.pk, key.sk])
+}
+
+export function wrappingContext(identity: MlKeyIdentity): Record<string, string> {
+ return {
+ purpose: identity.sessionId ? 'ai-research-session' : 'ai-research-image',
+ team_id: String(identity.teamId),
+ organization_id: identity.organizationId,
+ ...(identity.sessionId ? { session_id: identity.sessionId } : {}),
+ ...(identity.sessionMonth ? { session_month: identity.sessionMonth } : {}),
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/test-vectors.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/test-vectors.ts
new file mode 100644
index 000000000000..f5706e39787a
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/test-vectors.ts
@@ -0,0 +1,4 @@
+import { MlEncryptedEnvelope } from './crypto'
+import vector from './encryption-vector.json'
+
+export const TrainingEncryptionVector = { ...vector, envelope: vector.envelope as MlEncryptedEnvelope }
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/transport.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/transport.ts
new file mode 100644
index 000000000000..106eec810174
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/transport.ts
@@ -0,0 +1,132 @@
+import { Message } from 'node-rdkafka'
+
+import { parseKafkaHeaders } from '~/common/kafka/consumer/consumer-v1'
+import { parseJSON } from '~/common/utils/json-parse'
+import { parseImageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'
+import { sessionStartMonth } from '~/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format'
+
+import { MlDataKey, MlEncryptedEnvelope, MlKeyReadExpiredError, decryptEnvelope, encryptEnvelope } from './crypto'
+import { MlKeyReader } from './reader'
+import { INGESTION_VERSION_HEADER, sessionKeyId, tableKeyString } from './schema'
+
+export interface MlDecodedMessage {
+ message: Message
+ original: Message
+ key?: MlDataKey
+ invalid?: true
+}
+
+export function ingestionVersion(message: Pick<Message, 'headers'>): 1 | 2 {
+ const version = parseKafkaHeaders(message.headers)[INGESTION_VERSION_HEADER]
+ if (version === undefined || version === '1') {
+ return 1
+ }
+ if (version === '2') {
+ return 2
+ }
+ throw new Error('Unsupported ML ingestion version')
+}
+
+export function encryptedKafkaValue(
+ key: MlDataKey | undefined,
+ kind: string,
+ value: Buffer,
+ ref?: string
+): { value: Buffer; headers: Record<string, string> } {
+ return key
+ ? {
+ value: encryptEnvelope(key, kind, value, ref),
+ headers: {
+ [INGESTION_VERSION_HEADER]: '2',
+ },
+ }
+ : { value, headers: { [INGESTION_VERSION_HEADER]: '1' } }
+}
+
+export function validateImageOwner(ref: string, key: MlDataKey | undefined): void {
+ const parsed = parseImageRef(ref)
+ if (key) {
+ if (
+ !parsed ||
+ parsed.version !== 2 ||
+ parsed.teamId !== String(key.identity.teamId) ||
+ parsed.sessionMonth !== sessionStartMonth(key.identity.sessionId ?? '')
+ ) {
+ throw new Error('ML image reference ownership mismatch')
+ }
+ } else if (parsed?.version === 2) {
+ throw new Error('An ML v2 image requires an encrypted message')
+ }
+}
+
+export class MlKafkaEncryption {
+ constructor(private readonly reader: MlKeyReader) {}
+
+ public async read(messages: Message[], kind: string, bindKafkaKey = false): Promise<MlDecodedMessage[]> {
+ const envelopes = new Map<Message, MlEncryptedEnvelope>()
+ const invalid = new Set<Message>()
+ for (const message of messages) {
+ try {
+ if (ingestionVersion(message) === 1) {
+ continue
+ }
+ if (!message.value) {
+ throw new Error('Missing ML encrypted payload')
+ }
+ const envelope = parseJSON(message.value.toString()) as MlEncryptedEnvelope
+ const context = envelope?.context
+ if (
+ envelope.v !== 2 ||
+ !context ||
+ !Number.isSafeInteger(context.teamId) ||
+ context.teamId <= 0 ||
+ typeof context.organizationId !== 'string' ||
+ typeof context.sessionId !== 'string' ||
+ context.kind !== kind
+ ) {
+ throw new Error('Invalid ML encrypted payload context')
+ }
+ sessionStartMonth(context.sessionId)
+ envelopes.set(message, envelope)
+ } catch {
+ invalid.add(message)
+ }
+ }
+ const keys = await this.reader.read(
+ [...envelopes.values()].map(({ context }) => sessionKeyId(context.teamId, context.sessionId!))
+ )
+ const result: MlDecodedMessage[] = []
+ for (const original of messages) {
+ if (invalid.has(original)) {
+ result.push({ original, message: original, invalid: true })
+ continue
+ }
+ try {
+ const envelope = envelopes.get(original)
+ if (!envelope) {
+ if (bindKafkaKey) {
+ validateImageOwner(original.key?.toString() ?? '', undefined)
+ }
+ result.push({ message: original, original })
+ continue
+ }
+ const key = keys.get(tableKeyString(sessionKeyId(envelope.context.teamId, envelope.context.sessionId!)))
+ if (!key) {
+ continue
+ }
+ const ref = bindKafkaKey ? original.key?.toString() : undefined
+ if (bindKafkaKey) {
+ validateImageOwner(ref ?? '', key)
+ }
+ const value = decryptEnvelope(key, envelope, kind, ref)
+ result.push({ original, message: { ...original, value, size: value.length }, key })
+ } catch (error) {
+ if (error instanceof MlKeyReadExpiredError) {
+ throw error
+ }
+ result.push({ original, message: original, invalid: true })
+ }
+ }
+ return result
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key.test.ts
index c6fa93fc2c78..dea7a28d607e 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key.test.ts
@@ -1,10 +1,11 @@
+import { getMlMirrorConfig } from './config'
import { PseudonymKeyConfig, pseudonymKeyFingerprint, resolvePseudonymKey } from './pseudonym-key'
const baseConfig = (over: Partial<PseudonymKeyConfig> = {}): PseudonymKeyConfig => ({
- SESSION_RECORDING_ML_PSEUDONYM_SECRET: '',
+ AI_RESEARCH_REPLAY_PSEUDONYM_SECRET: '',
SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY: '',
- SESSION_RECORDING_ML_PSEUDONYM_KMS_REGION: '',
- SESSION_RECORDING_ML_PSEUDONYM_KEY_FINGERPRINT: '',
+ AI_RESEARCH_REPLAY_PSEUDONYM_KMS_REGION: '',
+ AI_RESEARCH_REPLAY_PSEUDONYM_KEY_FINGERPRINT: '',
...over,
})
@@ -24,7 +25,7 @@ describe('ml-mirror pseudonym key', () => {
it('uses the plaintext env secret when no ciphertext is set (local dev)', async () => {
const key = await resolvePseudonymKey(
- baseConfig({ SESSION_RECORDING_ML_PSEUDONYM_SECRET: 'dev' }),
+ baseConfig({ AI_RESEARCH_REPLAY_PSEUDONYM_SECRET: 'dev' }),
failDecrypt
)
expect(key).toBe('dev')
@@ -33,8 +34,8 @@ describe('ml-mirror pseudonym key', () => {
it('prefers the KMS-decrypted key over the plaintext secret', async () => {
const decrypt = jest.fn().mockResolvedValue(Buffer.from('kms-key-bytes'))
const key = await resolvePseudonymKey(
- baseConfig({
- SESSION_RECORDING_ML_PSEUDONYM_SECRET: 'dev',
+ getMlMirrorConfig({
+ AI_RESEARCH_REPLAY_PSEUDONYM_SECRET: 'dev',
SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY: 'Y2lwaGVy',
}),
decrypt
@@ -45,7 +46,7 @@ describe('ml-mirror pseudonym key', () => {
it('fails closed when neither a ciphertext nor a plaintext secret is set', async () => {
await expect(resolvePseudonymKey(baseConfig(), failDecrypt)).rejects.toThrow(
- 'SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY or SESSION_RECORDING_ML_PSEUDONYM_SECRET'
+ 'SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY or AI_RESEARCH_REPLAY_PSEUDONYM_SECRET'
)
})
@@ -53,8 +54,8 @@ describe('ml-mirror pseudonym key', () => {
const fingerprint = pseudonymKeyFingerprint('dev')
const key = await resolvePseudonymKey(
baseConfig({
- SESSION_RECORDING_ML_PSEUDONYM_SECRET: 'dev',
- SESSION_RECORDING_ML_PSEUDONYM_KEY_FINGERPRINT: fingerprint,
+ AI_RESEARCH_REPLAY_PSEUDONYM_SECRET: 'dev',
+ AI_RESEARCH_REPLAY_PSEUDONYM_KEY_FINGERPRINT: fingerprint,
}),
failDecrypt
)
@@ -65,8 +66,8 @@ describe('ml-mirror pseudonym key', () => {
await expect(
resolvePseudonymKey(
baseConfig({
- SESSION_RECORDING_ML_PSEUDONYM_SECRET: 'rotated-key',
- SESSION_RECORDING_ML_PSEUDONYM_KEY_FINGERPRINT: pseudonymKeyFingerprint('original-key'),
+ AI_RESEARCH_REPLAY_PSEUDONYM_SECRET: 'rotated-key',
+ AI_RESEARCH_REPLAY_PSEUDONYM_KEY_FINGERPRINT: pseudonymKeyFingerprint('original-key'),
}),
failDecrypt
)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key.ts
index 3c22b1b146be..1667fae9450f 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key.ts
@@ -1,14 +1,14 @@
-/** Resolves the pseudonymization key (KMS-wrapped in prod, plaintext env for local dev) and pins it against rotation. */
+/** Resolves the root key for legacy identifiers and image hashes (KMS-wrapped in prod, plaintext env for local dev) and pins it against rotation. */
import { DecryptCommand, KMSClient } from '@aws-sdk/client-kms'
import { createHmac } from 'crypto'
import { logger } from '~/common/utils/logger'
export interface PseudonymKeyConfig {
- SESSION_RECORDING_ML_PSEUDONYM_SECRET: string
+ AI_RESEARCH_REPLAY_PSEUDONYM_SECRET: string
SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY: string
- SESSION_RECORDING_ML_PSEUDONYM_KMS_REGION: string
- SESSION_RECORDING_ML_PSEUDONYM_KEY_FINGERPRINT: string
+ AI_RESEARCH_REPLAY_PSEUDONYM_KMS_REGION: string
+ AI_RESEARCH_REPLAY_PSEUDONYM_KEY_FINGERPRINT: string
}
/** Decrypts a base64 KMS-wrapped key; injectable so tests don't hit KMS. */
@@ -25,7 +25,7 @@ const kmsDecrypt: KeyDecryptor = async (ciphertextBase64, region) => {
/**
* Non-reversible, domain-separated fingerprint of the key. Safe to log/store: it identifies the key without
- * revealing it, so the dataset's identity space can be pinned to one key.
+ * revealing it, so legacy identifiers and image references can stay stable.
*/
export function pseudonymKeyFingerprint(secret: string | Buffer): string {
return createHmac('sha256', secret).update('pseudonym-key-fingerprint:v1').digest('hex').slice(0, 16)
@@ -34,7 +34,7 @@ export function pseudonymKeyFingerprint(secret: string | Buffer): string {
/**
* Resolves the HMAC key: prefers the KMS-wrapped ciphertext (decrypted once, never persisted), else the plaintext
* env secret (local dev). Fails closed when no key is configured, or when a pinned fingerprint doesn't match the
- * resolved key — a changed key would re-map every id and contaminate train/eval splits, so we refuse to start.
+ * resolved key because a changed key would break legacy identifiers, image references, and crawl-history cache joins.
*/
export async function resolvePseudonymKey(
config: PseudonymKeyConfig,
@@ -45,24 +45,24 @@ export async function resolvePseudonymKey(
if (config.SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY) {
secret = await decrypt(
config.SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY,
- config.SESSION_RECORDING_ML_PSEUDONYM_KMS_REGION
+ config.AI_RESEARCH_REPLAY_PSEUDONYM_KMS_REGION
)
source = 'kms'
- } else if (config.SESSION_RECORDING_ML_PSEUDONYM_SECRET) {
- secret = config.SESSION_RECORDING_ML_PSEUDONYM_SECRET
+ } else if (config.AI_RESEARCH_REPLAY_PSEUDONYM_SECRET) {
+ secret = config.AI_RESEARCH_REPLAY_PSEUDONYM_SECRET
source = 'env'
} else {
throw new Error(
- 'SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY or SESSION_RECORDING_ML_PSEUDONYM_SECRET must be set for the ML mirror'
+ 'SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY or AI_RESEARCH_REPLAY_PSEUDONYM_SECRET must be set for the ML mirror'
)
}
const fingerprint = pseudonymKeyFingerprint(secret)
- const expected = config.SESSION_RECORDING_ML_PSEUDONYM_KEY_FINGERPRINT
+ const expected = config.AI_RESEARCH_REPLAY_PSEUDONYM_KEY_FINGERPRINT
if (expected && expected !== fingerprint) {
throw new Error(
`pseudonym key fingerprint mismatch (resolved ${fingerprint}, expected ${expected}) — refusing to start: ` +
- 'a rotated/incorrect key would re-map ids and contaminate train/eval splits'
+ 'a rotated/incorrect key would break legacy identifiers, image references, and crawl-history cache joins'
)
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts
index e5deb69a0cdc..7a43507d4e80 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts
@@ -19,4 +19,3 @@ export const PSEUDONYM_IMAGE_CONTENT_KEY = 'image-content-key'
export const PSEUDONYM_IMAGE_URL_KEY = 'image-url-key'
export const PSEUDONYM_IMAGE_URL_GLOBAL_VALUE = 'global-v1'
export const PSEUDONYM_SESSION = 'session'
-export const PSEUDONYM_DISTINCT_ID = 'distinct_id'
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.ts
index cb883224f7fc..17548292c980 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.ts
@@ -1,5 +1,6 @@
import { ParquetSchema } from '@dsnp/parquetjs'
+import { parseJSON } from '~/common/utils/json-parse'
import {
ReplayIndexEntry,
ReplayIndexEntrySchema,
@@ -8,6 +9,8 @@ import { parquetRecordsToBuffer } from '~/ingestion/pipelines/sessionreplay/shar
import { MlBlockMetadataRow } from './block-metadata-row'
import { MlParquetSinkMetrics } from './metrics'
+import { MlDataKey, MlEncryptedEnvelope, encryptEnvelope } from './privacy/crypto'
+import { sessionStartTimestampFromUuidV7 } from './session-identifier-format'
const DAY_MS = 86_400_000
const schema = new ParquetSchema({
@@ -109,3 +112,28 @@ export function replayIndexPartitions(rows: MlBlockMetadataRow[]): Map<string, R
export function replayIndexToParquetBuffer(records: Record<string, unknown>[]): Promise<Buffer> {
return parquetRecordsToBuffer(schema, records)
}
+
+export interface EncryptedReplayIndex {
+ kind: ReplayIndexEntry['kind']
+ rowCount: number
+ envelope: MlEncryptedEnvelope
+}
+
+export function encryptReplayIndex(row: MlBlockMetadataRow, key: MlDataKey): EncryptedReplayIndex[] {
+ if (row.team_id !== String(key.identity.teamId) || row.session_id !== key.identity.sessionId) {
+ return []
+ }
+ const partitions = replayIndexPartitions([
+ { ...row, session_start_ts_ms: sessionStartTimestampFromUuidV7(row.session_id) ?? undefined },
+ ])
+ return [...partitions.values()].map((records) => {
+ const kind = records[0].kind as ReplayIndexEntry['kind']
+ return {
+ kind,
+ rowCount: records.length,
+ envelope: parseJSON(
+ encryptEnvelope(key, 'replay-index', Buffer.from(JSON.stringify(records)), kind).toString()
+ ) as MlEncryptedEnvelope,
+ }
+ })
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-format-file-storage.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-format-file-storage.test.ts
new file mode 100644
index 000000000000..a045b351a275
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-format-file-storage.test.ts
@@ -0,0 +1,111 @@
+import {
+ SessionBatchFileStorage,
+ WriteSessionData,
+} from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-file-storage'
+
+import { SessionFormatFileStorage } from './session-format-file-storage'
+import cases from './session-identifier-format-cases.json'
+
+function storage(prefix: string): SessionBatchFileStorage & { buffers: Buffer[]; finish: jest.Mock } {
+ const buffers: Buffer[] = []
+ const finish = jest.fn().mockResolvedValue(undefined)
+ return {
+ buffers,
+ finish,
+ checkHealth: () => Promise.resolve(true),
+ newBatch: () => ({
+ writeSession: (data: WriteSessionData) => {
+ const start = Buffer.concat(buffers).length
+ buffers.push(data.buffer)
+ return Promise.resolve({
+ bytesWritten: data.buffer.length,
+ url: `${prefix}?range=bytes=${start}-${start + data.buffer.length - 1}`,
+ retentionPeriodDays: null,
+ })
+ },
+ finish,
+ }),
+ }
+}
+
+describe('SessionFormatFileStorage', () => {
+ it('routes sessions to separate objects and byte ranges in mixed batches', async () => {
+ const legacy = storage('rrweb/object')
+ const raw = storage('rrweb_2/object')
+ const mixed = new SessionFormatFileStorage(legacy, () => raw)
+ for (let batch = 0; batch < 2; batch++) {
+ const writer = mixed.newBatch()
+ for (const entry of cases.cases) {
+ const destination = entry.rawIdentifiers ? raw : legacy
+ const prefix = entry.rawIdentifiers ? 'rrweb_2/object' : 'rrweb/object'
+ const start = Buffer.concat(destination.buffers).length
+ const result = await writer.writeSession({
+ buffer: Buffer.from('abc'),
+ sessionId: entry.sessionId,
+ teamId: 7,
+ retentionPeriod: '30d',
+ })
+ expect(result.url).toBe(`${prefix}?range=bytes=${start}-${start + 2}`)
+ }
+ await writer.finish()
+ }
+ expect(legacy.finish).toHaveBeenCalledTimes(2)
+ expect(raw.finish).toHaveBeenCalledTimes(2)
+ expect(raw.buffers).toHaveLength(cases.cases.filter((entry) => entry.rawIdentifiers).length * 2)
+ expect(legacy.buffers).toHaveLength(cases.cases.filter((entry) => !entry.rawIdentifiers).length * 2)
+ })
+
+ it('keeps late sessions in their start month across mixed batches', async () => {
+ const legacy = storage('rrweb/object')
+ const september = storage('rrweb_2/2026-09/object')
+ const october = storage('rrweb_2/2026-10/object')
+ const writer = new SessionFormatFileStorage(legacy, (month) =>
+ month === '2026-09' ? september : october
+ ).newBatch()
+ for (const [date, prefix] of [
+ ['2026-09-30T23:59:59.999Z', '2026-09'],
+ ['2026-10-01T00:00:00Z', '2026-10'],
+ ['2026-09-30T23:59:59.999Z', '2026-09'],
+ ]) {
+ const hex = Date.parse(date).toString(16).padStart(12, '0')
+ const result = await writer.writeSession({
+ buffer: Buffer.from('abc'),
+ teamId: 7,
+ sessionId: `${hex.slice(0, 8)}-${hex.slice(8)}-7000-8000-000000000007`,
+ retentionPeriod: '30d',
+ })
+ expect(result.url).toContain(`rrweb_2/${prefix}/`)
+ }
+ await writer.finish()
+ expect(september.buffers).toHaveLength(2)
+ expect(october.buffers).toHaveLength(1)
+ })
+
+ it('waits for both uploads before reporting a failure', async () => {
+ const legacy = storage('rrweb/object')
+ const raw = storage('rrweb_2/object')
+ legacy.finish.mockRejectedValue(new Error('upload failed'))
+ let completeRaw!: () => void
+ raw.finish.mockReturnValue(
+ new Promise<void>((resolve) => {
+ completeRaw = resolve
+ })
+ )
+ const writer = new SessionFormatFileStorage(legacy, () => raw).newBatch()
+ for (const entry of cases.cases.slice(0, 2)) {
+ await writer.writeSession({
+ buffer: Buffer.from('abc'),
+ sessionId: entry.sessionId,
+ teamId: 7,
+ retentionPeriod: '30d',
+ })
+ }
+ const settled = jest.fn()
+ const done = writer.finish().catch(settled)
+ await Promise.resolve()
+ expect(settled).not.toHaveBeenCalled()
+ completeRaw()
+ await done
+ expect(settled).toHaveBeenCalledWith(new Error('upload failed'))
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-format-file-storage.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-format-file-storage.ts
new file mode 100644
index 000000000000..de92599fa7ce
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-format-file-storage.ts
@@ -0,0 +1,53 @@
+import {
+ SessionBatchFileStorage,
+ SessionBatchFileWriter,
+ WriteSessionData,
+ WriteSessionResult,
+} from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-file-storage'
+
+import { sessionStartMonth, usesRawSessionIdentifiers } from './session-identifier-format'
+
+class SessionFormatFileWriter implements SessionBatchFileWriter {
+ private readonly writers = new Map<string, SessionBatchFileWriter>()
+
+ constructor(
+ private readonly legacyStorage: SessionBatchFileStorage,
+ private readonly rawStorage: (month?: string) => SessionBatchFileStorage
+ ) {}
+
+ public writeSession(data: WriteSessionData): Promise<WriteSessionResult> {
+ const rawIdentifiers = usesRawSessionIdentifiers(data.sessionId)
+ const partition = rawIdentifiers ? sessionStartMonth(data.sessionId) : 'legacy'
+ let writer = this.writers.get(partition)
+ if (!writer) {
+ writer = (rawIdentifiers ? this.rawStorage(partition) : this.legacyStorage).newBatch()
+ this.writers.set(partition, writer)
+ }
+ return writer.writeSession(data)
+ }
+
+ public async finish(): Promise<void> {
+ const results = await Promise.allSettled([...this.writers.values()].map((writer) => writer.finish()))
+ for (const result of results) {
+ if (result.status === 'rejected') {
+ throw result.reason
+ }
+ }
+ }
+}
+
+export class SessionFormatFileStorage implements SessionBatchFileStorage {
+ constructor(
+ private readonly legacyStorage: SessionBatchFileStorage,
+ private readonly rawStorage: (month?: string) => SessionBatchFileStorage
+ ) {}
+
+ public newBatch(): SessionBatchFileWriter {
+ return new SessionFormatFileWriter(this.legacyStorage, this.rawStorage)
+ }
+
+ public async checkHealth(): Promise<boolean> {
+ const health = await Promise.all([this.legacyStorage.checkHealth(), this.rawStorage().checkHealth()])
+ return health.every(Boolean)
+ }
+}
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
new file mode 100644
index 000000000000..a87cd6f66ba6
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format-cases.json
@@ -0,0 +1,65 @@
+{
+ "cutoffMs": 1789466400000,
+ "cases": [
+ {
+ "sessionId": "01a0a482-54ff-7000-8000-000000000001",
+ "rawIdentifiers": false,
+ "storedSessionId": "fb55e8182cd5ac4247c1894289cea4d1",
+ "storedTeamId": "a725cc999d0421ba516777bc3c460c8d"
+ },
+ {
+ "sessionId": "01a0a482-5500-7000-8000-000000000001",
+ "rawIdentifiers": true,
+ "storedSessionId": "01a0a482-5500-7000-8000-000000000001",
+ "storedTeamId": "7"
+ },
+ {
+ "sessionId": "01a0a482-5501-7000-8000-000000000001",
+ "rawIdentifiers": true,
+ "storedSessionId": "01a0a482-5501-7000-8000-000000000001",
+ "storedTeamId": "7"
+ },
+ {
+ "sessionId": "01A0A482-5500-7000-8000-000000000001",
+ "rawIdentifiers": true,
+ "storedSessionId": "01A0A482-5500-7000-8000-000000000001",
+ "storedTeamId": "7"
+ },
+ {
+ "sessionId": "legacy-session",
+ "rawIdentifiers": false,
+ "storedSessionId": "0fb0a749493d697fa8ec9a23e2295d12",
+ "storedTeamId": "a725cc999d0421ba516777bc3c460c8d"
+ },
+ {
+ "sessionId": "01a0a482-5500-4000-8000-000000000001",
+ "rawIdentifiers": false,
+ "storedSessionId": "047dc889f71de4a7dc45e5cf462dbaaf",
+ "storedTeamId": "a725cc999d0421ba516777bc3c460c8d"
+ },
+ {
+ "sessionId": "01a0a482-5500-7000-0000-000000000001",
+ "rawIdentifiers": false,
+ "storedSessionId": "730f80c89283a28469d60e44047ed476",
+ "storedTeamId": "a725cc999d0421ba516777bc3c460c8d"
+ },
+ {
+ "sessionId": "00000000-0000-7000-8000-000000000001",
+ "rawIdentifiers": false,
+ "storedSessionId": "7a7990c03b4abd6f26136d0ffb45cab9",
+ "storedTeamId": "a725cc999d0421ba516777bc3c460c8d"
+ },
+ {
+ "sessionId": "ffffffff-ffff-7000-8000-000000000007",
+ "rawIdentifiers": false,
+ "storedSessionId": "4f55f5e61c2120dca9aa8d3be6dead49",
+ "storedTeamId": "a725cc999d0421ba516777bc3c460c8d"
+ },
+ {
+ "sessionId": "e677d21f-dc00-7000-8000-000000000007",
+ "rawIdentifiers": false,
+ "storedSessionId": "bd06d56b33907c2971f5fdf25a5e396d",
+ "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
new file mode 100644
index 000000000000..0015b0e97906
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format.ts
@@ -0,0 +1,26 @@
+export const RAW_SESSION_IDENTIFIERS_START_MS = Date.parse('2026-09-15T10: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)) {
+ return null
+ }
+ const timestamp = Number.parseInt(sessionId.slice(0, 8) + sessionId.slice(9, 13), 16)
+ return timestamp > 0 ? timestamp : null
+}
+
+export function usesRawSessionIdentifiers(sessionId: string): boolean {
+ const startedAt = sessionStartTimestampFromUuidV7(sessionId)
+ return startedAt !== null && startedAt >= RAW_SESSION_IDENTIFIERS_START_MS && startedAt < Date.UTC(10000, 0, 1)
+}
+
+export function sessionStartMonth(sessionId: string): string {
+ const timestamp = sessionStartTimestampFromUuidV7(sessionId)
+ if (timestamp === null) {
+ throw new Error('ML monthly partitions require a UUIDv7 session ID')
+ }
+ const month = new Date(timestamp).toISOString().slice(0, 7)
+ if (!/^[0-9]{4}-(0[1-9]|1[0-2])$/.test(month)) {
+ throw new Error('ML session month is out of range')
+ }
+ return month
+}
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 efbec11243c0..666a645b8c55 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
@@ -394,7 +394,7 @@ describeAddon('native image collection', () => {
rustAddon!.initAnonymizer({ text: [], url: [] })
await expect(
rustAddon!.anonymizeKafkaPayload(imagePayload(), undefined, undefined, CONTENT_KEY)
- ).rejects.toThrow('contentKey requires pseudoTeam')
+ ).rejects.toThrow('contentKey requires teamId')
await expect(
rustAddon!.anonymizeKafkaPayload(imagePayload(), undefined, undefined, undefined, CONTENT_KEY)
).resolves.toMatchObject({ failed: false })
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts
index 32f2e64237d1..b2acbd3ba12c 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts
@@ -108,7 +108,7 @@ export function getDefaultKafkaMlImageScrubProducerEnvConfig(): KafkaMlImageScru
// of accumulating in the mirror process.
KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES: '10000',
KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES: '131072',
- KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_MESSAGE_MAX_BYTES: `${20 * 1024 * 1024 + 64 * 1024}`,
+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_MESSAGE_MAX_BYTES: `${40 * 1024 * 1024 + 64 * 1024}`,
// Short local delivery timeout (librdkafka defaults to 300s): the lane is best-effort and
// its ack promises join the mirror's pre-commit side-effect drain, so a scrub-topic
// slowdown must fail deliveries fast (dangling ref = placeholder) rather than stall the
@@ -159,7 +159,7 @@ export function getDefaultKafkaMlImageFetchProducerEnvConfig(): KafkaMlImageFetc
// This holds one maximum image response or roughly 60 maximum frontier records.
KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES: '50000',
KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES: '32768',
- KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_MESSAGE_MAX_BYTES: `${20 * 1024 * 1024 + 64 * 1024}`,
+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_MESSAGE_MAX_BYTES: `${40 * 1024 * 1024 + 64 * 1024}`,
// The same short local timeout as the scrub lane, and for the same reason: these ack
// promises join the mirror's pre-commit side-effect drain, so a slow topic must fail fast
// rather than hold the mirror's offset commits toward max.poll.interval.ms.
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts
index 95c1bc53d7d9..2edc3b8b4c77 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts
@@ -66,6 +66,7 @@ export async function fetchTeamTokensWithRecordings(client: PostgresRouter): Pro
{
capture_console_log_opt_in: boolean
session_recording_retention_period: string
+ organization_id: string
is_ai_training_opted_in: boolean
} & Pick<Team, 'id' | 'api_token'>
>(
@@ -73,6 +74,7 @@ export async function fetchTeamTokensWithRecordings(client: PostgresRouter): Pro
`
SELECT
t.id,
+ t.organization_id,
t.api_token,
t.capture_console_log_opt_in,
t.session_recording_retention_period,
@@ -89,6 +91,7 @@ export async function fetchTeamTokensWithRecordings(client: PostgresRouter): Pro
(acc, row) => {
acc[row.api_token] = {
teamId: row.id,
+ organizationId: row.organization_id,
consoleLogIngestionEnabled: row.capture_console_log_opt_in,
aiTrainingOptedIn: row.is_ai_training_opted_in,
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/types.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/types.ts
index 312149baf425..0a0d400633d1 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/types.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/types.ts
@@ -1,6 +1,7 @@
import { TeamId } from '~/types'
export interface TeamForReplay {
+ organizationId?: string
teamId: TeamId
consoleLogIngestionEnabled: boolean
/** Whether the team's organization opted into using its data for AI training. */
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-retry-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-retry-server.ts
index 3b37841910f8..c7aa1c5c9c2f 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-retry-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-retry-server.ts
@@ -1,6 +1,5 @@
import { LibrdKafkaError } from 'node-rdkafka'
-import { initializePrometheusLabels } from '~/common/api/router'
import {
KAFKA_SESSION_REPLAY_IMAGE_FETCH,
KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1H,
@@ -15,11 +14,8 @@ import { RetryDelayConsumer } from '~/ingestion/pipelines/sessionreplay/ml-mirro
import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'
import { INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER } from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'
-import { CleanupResources, NodeServer, ServerLifecycle } from './base-server'
-import {
- IngestionSessionReplayMlMirrorServerConfig,
- buildMlMirrorServerConfig,
-} from './ingestion-session-replay-ml-mirror-server'
+import { CleanupResources } from './base-server'
+import { MlMirrorConsumerServer } from './ml-mirror-consumer-server'
/**
* Headroom on top of the sleeping a batch can do, for the publishing between the sleeps.
@@ -38,30 +34,10 @@ const DELAY_TOPICS = [
KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1H,
]
-export class IngestionSessionReplayMlImageFetchRetryServer implements NodeServer {
- readonly lifecycle: ServerLifecycle
- private config: IngestionSessionReplayMlMirrorServerConfig
+export class IngestionSessionReplayMlImageFetchRetryServer extends MlMirrorConsumerServer {
private producerRegistry?: KafkaProducerRegistry<SessionReplayProducerName>
- constructor(config: Partial<IngestionSessionReplayMlMirrorServerConfig> = {}) {
- this.config = buildMlMirrorServerConfig(config)
- this.lifecycle = new ServerLifecycle(this.config)
- }
-
- async start(): Promise<void> {
- return this.lifecycle.start(
- () => this.startServices(),
- () => this.getCleanupResources()
- )
- }
-
- async stop(error?: Error): Promise<void> {
- return this.lifecycle.stop(() => this.getCleanupResources(), error)
- }
-
- private async startServices(): Promise<void> {
- initializePrometheusLabels(this.config.INGESTION_PIPELINE, this.config.INGESTION_LANE)
-
+ protected async startServices(): Promise<void> {
const topic = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_TOPIC
const delayMs = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_DELAY_MS
const batchSize = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_BATCH_SIZE
@@ -145,7 +121,7 @@ export class IngestionSessionReplayMlImageFetchRetryServer implements NodeServer
})
}
- private getCleanupResources(): CleanupResources {
+ protected getCleanupResources(): CleanupResources {
return {
kafkaProducers: [],
redisPools: [],
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.test.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.test.ts
index 66874609b8ea..07c8104441c5 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.test.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.test.ts
@@ -11,9 +11,9 @@ import { buildMlMirrorServerConfig } from './ingestion-session-replay-ml-mirror-
describe('image fetch consumer wiring', () => {
it.each([
['the default', {}, 2, 102_400],
- ['four consumers', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 4 }, 4, 102_400],
- ['eight consumers', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 8 }, 8, 204_800],
- ['sixteen consumers', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 16 }, 16, 409_600],
+ ['four consumers', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 4 }, 4, 164_096],
+ ['eight consumers', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 8 }, 8, 328_192],
+ ['sixteen consumers', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 16 }, 16, 656_384],
])('creates %s number of Kafka group members', (_name, overrides, expectedConsumers, expectedQueueBudget) => {
const serverConfig = buildMlMirrorServerConfig(overrides)
const consumerConfigs = buildImageFetchConsumerConfigs(serverConfig)
@@ -32,7 +32,7 @@ describe('image fetch consumer wiring', () => {
expectedQueueBudget - expectedConsumers
)
expect(Number(consumerOverrides['queued.max.messages.kbytes']) * 1024).toBeGreaterThanOrEqual(
- serverConfig.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES + 64 * 1024
+ serverConfig.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES * 2 + 64 * 1024
)
})
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 9de300fbeb6a..17d337a53d6b 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
@@ -1,7 +1,6 @@
import { DynamoDBClient } from '@aws-sdk/client-dynamodb'
import { NodeHttpHandler } from '@smithy/node-http-handler'
-import { initializePrometheusLabels } from '~/common/api/router'
import {
KAFKA_SESSION_REPLAY_IMAGE_FETCH,
KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1H,
@@ -33,17 +32,17 @@ import { OriginRequestScheduler } from '~/ingestion/pipelines/sessionreplay/ml-m
import { assertUrlPolicyLoaded } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key'
import { ImageFetchTopHogMetrics } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/tophog-metrics'
import { UrlFetchConsumer } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer'
+import { VersionedCrawlHistory } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/versioned-crawl-history'
import { createWebBotAuthRequestSigner } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/web-bot-auth'
+import { MlPrivacyRuntime } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/runtime'
import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'
import { createOutputsRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/registry'
import { INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER } from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'
import { HealthCheckResultOk } from '~/types'
-import { CleanupResources, NodeServer, ServerLifecycle } from './base-server'
-import {
- IngestionSessionReplayMlMirrorServerConfig,
- buildMlMirrorServerConfig,
-} from './ingestion-session-replay-ml-mirror-server'
+import { CleanupResources } from './base-server'
+import { IngestionSessionReplayMlMirrorServerConfig } from './ingestion-session-replay-ml-mirror-server'
+import { MlMirrorConsumerServer } from './ml-mirror-consumer-server'
/**
* How long the store may spend on one batch, well inside Kafka's max.poll.interval.ms of 300s.
@@ -173,12 +172,13 @@ export function buildImageFetchConsumerOverrides(
consumerCount: number
): RdKafkaConsumerOverrides {
assertImageFetchBatchTarget(consumerCount)
- const maximumRecordBytes = config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES + 64 * 1024
+ const maximumRecordBytes = config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES * 2 + 64 * 1024
return {
'fetch.message.max.bytes': maximumRecordBytes,
'max.partition.fetch.bytes': maximumRecordBytes,
'queued.max.messages.kbytes': Math.max(
IMAGE_FETCH_MIN_CONSUMER_QUEUE_KBYTES,
+ Math.ceil(maximumRecordBytes / 1024),
Math.floor(IMAGE_FETCH_KAFKA_QUEUE_BUDGET_KBYTES / consumerCount)
),
}
@@ -198,31 +198,13 @@ export async function shutdownImageFetchConsumers(
*
* It scales separately because fetching waits on network IO while scrubbing needs CPU and ML models.
*/
-export class IngestionSessionReplayMlImageFetchServer implements NodeServer {
- readonly lifecycle: ServerLifecycle
- private config: IngestionSessionReplayMlMirrorServerConfig
+export class IngestionSessionReplayMlImageFetchServer extends MlMirrorConsumerServer {
+ private privacy?: MlPrivacyRuntime
private crawlHistoryClient?: DynamoDBClient
private producerRegistry?: KafkaProducerRegistry<SessionReplayProducerName>
private topHog?: TopHog
- constructor(config: Partial<IngestionSessionReplayMlMirrorServerConfig> = {}) {
- this.config = buildMlMirrorServerConfig(config)
- this.lifecycle = new ServerLifecycle(this.config)
- }
-
- async start(): Promise<void> {
- return this.lifecycle.start(
- () => this.startServices(),
- () => this.getCleanupResources()
- )
- }
-
- async stop(error?: Error): Promise<void> {
- return this.lifecycle.stop(() => this.getCleanupResources(), error)
- }
-
- private async startServices(): Promise<void> {
- initializePrometheusLabels(this.config.INGESTION_PIPELINE, this.config.INGESTION_LANE)
+ protected async startServices(): Promise<void> {
// Here rather than on the first record. The parser calls into this addon for every URL, and
// it must answer with a reason rather than raise, so a build that shipped without the addon
// has to stop the pod at startup instead.
@@ -246,13 +228,33 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {
maxAttempts: 5,
requestHandler: new NodeHttpHandler(),
})
- const crawlHistory = new DynamoDBCrawlHistory(
+ const legacyCrawlHistory = new DynamoDBCrawlHistory(
this.crawlHistoryClient,
tableName,
dynamoDBTimeoutMs,
STORE_BATCH_BUDGET_MS
)
- await crawlHistory.validateAccess(Date.now())
+ 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_IMAGE_FETCH_V2_DYNAMODB_TABLE ||
+ this.config.AI_RESEARCH_REPLAY_IMAGE_FETCH_V2_DYNAMODB_TABLE === tableName
+ ) {
+ throw new Error('ML v2 requires a separate image fetch history table')
+ }
+ this.privacy = new MlPrivacyRuntime(this.config)
+ await this.privacy.start()
+ const v2 = new DynamoDBCrawlHistory(
+ this.crawlHistoryClient,
+ this.config.AI_RESEARCH_REPLAY_IMAGE_FETCH_V2_DYNAMODB_TABLE,
+ dynamoDBTimeoutMs,
+ STORE_BATCH_BUDGET_MS
+ )
+ await v2.validateAccess(Date.now())
+ crawlHistory = new VersionedCrawlHistory(legacyCrawlHistory, v2)
+ }
// Built even in dry run, so the wiring is exercised by every start rather than only by the
// one that clears the flag.
@@ -284,7 +286,8 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {
},
buildFetchRunner(this.config, publisher, topHogMetrics),
deadLetters,
- topHogMetrics
+ topHogMetrics,
+ this.privacy?.kafka
)
logger.info('🌐', 'ml_image_fetch_started', { dryRun })
@@ -315,11 +318,12 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {
)
}
- private getCleanupResources(): CleanupResources {
+ protected getCleanupResources(): CleanupResources {
return {
kafkaProducers: [],
redisPools: [],
additionalCleanup: async () => {
+ this.privacy?.stop()
this.crawlHistoryClient?.destroy()
try {
await this.topHog?.stop()
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-dlq-replay-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-dlq-replay-server.ts
index 11e2e41de56d..40391a92c33d 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-dlq-replay-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-dlq-replay-server.ts
@@ -1,17 +1,13 @@
-import { initializePrometheusLabels } from '~/common/api/router'
import { KafkaConsumer } from '~/common/kafka/consumer/consumer-v1'
import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'
+import { logger } from '~/common/utils/logger'
import { SessionReplayProducerName } from '~/ingestion/pipelines/sessionreplay/config'
import { replayBatch } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay'
import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'
import { INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER } from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'
-import { logger } from '../common/utils/logger'
-import { CleanupResources, NodeServer, ServerLifecycle } from './base-server'
-import {
- IngestionSessionReplayMlMirrorServerConfig,
- buildMlMirrorServerConfig,
-} from './ingestion-session-replay-ml-mirror-server'
+import { CleanupResources } from './base-server'
+import { MlMirrorConsumerServer } from './ml-mirror-consumer-server'
/**
* Pushes images the scrub sidecar could not process back onto the topic they came from.
@@ -26,30 +22,10 @@ import {
* same images between the two topics and spend scrub capacity on work already known to fail. The
* lane has no capacity to spare for that.
*/
-export class IngestionSessionReplayMlImageScrubDlqReplayServer implements NodeServer {
- readonly lifecycle: ServerLifecycle
- private config: IngestionSessionReplayMlMirrorServerConfig
+export class IngestionSessionReplayMlImageScrubDlqReplayServer extends MlMirrorConsumerServer {
private producerRegistry?: KafkaProducerRegistry<SessionReplayProducerName>
- constructor(config: Partial<IngestionSessionReplayMlMirrorServerConfig> = {}) {
- this.config = buildMlMirrorServerConfig(config)
- this.lifecycle = new ServerLifecycle(this.config)
- }
-
- async start(): Promise<void> {
- return this.lifecycle.start(
- () => this.startServices(),
- () => this.getCleanupResources()
- )
- }
-
- async stop(error?: Error): Promise<void> {
- return this.lifecycle.stop(() => this.getCleanupResources(), error)
- }
-
- private async startServices(): Promise<void> {
- initializePrometheusLabels(this.config.INGESTION_PIPELINE, this.config.INGESTION_LANE)
-
+ protected async startServices(): Promise<void> {
const dlqTopic = this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_DLQ_TOPIC
if (!dlqTopic) {
throw new Error('SESSION_RECORDING_ML_IMAGE_SCRUB_DLQ_TOPIC must be set to replay from it')
@@ -59,7 +35,7 @@ export class IngestionSessionReplayMlImageScrubDlqReplayServer implements NodeSe
// A separate group from the scrub consumer's, and its own topic, so a replay run cannot
// disturb the offsets of the lane it is feeding.
- const maximumRecordBytes = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES + 64 * 1024
+ const maximumRecordBytes = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES * 2 + 64 * 1024
const consumer = new KafkaConsumer(
{
topic: dlqTopic,
@@ -109,7 +85,7 @@ export class IngestionSessionReplayMlImageScrubDlqReplayServer implements NodeSe
})
}
- private getCleanupResources(): CleanupResources {
+ protected getCleanupResources(): CleanupResources {
return {
kafkaProducers: [],
redisPools: [],
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
new file mode 100644
index 000000000000..9a0ae175fad0
--- /dev/null
+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.test.ts
@@ -0,0 +1,30 @@
+import { IngestionSessionReplayMlImageScrubServer } from './ingestion-session-replay-ml-image-scrub-server'
+
+class TestImageScrubServer extends IngestionSessionReplayMlImageScrubServer {
+ public override startServices(): Promise<void> {
+ return super.startServices()
+ }
+}
+
+describe('image scrub server startup', () => {
+ it.each(['', ' '])(
+ '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_KMS_KEY_ARN: '',
+ SESSION_RECORDING_ML_IMAGE_SCRUB_DLQ_TOPIC: topic,
+ })
+ await expect(server.startServices()).rejects.toThrow('requires SESSION_RECORDING_ML_IMAGE_SCRUB_DLQ_TOPIC')
+ }
+ )
+
+ it('allows a disabled DLQ without privacy and continues to the S3 configuration check', async () => {
+ const server = new TestImageScrubServer({
+ AI_RESEARCH_REPLAY_PRIVACY_TABLE: '',
+ SESSION_RECORDING_ML_IMAGE_SCRUB_DLQ_TOPIC: '',
+ SESSION_RECORDING_V2_S3_BUCKET: '',
+ })
+ await expect(server.startServices()).rejects.toThrow('SESSION_RECORDING_V2_S3_*')
+ })
+})
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 fbdc43f4e9b3..7fb86625381e 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
@@ -1,6 +1,5 @@
import { S3Client } from '@aws-sdk/client-s3'
-import { initializePrometheusLabels } from '~/common/api/router'
import { KAFKA_SESSION_REPLAY_IMAGE_SCRUB } from '~/common/config/kafka-topics'
import { KafkaConsumer, KafkaConsumerConfig } from '~/common/kafka/consumer/consumer-v1'
import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'
@@ -9,15 +8,14 @@ import { KafkaDeadLetterSink } from '~/ingestion/pipelines/sessionreplay/ml-mirr
import { ImageBatcher } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher'
import { ImageShardStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store'
import { ScrubClient } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client'
+import { MlPrivacyRuntime } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/runtime'
import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'
import { INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER } from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'
import { buildSessionRecordingS3Client } from '~/ingestion/pipelines/sessionreplay/shared/s3-client'
-import { CleanupResources, NodeServer, ServerLifecycle } from './base-server'
-import {
- IngestionSessionReplayMlMirrorServerConfig,
- buildMlMirrorServerConfig,
-} from './ingestion-session-replay-ml-mirror-server'
+import { CleanupResources } from './base-server'
+import { IngestionSessionReplayMlMirrorServerConfig } from './ingestion-session-replay-ml-mirror-server'
+import { MlMirrorConsumerServer } from './ml-mirror-consumer-server'
// A scrub + S3-write batch blocks the poll loop (which only heartbeats once per batch) for up to minutes, so
// we refresh the heartbeat this often during it. Must stay under CONSUMER_MAX_HEARTBEAT_INTERVAL_MS (30s).
@@ -48,30 +46,21 @@ export function buildImageScrubConsumerConfig(config: IngestionSessionReplayMlMi
}
}
-export class IngestionSessionReplayMlImageScrubServer implements NodeServer {
- readonly lifecycle: ServerLifecycle
- private config: IngestionSessionReplayMlMirrorServerConfig
+export class IngestionSessionReplayMlImageScrubServer extends MlMirrorConsumerServer {
+ private privacy?: MlPrivacyRuntime
private producerRegistry?: KafkaProducerRegistry<SessionReplayProducerName>
- constructor(config: Partial<IngestionSessionReplayMlMirrorServerConfig> = {}) {
- this.config = buildMlMirrorServerConfig(config)
- this.lifecycle = new ServerLifecycle(this.config)
- }
-
- async start(): Promise<void> {
- return this.lifecycle.start(
- () => this.startServices(),
- () => this.getCleanupResources()
- )
- }
-
- async stop(error?: Error): Promise<void> {
- return this.lifecycle.stop(() => this.getCleanupResources(), error)
- }
-
- private async startServices(): Promise<void> {
- initializePrometheusLabels(this.config.INGESTION_PIPELINE, this.config.INGESTION_LANE)
-
+ protected async startServices(): Promise<void> {
+ if (
+ this.config.AI_RESEARCH_REPLAY_PRIVACY_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) {
+ this.privacy = new MlPrivacyRuntime(this.config)
+ await this.privacy.start()
+ }
const s3Client = requireS3Client(buildSessionRecordingS3Client(this.config))
const store = new ImageShardStore(
s3Client,
@@ -103,7 +92,7 @@ export class IngestionSessionReplayMlImageScrubServer implements NodeServer {
deadLetters !== null
)
- const maximumRecordBytes = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES + 64 * 1024
+ const maximumRecordBytes = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES * 2 + 64 * 1024
const consumer = new KafkaConsumer(buildImageScrubConsumerConfig(this.config), {
'fetch.message.max.bytes': maximumRecordBytes,
'max.partition.fetch.bytes': maximumRecordBytes,
@@ -120,7 +109,8 @@ export class IngestionSessionReplayMlImageScrubServer implements NodeServer {
dedupMaxRefs: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_DEDUP_MAX_REFS,
},
Date.now(),
- deadLetters
+ deadLetters,
+ this.privacy
)
await scrubClient.waitUntilReachable()
await consumer.connect((messages) => {
@@ -144,10 +134,13 @@ export class IngestionSessionReplayMlImageScrubServer implements NodeServer {
})
}
- private getCleanupResources(): CleanupResources {
+ protected getCleanupResources(): CleanupResources {
return {
kafkaProducers: [],
- additionalCleanup: () => this.producerRegistry?.disconnectAll(),
+ additionalCleanup: async () => {
+ this.privacy?.stop()
+ await this.producerRegistry?.disconnectAll()
+ },
redisPools: [],
}
}
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 93a4ca46c94a..6eeefc4aacaa 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
@@ -4,6 +4,24 @@ import { getDefaultSessionRecordingConfig } from '~/ingestion/pipelines/sessionr
import { buildMlMirrorServerConfig } from './ingestion-session-replay-ml-mirror-server'
describe('buildMlMirrorServerConfig', () => {
+ it.each(['S3_PREFIX', 'PSEUDONYM_SECRET', 'PSEUDONYM_KMS_REGION', 'PSEUDONYM_KEY_FINGERPRINT'] as const)(
+ 'applies the legacy %s environment alias when building server configuration',
+ (suffix) => {
+ const legacy = `SESSION_RECORDING_ML_${suffix}`
+ const canonical = `AI_RESEARCH_REPLAY_${suffix}` as const
+ const originalEnv = process.env
+ try {
+ process.env = { ...originalEnv, [legacy]: 'legacy-value' }
+ delete process.env[canonical]
+ expect(buildMlMirrorServerConfig({})[canonical]).toBe('legacy-value')
+ process.env[canonical] = 'canonical-value'
+ expect(buildMlMirrorServerConfig({})[canonical]).toBe('canonical-value')
+ } finally {
+ process.env = originalEnv
+ }
+ }
+ )
+
it('defaults the mirror to its own consumer group, distinct from the primary ingester', () => {
const config = buildMlMirrorServerConfig({})
expect(config.INGESTION_SESSION_REPLAY_CONSUMER_GROUP_ID).toBe('session-replay-ml-mirror')
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 20efe5436d92..8662ff9062bf 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
@@ -2,21 +2,12 @@ import { DynamoDBClient } from '@aws-sdk/client-dynamodb'
import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3'
import { NodeHttpHandler } from '@smithy/node-http-handler'
-import { initializePrometheusLabels } from '~/common/api/router'
-import { defaultConfig, overrideConfigWithEnv } from '~/common/config/config'
import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'
import { PostgresRouter } from '~/common/utils/db/postgres'
import { parseJSON } from '~/common/utils/json-parse'
import { logger } from '~/common/utils/logger'
-import { getDefaultKafkaDownstreamProducerEnvConfig } from '~/ingestion/common/outputs/producers'
-import { getDefaultIngestionConsumerConfig } from '~/ingestion/config'
import { AllowListFetcher, loadAllowLists } from '~/ingestion/pipelines/sessionreplay/anonymize/allow-list-loader'
-import {
- type SessionReplayProducerName,
- getDefaultSessionRecordingApiConfig,
- getDefaultSessionRecordingConfig,
- getDefaultSessionReplayOutputsConfig,
-} from '~/ingestion/pipelines/sessionreplay/config'
+import { type SessionReplayProducerName } from '~/ingestion/pipelines/sessionreplay/config'
import {
SessionRecordingIngester,
SessionRecordingIngesterCollaborators,
@@ -24,8 +15,6 @@ import {
import type { CrawlHistoryStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history'
import { DynamoDBCrawlHistory } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history'
import {
- MlMirrorConfig,
- getDefaultMlMirrorConfig,
resolveMlAnonymizeMaxConcurrency,
resolveMlMirrorRedisConnection,
} from '~/ingestion/pipelines/sessionreplay/ml-mirror/config'
@@ -40,37 +29,14 @@ import { SessionConsoleLogStore } from '~/ingestion/pipelines/sessionreplay/sess
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 { getDefaultKafkaSessionreplayProducerEnvConfig } from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'
import { buildSessionRecordingS3Client } from '~/ingestion/pipelines/sessionreplay/shared/s3-client'
import { RedisPool } from '../types'
-import { CleanupResources, NodeServer, ServerLifecycle } from './base-server'
-import { IngestionSessionReplayServerConfig, buildSessionReplayRedisPools } from './ingestion-session-replay-server'
-
-/** Full config for an ML mirror deployment: the primary replay config plus ML knobs. */
-export type IngestionSessionReplayMlMirrorServerConfig = IngestionSessionReplayServerConfig & MlMirrorConfig
+import { CleanupResources } from './base-server'
+import { buildSessionReplayRedisPools } from './ingestion-session-replay-server'
+import { MlMirrorConsumerServer } from './ml-mirror-consumer-server'
-/** Assembles the ML-mirror config; shared by the mirror ingester and the Parquet-sink deployments. */
-export function buildMlMirrorServerConfig(
- config: Partial<IngestionSessionReplayMlMirrorServerConfig>
-): IngestionSessionReplayMlMirrorServerConfig {
- return {
- ...defaultConfig,
- ...overrideConfigWithEnv(getDefaultIngestionConsumerConfig()),
- ...overrideConfigWithEnv(getDefaultKafkaDownstreamProducerEnvConfig()),
- ...overrideConfigWithEnv(getDefaultKafkaSessionreplayProducerEnvConfig()),
- ...overrideConfigWithEnv({
- ...getDefaultSessionRecordingConfig(),
- // Distinct default group id so the mirror gets its own copy of every recording rather than
- // splitting the snapshot topic's partitions with the primary ingester (still env-overridable).
- INGESTION_SESSION_REPLAY_CONSUMER_GROUP_ID: 'session-replay-ml-mirror',
- }),
- ...overrideConfigWithEnv(getDefaultSessionRecordingApiConfig()),
- ...overrideConfigWithEnv(getDefaultSessionReplayOutputsConfig()),
- ...overrideConfigWithEnv(getDefaultMlMirrorConfig()),
- ...config,
- }
-}
+export { type IngestionSessionReplayMlMirrorServerConfig, buildMlMirrorServerConfig } from './ml-mirror-server-config'
/** Boot-time smoke test so a broken addon crashes startup instead of dropping all traffic later. */
async function assertAnonymizerHealthy(anonymizer: typeof import('@posthog/replay-anonymizer')): Promise<void> {
@@ -89,35 +55,14 @@ async function assertAnonymizerHealthy(anonymizer: typeof import('@posthog/repla
}
}
-export class IngestionSessionReplayMlMirrorServer implements NodeServer {
- readonly lifecycle: ServerLifecycle
- private config: IngestionSessionReplayMlMirrorServerConfig
-
+export class IngestionSessionReplayMlMirrorServer extends MlMirrorConsumerServer {
private postgres?: PostgresRouter
private producerRegistry?: KafkaProducerRegistry<SessionReplayProducerName>
private crawlHistoryClient?: DynamoDBClient
private redisPool?: RedisPool
private restrictionRedisPool?: RedisPool
- constructor(config: Partial<IngestionSessionReplayMlMirrorServerConfig> = {}) {
- this.config = buildMlMirrorServerConfig(config)
- this.lifecycle = new ServerLifecycle(this.config)
- }
-
- async start(): Promise<void> {
- return this.lifecycle.start(
- () => this.startServices(),
- () => this.getCleanupResources()
- )
- }
-
- async stop(error?: Error): Promise<void> {
- return this.lifecycle.stop(() => this.getCleanupResources(), error)
- }
-
- private async startServices(): Promise<void> {
- initializePrometheusLabels(this.config.INGESTION_PIPELINE, this.config.INGESTION_LANE)
-
+ protected async startServices(): Promise<void> {
this.postgres = new PostgresRouter(this.config, this.config.PLUGIN_SERVER_MODE ?? undefined)
this.producerRegistry = await createProducerRegistry(this.config.KAFKA_CLIENT_RACK).build(this.config)
const outputs = createOutputsRegistry().build(this.producerRegistry, this.config)
@@ -251,7 +196,7 @@ export class IngestionSessionReplayMlMirrorServer implements NodeServer {
return new DynamoDBCrawlHistory(this.crawlHistoryClient, tableName, timeoutMs, timeoutMs)
}
- private getCleanupResources(): CleanupResources {
+ protected getCleanupResources(): CleanupResources {
return {
kafkaProducers: [],
redisPools: [this.redisPool, this.restrictionRedisPool].filter(Boolean) as RedisPool[],
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 bb3af39d7144..18044e5dc97e 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
@@ -1,17 +1,15 @@
import { S3Client } from '@aws-sdk/client-s3'
-import { initializePrometheusLabels } from '~/common/api/router'
import { KafkaConsumer, KafkaConsumerConfig } from '~/common/kafka/consumer/consumer-v1'
import { logger } from '~/common/utils/logger'
import { BlockMetadataBatcher } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher'
import { BlockMetadataParquetStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store'
+import { MlPrivacyRuntime } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/runtime'
import { buildSessionRecordingS3Client } from '~/ingestion/pipelines/sessionreplay/shared/s3-client'
-import { CleanupResources, NodeServer, ServerLifecycle } from './base-server'
-import {
- IngestionSessionReplayMlMirrorServerConfig,
- buildMlMirrorServerConfig,
-} from './ingestion-session-replay-ml-mirror-server'
+import { CleanupResources } from './base-server'
+import { IngestionSessionReplayMlMirrorServerConfig } from './ingestion-session-replay-ml-mirror-server'
+import { MlMirrorConsumerServer } from './ml-mirror-consumer-server'
/** The Parquet sink writes unencrypted data, so a misconfigured (absent) S3 client must fail loudly, not silently no-op. */
export function requireS3Client(client: S3Client | null): S3Client {
@@ -36,29 +34,14 @@ export function buildSinkConsumerConfig(config: IngestionSessionReplayMlMirrorSe
}
/** Drains the ML block-metadata topic, rolling rows up into one Parquet object per flush interval in the ML bucket. */
-export class IngestionSessionReplayMlParquetSinkServer implements NodeServer {
- readonly lifecycle: ServerLifecycle
- private config: IngestionSessionReplayMlMirrorServerConfig
-
- constructor(config: Partial<IngestionSessionReplayMlMirrorServerConfig> = {}) {
- this.config = buildMlMirrorServerConfig(config)
- this.lifecycle = new ServerLifecycle(this.config)
- }
-
- async start(): Promise<void> {
- return this.lifecycle.start(
- () => this.startServices(),
- () => this.getCleanupResources()
- )
- }
-
- async stop(error?: Error): Promise<void> {
- return this.lifecycle.stop(() => this.getCleanupResources(), error)
- }
-
- private async startServices(): Promise<void> {
- initializePrometheusLabels(this.config.INGESTION_PIPELINE, this.config.INGESTION_LANE)
+export class IngestionSessionReplayMlParquetSinkServer extends MlMirrorConsumerServer {
+ private privacy?: MlPrivacyRuntime
+ protected async startServices(): Promise<void> {
+ if (this.config.AI_RESEARCH_REPLAY_PRIVACY_TABLE) {
+ this.privacy = new MlPrivacyRuntime(this.config)
+ await this.privacy.start()
+ }
const s3Client = requireS3Client(buildSessionRecordingS3Client(this.config))
const store = new BlockMetadataParquetStore(
s3Client,
@@ -74,7 +57,8 @@ export class IngestionSessionReplayMlParquetSinkServer implements NodeServer {
flushIntervalMs: this.config.SESSION_RECORDING_ML_PARQUET_FLUSH_INTERVAL_MS,
maxRows: this.config.SESSION_RECORDING_ML_PARQUET_MAX_ROWS,
},
- Date.now()
+ Date.now(),
+ this.privacy?.kafka
)
await consumer.connect((messages) => {
consumer.heartbeat()
@@ -97,10 +81,14 @@ export class IngestionSessionReplayMlParquetSinkServer implements NodeServer {
})
}
- private getCleanupResources(): CleanupResources {
+ protected getCleanupResources(): CleanupResources {
return {
kafkaProducers: [],
redisPools: [],
+ additionalCleanup: () => {
+ this.privacy?.stop()
+ return Promise.resolve()
+ },
}
}
}
diff --git a/nodejs/src/servers/ml-mirror-consumer-server.ts b/nodejs/src/servers/ml-mirror-consumer-server.ts
new file mode 100644
index 000000000000..0a2a03d07221
--- /dev/null
+++ b/nodejs/src/servers/ml-mirror-consumer-server.ts
@@ -0,0 +1,31 @@
+import { initializePrometheusLabels } from '~/common/api/router'
+
+import { CleanupResources, NodeServer, ServerLifecycle } from './base-server'
+import { IngestionSessionReplayMlMirrorServerConfig, buildMlMirrorServerConfig } from './ml-mirror-server-config'
+
+export abstract class MlMirrorConsumerServer implements NodeServer {
+ readonly lifecycle: ServerLifecycle
+ protected readonly config: IngestionSessionReplayMlMirrorServerConfig
+
+ constructor(config: Partial<IngestionSessionReplayMlMirrorServerConfig> = {}) {
+ this.config = buildMlMirrorServerConfig(config)
+ this.lifecycle = new ServerLifecycle(this.config)
+ }
+
+ async start(): Promise<void> {
+ return this.lifecycle.start(
+ () => {
+ initializePrometheusLabels(this.config.INGESTION_PIPELINE, this.config.INGESTION_LANE)
+ return this.startServices()
+ },
+ () => this.getCleanupResources()
+ )
+ }
+
+ async stop(error?: Error): Promise<void> {
+ return this.lifecycle.stop(() => this.getCleanupResources(), error)
+ }
+
+ protected abstract startServices(): Promise<void>
+ protected abstract getCleanupResources(): CleanupResources
+}
diff --git a/nodejs/src/servers/ml-mirror-server-config.ts b/nodejs/src/servers/ml-mirror-server-config.ts
new file mode 100644
index 000000000000..dc05ffe55096
--- /dev/null
+++ b/nodejs/src/servers/ml-mirror-server-config.ts
@@ -0,0 +1,37 @@
+import { defaultConfig, overrideConfigWithEnv } from '~/common/config/config'
+import { getDefaultKafkaDownstreamProducerEnvConfig } from '~/ingestion/common/outputs/producers'
+import { getDefaultIngestionConsumerConfig } from '~/ingestion/config'
+import {
+ getDefaultSessionRecordingApiConfig,
+ getDefaultSessionRecordingConfig,
+ getDefaultSessionReplayOutputsConfig,
+} from '~/ingestion/pipelines/sessionreplay/config'
+import { MlMirrorConfig, getMlMirrorConfig } from '~/ingestion/pipelines/sessionreplay/ml-mirror/config'
+import { getDefaultKafkaSessionreplayProducerEnvConfig } from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'
+
+import type { IngestionSessionReplayServerConfig } from './ingestion-session-replay-server'
+
+/** Full config for an ML mirror deployment: the primary replay config plus ML knobs. */
+export type IngestionSessionReplayMlMirrorServerConfig = IngestionSessionReplayServerConfig & MlMirrorConfig
+
+/** Assembles the ML-mirror config; shared by the mirror ingester and the Parquet-sink deployments. */
+export function buildMlMirrorServerConfig(
+ config: Partial<IngestionSessionReplayMlMirrorServerConfig>
+): IngestionSessionReplayMlMirrorServerConfig {
+ return {
+ ...defaultConfig,
+ ...overrideConfigWithEnv(getDefaultIngestionConsumerConfig()),
+ ...overrideConfigWithEnv(getDefaultKafkaDownstreamProducerEnvConfig()),
+ ...overrideConfigWithEnv(getDefaultKafkaSessionreplayProducerEnvConfig()),
+ ...overrideConfigWithEnv({
+ ...getDefaultSessionRecordingConfig(),
+ // Distinct default group id so the mirror gets its own copy of every recording rather than
+ // splitting the snapshot topic's partitions with the primary ingester (still env-overridable).
+ INGESTION_SESSION_REPLAY_CONSUMER_GROUP_ID: 'session-replay-ml-mirror',
+ }),
+ ...overrideConfigWithEnv(getDefaultSessionRecordingApiConfig()),
+ ...overrideConfigWithEnv(getDefaultSessionReplayOutputsConfig()),
+ ...getMlMirrorConfig(),
+ ...config,
+ }
+}
diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.md
index 65b81d293d3d..41a5b145f418 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 **Monday, 2026-09-14 at 11:00 UTC**, which is noon in Europe/London.
+The cutoff is **Tuesday, 2026-09-15 at 10:00 UTC**, which is 11: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 selects v1.
+- An invalid UUIDv7 timestamp or a start year beyond 9999 selects v1.
Event timestamps, arrival times, retries, and flushes do not change the version.
Both versions can occur in one ingestion batch.
@@ -37,7 +37,7 @@ The independent DynamoDB table stores session keys, team image keys, deletion ma
ML outputs omit distinct IDs, including their hashes and pseudonyms.
The metadata consumer projects supported fields before storage, including for messages already in Kafka.
A session has one data key.
-New sessions share one image key per team and session start month.
+A team has one image key per session start month.
KMS wraps each data key with an encryption context that binds its owner and purpose.
Payload encryption uses XSalsa20-Poly1305.
The authenticated payload also binds the dataset kind and, for images, the object or reference being encrypted.
@@ -56,7 +56,6 @@ Reads use strongly consistent `BatchGetItem` requests with bounded retries for u
KMS plaintext caches reduce repeated decrypt calls.
A cache hit does not bypass live key and deletion checks.
-Ingestion also checks current consent.
Each process limits KMS concurrency and request rate; deployment capacity must account for the sum across replicas.
Readers check live state before each batch and permit key use for at most five minutes from the start of that read.
An expired read must obtain permission again.
@@ -117,13 +116,18 @@ Deleting a month does not affect another month's image keys.
## Data layout and readers
-| Dataset | Default path | Encryption key |
-| -------------------- | ------------------------------------------------ | --------------------------------------- |
-| Replay blocks | `rrweb_2/` | Session |
-| Metadata catalog | `block-metadata/v2/dt=<arrival-date>/` | Each row's payload uses its session key |
-| Inline image shards | `scrubbed-images/v2/<YYYY-MM>/<team>/shards/` | Team and session month |
-| Inline image indexes | `scrubbed-images/v2/<YYYY-MM>/<team>/index/` | Team and session month |
-| URL images | `scrubbed-images/v2/<YYYY-MM>/<team>/url/<hash>` | Team and session month |
+All v2 S3 datasets use a `YYYY-MM` directory derived from the session UUIDv7 start timestamp in UTC.
+A session that crosses a month boundary stays in its start month, including late blocks and image fetches.
+
+| Dataset | Default path | Encryption key |
+| -------------------- | ----------------------------------------------------------- | ---------------------------------------- |
+| Replay blocks | `rrweb_2/<month>/` | Session |
+| Metadata catalog | `block-metadata/v2/<month>/` | Each row's payload uses its session key |
+| Evaluation index | `block-metadata-replay-index/v2/<month>/kind=<kind>/` | Each block and kind uses its session key |
+| Inline image shards | `scrubbed-images/v2/<month>/<team>/shards/` | Team and session month |
+| Inline image lookups | `scrubbed-images/v2/<month>/<team>/lookup/<hash>.encrypted` | Team and session month |
+| Inline image indexes | `scrubbed-images/v2/<month>/<team>/index/` | Team and session month |
+| URL images | `scrubbed-images/v2/<month>/<team>/url/<hash>` | Team and session month |
Metadata catalogs expose raw `team_id`, `session_id`, `format_version`, and an encrypted `payload`.
URLs, block locations, and replay indexes are inside that payload.
@@ -132,12 +136,13 @@ V2 does not write a separate plaintext replay index.
Athena can select catalog rows but cannot decrypt replay fields.
Training readers must bulk-read live keys and deletion markers before decrypting.
+If a download exceeds the key read lifetime, readers must check live eligibility again before decryption.
Cross-account readers use the full DynamoDB table ARN and the prod-us KMS key ARN.
Both accounts must authorize the reader role.
Readers have key-read and decrypt permissions; they cannot create keys or change deletion state.
Use metadata block locations and byte ranges to fetch recordings, then decrypt before decompressing.
-Include all relevant metadata arrival dates when collecting a session with late blocks.
+Read metadata from the session start month, including blocks that arrive in later months.
Join analytics on both raw team and session IDs.
Remove identifiers from model inputs.
@@ -145,11 +150,18 @@ Resolve image references before training because they contain team IDs.
## Images and Kafka
-V2 references are `image:v2:<team>:<YYYY-MM>:<hash>` and `imageurl:v2:<team>:<YYYY-MM>:<hash>`.
-Images do not deduplicate across teams or session start months.
+V2 references are `image:v2:<team>:<month>:<hash>` and `imageurl:v2:<team>:<month>:<hash>`.
+Images do not deduplicate across teams or session months.
Source messages use session keys; stored scrubbed images use team image keys.
+Consumers reject malformed UUIDv7 session identifiers before reading DynamoDB.
+Oversized identifiers cannot fail a whole bulk key lookup.
+Inline images have an encrypted lookup for each reference, published after the shard and its index.
+Readers fetch that lookup directly; a missing image does not require a scan of the team's image history.
Source deduplication includes the session, so deleting one source session cannot suppress another session's copy.
The v2 image-fetch frontier uses a separate, initially empty DynamoDB history table.
+Its URL history expires eight days after the end of the session's UTC month.
+Explicit HTTP freshness or cache restrictions can shorten this expiry; they cannot extend it.
+Robots.txt and TDM reservation caches keep their shared origin keys and existing expiry rules.
It does not inherit v1 seen flags or successful fetch results.
ML Kafka producers write `ai_research_ingestion_version: 1` or `2`.
@@ -175,6 +187,31 @@ The wrapped HMAC secret keeps the single name `SESSION_RECORDING_ML_PSEUDONYM_WR
It has no new alias.
Renaming configuration must not rotate that key.
+The shared ML server configuration applies the legacy aliases before explicit server overrides.
+An image scrubber with privacy enabled must configure `SESSION_RECORDING_ML_IMAGE_SCRUB_DLQ_TOPIC` before startup.
+Malformed encrypted images retain their original payload and headers in the dead-letter queue.
+The scrubber retries failed dead-letter writes and interrupts retry waits during shutdown.
+The image fetch consumer dead-letters unsupported ingestion version headers while processing other valid records in the batch.
+A v2 message without privacy configuration still fails the batch because it needs the missing encryption settings.
+
+V2 data uses `YYYY-MM` directories from the session UUIDv7 start timestamp in UTC.
+Recording blocks, metadata, image shards, image lookups and URL images retain that month across late arrivals.
+V2 image references include `<team>:<month>:<hash>`, so the image-fetch seen history is independent for each month.
+Robots.txt and TDM reservation caches remain shared by origin across months.
+
+## JSON-LD evaluation index
+
+The v2 metadata consumer writes a separate encrypted index for `json_ld`, `full_snapshot`, and `page` entries.
+The path uses the session's UTC start month, even when events or uploads fall in a later month.
+Each Parquet row exposes real `team_id` and `session_id` values and encrypts the projected entries with the session key.
+Session, person, team, and month deletion therefore remove access to the index along with its recording.
+The JSON-LD payload remains in the referenced recording block.
+
+Use the real team ID to exclude all teams present in the model's training data before selecting eval examples.
+The exclusion must cover every training month, not only the eval partition's month.
+Use the encrypted reader for index entries, then fetch selected recording blocks to inspect their JSON-LD payloads.
+Legacy v1 indexes retain their pseudonymized identifiers and daily partitions.
+
### Privacy worker isolation
The privacy task uses the `ai_research_privacy` Celery queue.
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 3b4c3bf829c8..d9d864f30fe2 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -9333,7 +9333,7 @@ dependencies = [
[[package]]
name = "posthog-replay-anonymizer"
-version = "0.6.2"
+version = "0.7.0"
dependencies = [
"ahash 0.8.12",
"anyhow",
diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.ts
index 1bb9963e8bd4..a28cf457e170 100644
--- a/rust/replay-anonymizer-node/src/index.ts
+++ b/rust/replay-anonymizer-node/src/index.ts
@@ -142,31 +142,35 @@ export function initAnonymizer(allow: AllowListsInput): void {
*
* `cv` payloads re-emit as zstd; the reader dispatches on magic bytes.
*
- * Non-empty `pseudoTeam` + `contentKey` (the per-team HMAC pseudonym and content-hash key — never
- * the raw team id or master secret) enable the image-collection lane: inlined images are replaced
- * with `image:<pseudoTeam>:<hash>` refs (hash = keyed HMAC of the bytes) instead of the inline
+ * Non-empty `teamId` + `contentKey` enable image collection using the raw team ID and per-team
+ * content HMAC key. The master secret stays with the caller. Inlined images are replaced
+ * with `image:<teamId>:<hash>` refs (hash = keyed HMAC of the bytes) instead of the inline
* blur, and the original bytes come back in `images`/`meta.images` for the caller to produce to
* the scrub topic.
*
* `urlKey` enables the URL-collection lane independently. It is the global URL HMAC key. A remote
* image's `src` keeps the media placeholder, a namespaced sibling attribute carries its ref, and
* its original URL comes back in `meta.urls` for the caller to hand to the fetch lane.
+ * `referenceNamespace` scopes URL refs as `imageurl:<namespace>:<hash>`; omitting it produces
+ * `imageurl:<hash>`. For v2, pass `v2:<raw team id>:<YYYY-MM>` as both `teamId` and `referenceNamespace`.
*
- * The two lanes are independent: either, both, or neither. Only `contentKey` needs `pseudoTeam`.
+ * The two lanes are independent: either, both, or neither. Only `contentKey` needs `teamId`.
*/
export async function anonymizeKafkaPayload(
payload: Buffer,
contentEncoding?: string | null,
- pseudoTeam?: string | null,
+ teamId?: string | null,
contentKey?: string | null,
- urlKey?: string | null
+ urlKey?: string | null,
+ referenceNamespace?: string | null
): Promise<AnonymizeKafkaPayloadResult> {
const result = await native.anonymizeKafkaPayload(
payload,
contentEncoding ?? undefined,
- pseudoTeam ?? undefined,
+ teamId ?? undefined,
contentKey ?? undefined,
- urlKey ?? undefined
+ urlKey ?? undefined,
+ referenceNamespace ?? undefined
)
// Timings are best-effort telemetry: a malformed timings blob must never fail the message.
let timings: AnonymizeTimings | null = null
diff --git a/rust/replay-anonymizer-node/src/lib.rs b/rust/replay-anonymizer-node/src/lib.rs
index 2efaa5b752cc..09779617787f 100644
--- a/rust/replay-anonymizer-node/src/lib.rs
+++ b/rust/replay-anonymizer-node/src/lib.rs
@@ -87,7 +87,7 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {
.and_then(|v| v.downcast::<JsString, _>(&mut cx).ok())
.map(|s| s.value(&mut cx));
// Present + non-empty (both of them) enables the image-collection lane, keyed to this
- // pseudonymous team id and per-team content-HMAC key. A present-but-non-string argument, or one
+ // raw team ID and per-team content-HMAC key. A present-but-non-string argument, or one
// of the pair without the other, must fail loudly (the caller drops the message) rather than
// silently disable or mis-key collection; only absent/undefined/null mean "collection off".
let opt_string_arg = |cx: &mut FunctionContext, index: usize| -> NeonResult<Option<String>> {
@@ -98,20 +98,24 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {
}
.filter(|s| !s.is_empty()))
};
- let pseudo_team = opt_string_arg(&mut cx, 2)?;
+ let team_id = opt_string_arg(&mut cx, 2)?;
let content_key = opt_string_arg(&mut cx, 3)?;
let url_key = opt_string_arg(&mut cx, 4)?;
- if pseudo_team.is_none() && content_key.is_some() {
- return cx.throw_error("contentKey requires pseudoTeam");
+ let reference_namespace = opt_string_arg(&mut cx, 5)?;
+ if team_id.is_none() && content_key.is_some() {
+ return cx.throw_error("contentKey requires teamId");
}
- let image_collection = match (pseudo_team.clone(), content_key) {
- (Some(pseudo_team), Some(content_key)) => Some(ImageCollection {
- pseudo_team,
+ let image_collection = match (team_id.clone(), content_key) {
+ (Some(team_id), Some(content_key)) => Some(ImageCollection {
+ team_id,
content_key,
}),
_ => None,
};
- let url_collection = url_key.map(|url_key| UrlCollection { url_key });
+ let url_collection = url_key.map(|url_key| UrlCollection {
+ url_key,
+ reference_namespace,
+ });
// Created on the JS thread so every offset shares one monotonic origin: the task-start mark
// becomes the threadpool queue wait, and no wall clock is involved.
let timings = PhaseTimings::new();
diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.toml
index a098d1f051bb..4ce401501ffc 100644
--- a/rust/replay-anonymizer/Cargo.toml
+++ b/rust/replay-anonymizer/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "posthog-replay-anonymizer"
-version = "0.6.2"
+version = "0.7.0"
edition = "2021"
description = "PII scrubber for rrweb session-replay events: text/URL redaction, native image blur, and canvas/cv neutralization"
license = "MIT"
diff --git a/rust/replay-anonymizer/src/canvas.rs b/rust/replay-anonymizer/src/canvas.rs
index c5ef851875a4..4668cd0cbf58 100644
--- a/rust/replay-anonymizer/src/canvas.rs
+++ b/rust/replay-anonymizer/src/canvas.rs
@@ -441,7 +441,7 @@ mod tests {
let ctx = Ctx::with_image_collection(
&allow,
Some(ImageCollection {
- pseudo_team: "0".repeat(32),
+ team_id: "0".repeat(32),
content_key: "k".repeat(32),
}),
);
diff --git a/rust/replay-anonymizer/src/collect.rs b/rust/replay-anonymizer/src/collect.rs
index 613fb98327b2..634a6468f960 100644
--- a/rust/replay-anonymizer/src/collect.rs
+++ b/rust/replay-anonymizer/src/collect.rs
@@ -1,17 +1,17 @@
//! Collect original image bytes for the out-of-band scrub lane.
//!
//! With collection enabled (an [`ImageCollection`] on the anonymize call), each inlined image is
-//! replaced by a stable content reference — `image:<pseudoTeam>:<hash>` — instead of the native
+//! replaced by a stable content reference, `image:<teamId>:<hash>`, instead of the native
//! blur, and the original bytes ride back to the caller on the message. The caller produces them
//! to the `session_replay_image_scrub` Kafka topic keyed by the ref; the scrub consumer trusts the
//! ref (this producer is the only writer), blurs the bytes out of process, and writes them to the
-//! ML bucket indexed by `(pseudo_team, hash)` — so the ref embedded in the mirrored lines is the
+//! ML bucket indexed by `(team_id, hash)`, so the ref embedded in the mirrored lines is the
//! join key.
//!
//! The hash is a *keyed* HMAC, not a plain digest: the ML bucket is unencrypted, and a plain
//! content hash would let any bucket reader confirm whether specific known bytes appeared in a
//! session (and correlate identical images across teams). The per-team key is derived by the
-//! caller from the same KMS-held secret as the team pseudonym, so neither leaves the ingester.
+//! caller from the KMS-held pseudonymization secret, which never leaves the ingester.
//! `image-hash.json` pins the construction against Node `createHmac` reference vectors.
use std::collections::HashSet;
@@ -30,8 +30,8 @@ pub fn hash_image_bytes(content_key: &[u8], bytes: &[u8]) -> String {
b64
}
-pub fn image_ref(pseudo_team: &str, hash: &str) -> String {
- format!("image:{pseudo_team}:{hash}")
+pub fn image_ref(team_id: &str, hash: &str) -> String {
+ format!("image:{team_id}:{hash}")
}
/// The prefix of a ref whose hash comes from a URL rather than from bytes.
@@ -60,31 +60,57 @@ pub fn is_image_ref(s: &str) -> bool {
/// True only for a fully well-formed content ref or URL ref.
///
/// The loose prefix check would let a captured page set a media attribute to `image:<anything>` and
-/// have it copied verbatim into anonymized output. This bounds what can survive to a fixed-width
-/// opaque token with no room for readable content.
+/// have it copied verbatim into anonymized output. Limit preserved refs to a numeric team ID
+/// or legacy pseudonym and a fixed-width hash.
pub fn is_image_ref_strict(s: &str) -> bool {
+ if let Some(rest) = s
+ .strip_prefix("image:v2:")
+ .or_else(|| s.strip_prefix("imageurl:v2:"))
+ {
+ let parts: Vec<&str> = rest.split(':').collect();
+ return parts.len() == 3
+ && is_raw_team_id(parts[0])
+ && parts[1].len() == 7
+ && parts[1].as_bytes()[..4].iter().all(u8::is_ascii_digit)
+ && parts[1].as_bytes()[4] == b'-'
+ && matches!(
+ &parts[1][5..],
+ "01" | "02" | "03" | "04" | "05" | "06" | "07" | "08" | "09" | "10" | "11" | "12"
+ )
+ && is_ref_hash(parts[2]);
+ }
if let Some(rest) = s.strip_prefix("image:") {
let Some((team, hash)) = rest.split_once(':') else {
return false;
};
- return is_pseudo_team(team) && is_ref_hash(hash);
+ return (is_raw_team_id(team) || is_legacy_team_pseudonym(team)) && is_ref_hash(hash);
}
if let Some(rest) = s.strip_prefix("imageurl:") {
return is_ref_hash(rest)
|| rest
.split_once(':')
- .is_some_and(|(team, hash)| is_pseudo_team(team) && is_ref_hash(hash));
+ .is_some_and(|(team, hash)| is_legacy_team_pseudonym(team) && is_ref_hash(hash));
}
false
}
-fn is_pseudo_team(team: &str) -> bool {
+fn is_legacy_team_pseudonym(team: &str) -> bool {
team.len() == 32
&& team
.bytes()
.all(|b| b.is_ascii_digit() || b.is_ascii_lowercase() && b <= b'f')
}
+fn is_raw_team_id(team: &str) -> bool {
+ !team.starts_with('0')
+ && !team.is_empty()
+ && team.len() <= 16
+ && team.bytes().all(|b| b.is_ascii_digit())
+ && team
+ .parse::<u64>()
+ .is_ok_and(|id| id <= 9_007_199_254_740_991)
+}
+
fn is_ref_hash(hash: &str) -> bool {
hash.len() == 22
&& hash
@@ -112,10 +138,8 @@ pub const MAX_TOTAL_BYTES_PER_MESSAGE: usize = 32 * 1024 * 1024;
/// Enables collection for one anonymize call.
#[derive(Debug, Clone)]
pub struct ImageCollection {
- /// The non-reversible HMAC team pseudonym (32 hex chars), computed by the caller — the secret
- /// never crosses into this crate. Embedded verbatim in every emitted ref.
- pub pseudo_team: String,
- /// Per-team key for the content HMAC, derived by the caller alongside the pseudonym. Its ASCII
+ pub team_id: String,
+ /// Per-team key for the content HMAC, derived by the caller. Its ASCII
/// bytes key [`hash_image_bytes`].
pub content_key: String,
}
@@ -128,7 +152,7 @@ pub struct CollectedImage {
/// Accumulates the images of one message. Byte-level dedup on the hash: the same image arriving
/// under different URIs (or after the per-URI memo misses) is collected once but still gets its ref.
pub struct ImageCollector {
- pseudo_team: String,
+ team_id: String,
content_key: String,
images: Vec<CollectedImage>,
seen: HashSet<String>,
@@ -138,7 +162,7 @@ pub struct ImageCollector {
impl ImageCollector {
pub fn new(collection: ImageCollection) -> Self {
Self {
- pseudo_team: collection.pseudo_team,
+ team_id: collection.team_id,
content_key: collection.content_key,
images: Vec::new(),
seen: HashSet::new(),
@@ -154,7 +178,7 @@ impl ImageCollector {
}
let hash = hash_image_bytes(self.content_key.as_bytes(), &bytes);
if self.seen.contains(&hash) {
- return Some(image_ref(&self.pseudo_team, &hash));
+ return Some(image_ref(&self.team_id, &hash));
}
if self.images.len() >= MAX_IMAGES_PER_MESSAGE
|| self.total_bytes + bytes.len() > MAX_TOTAL_BYTES_PER_MESSAGE
@@ -167,7 +191,7 @@ impl ImageCollector {
hash: hash.clone(),
bytes,
});
- Some(image_ref(&self.pseudo_team, &hash))
+ Some(image_ref(&self.team_id, &hash))
}
/// Drain, sorted by hash — a deterministic order that cannot depend on which scrub engine
@@ -240,7 +264,7 @@ mod tests {
fn collector() -> ImageCollector {
ImageCollector::new(ImageCollection {
- pseudo_team: "a".repeat(32),
+ team_id: "a".repeat(32),
content_key: String::from_utf8(TEST_KEY.to_vec()).unwrap(),
})
}
@@ -259,13 +283,27 @@ mod tests {
#[test]
fn ref_matches_consumer_shape() {
- // The consumer's REF_RE: image:<32 hex>:<22 base64url>.
- let r = image_ref(&"ab".repeat(16), &hash_image_bytes(TEST_KEY, b"x"));
- assert!(is_image_ref(&r));
- let parts: Vec<&str> = r.splitn(3, ':').collect();
- assert_eq!(parts[0], "image");
- assert_eq!(parts[1].len(), 32);
- assert_eq!(parts[2].len(), 22);
+ let hash = hash_image_bytes(TEST_KEY, b"x");
+ for prefix in ["image:v2", "imageurl:v2"] {
+ assert!(is_image_ref_strict(&format!("{prefix}:42:2026-09:{hash}")));
+ for invalid in [
+ "42:2026-13",
+ "42:2026-00",
+ "42:202-09",
+ "42:2026-9",
+ "0:2026-09",
+ "42:2026_09",
+ "42",
+ ] {
+ assert!(!is_image_ref_strict(&format!("{prefix}:{invalid}:{hash}")));
+ }
+ }
+ for team in ["42", "9007199254740991", "0123456789abcdef0123456789abcdef"] {
+ assert!(is_image_ref_strict(&image_ref(team, &hash)));
+ }
+ for team in ["0", "01", "-1", "9007199254740992", "1e3", "secret"] {
+ assert!(!is_image_ref_strict(&image_ref(team, &hash)));
+ }
}
#[test]
diff --git a/rust/replay-anonymizer/src/css.rs b/rust/replay-anonymizer/src/css.rs
index 2bf9c6b77942..cdf0a2180f6f 100644
--- a/rust/replay-anonymizer/src/css.rs
+++ b/rust/replay-anonymizer/src/css.rs
@@ -705,7 +705,7 @@ mod tests {
let ctx = Ctx::with_image_collection(
&allow,
Some(ImageCollection {
- pseudo_team: "0123456789abcdef0123456789abcdef".to_string(),
+ team_id: "0123456789abcdef0123456789abcdef".to_string(),
content_key: "fedcba9876543210fedcba9876543210".to_string(),
}),
);
@@ -732,11 +732,12 @@ mod tests {
let ctx = Ctx::with_image_collection(
&allow,
Some(ImageCollection {
- pseudo_team: "0123456789abcdef0123456789abcdef".to_string(),
+ team_id: "0123456789abcdef0123456789abcdef".to_string(),
content_key: "fedcba9876543210fedcba9876543210".to_string(),
}),
)
.collecting_urls(Some(UrlCollection {
+ reference_namespace: None,
url_key: "0123456789abcdef0123456789abcdef".to_string(),
}));
let original = png_data_uri(8, 8, [10, 20, 30, 255]);
@@ -765,6 +766,7 @@ mod tests {
fn collected_remote_images_record_the_css_property() {
let allow = AllowLists::default();
let ctx = Ctx::new(&allow).collecting_urls(Some(UrlCollection {
+ reference_namespace: None,
url_key: "0123456789abcdef0123456789abcdef".to_string(),
}));
let css = "mask-image:url('https://cdn.example.com/mask.png')";
@@ -787,7 +789,7 @@ mod tests {
let ctx = Ctx::with_image_collection(
&allow,
Some(ImageCollection {
- pseudo_team: "0123456789abcdef0123456789abcdef".to_string(),
+ team_id: "0123456789abcdef0123456789abcdef".to_string(),
content_key: "fedcba9876543210fedcba9876543210".to_string(),
}),
);
diff --git a/rust/replay-anonymizer/src/url_collect.rs b/rust/replay-anonymizer/src/url_collect.rs
index 1f4bb3a467a0..4bb6dcb37f3c 100644
--- a/rust/replay-anonymizer/src/url_collect.rs
+++ b/rust/replay-anonymizer/src/url_collect.rs
@@ -51,6 +51,8 @@ pub const MAX_URLS_PER_MESSAGE: usize = 512;
/// Enables URL collection for one anonymize call.
#[derive(Debug, Clone)]
pub struct UrlCollection {
+ /// Use `v2:<raw_team_id>:<YYYY-MM>` or a 32-character lowercase hexadecimal pseudonym. `None` produces global URL refs.
+ pub reference_namespace: Option<String>,
/// Global key for the URL HMAC. The caller derives it under a URL-specific domain separator.
pub url_key: String,
}
@@ -83,6 +85,7 @@ pub fn hash_url(url_key: &[u8], dedup_url: &str) -> String {
/// Accumulates the remote image URLs of one message, deduplicated on the hash.
pub struct UrlCollector {
+ reference_namespace: Option<String>,
url_key: String,
urls: Vec<CollectedUrl>,
seen: HashSet<String>,
@@ -101,6 +104,7 @@ pub struct UrlCollector {
impl UrlCollector {
pub fn new(collection: UrlCollection) -> Self {
Self {
+ reference_namespace: collection.reference_namespace,
url_key: collection.url_key,
urls: Vec::new(),
seen: HashSet::new(),
@@ -155,6 +159,13 @@ impl UrlCollector {
*self.declines.entry(reason).or_insert(0) += 1;
}
+ fn reference(&self, hash: &str) -> String {
+ match &self.reference_namespace {
+ Some(namespace) => format!("imageurl:{namespace}:{hash}"),
+ None => crate::collect::url_ref(hash),
+ }
+ }
+
fn collect_uncached(&mut self, raw: &str) -> Option<String> {
let canonical = match try_canonicalize(raw) {
Ok(c) => c,
@@ -165,7 +176,7 @@ impl UrlCollector {
};
let hash = hash_url(self.url_key.as_bytes(), &canonical.dedup);
if self.seen.contains(&hash) {
- return Some(crate::collect::url_ref(&hash));
+ return Some(self.reference(&hash));
}
self.seen.insert(hash.clone());
self.urls.push(CollectedUrl {
@@ -174,7 +185,7 @@ impl UrlCollector {
host: canonical.host,
domain: canonical.domain,
});
- Some(crate::collect::url_ref(&hash))
+ Some(self.reference(&hash))
}
/// Counts by reason for the URLs this collector refused.
@@ -203,6 +214,7 @@ mod tests {
fn collector() -> UrlCollector {
UrlCollector::new(UrlCollection {
+ reference_namespace: None,
url_key: String::from_utf8(TEST_KEY.to_vec()).unwrap(),
})
}
diff --git a/rust/replay-anonymizer/tests/image_token_fuzz.rs b/rust/replay-anonymizer/tests/image_token_fuzz.rs
index 9aa7ed40f6c4..913d1613c0a9 100644
--- a/rust/replay-anonymizer/tests/image_token_fuzz.rs
+++ b/rust/replay-anonymizer/tests/image_token_fuzz.rs
@@ -209,7 +209,7 @@ fn fuzz_no_deferred_image_token_reaches_output() {
image_policy: ImagePolicy::Parallel,
},
collect.then(|| ImageCollection {
- pseudo_team: "a".repeat(32),
+ team_id: "a".repeat(32),
content_key: "0123456789abcdef0123456789abcdef".to_string(),
}),
);
diff --git a/rust/replay-anonymizer/tests/image_token_leak.rs b/rust/replay-anonymizer/tests/image_token_leak.rs
index b17c5a035864..27dabcaa1242 100644
--- a/rust/replay-anonymizer/tests/image_token_leak.rs
+++ b/rust/replay-anonymizer/tests/image_token_leak.rs
@@ -96,7 +96,7 @@ fn svg_data_uri() -> String {
fn collection() -> ImageCollection {
ImageCollection {
- pseudo_team: "a".repeat(32),
+ team_id: "a".repeat(32),
content_key: "0123456789abcdef0123456789abcdef".to_string(),
}
}
diff --git a/rust/replay-anonymizer/tests/ref_idempotence.rs b/rust/replay-anonymizer/tests/ref_idempotence.rs
index 2fd4c0ba0cb6..65ecb52ac6e1 100644
--- a/rust/replay-anonymizer/tests/ref_idempotence.rs
+++ b/rust/replay-anonymizer/tests/ref_idempotence.rs
@@ -1,7 +1,7 @@
//! Re-scrubbing already-mirrored output must preserve its image content refs — but only when the
//! caller vouches for where that input came from.
//!
-//! The mirror replaces each inlined image with an `image:<pseudo_team>:<hash>` ref and ships the
+//! The mirror replaces each inlined image with an `image:<team_id>:<hash>` ref and ships the
//! bytes out of band, so that ref is the only join key back to them. Remote images keep a media
//! placeholder and carry an `imageurl:<hash>` ref in a namespaced sibling attribute.
//! Scrubbing mirrored output a second time must not destroy either join key.
@@ -18,7 +18,7 @@ use posthog_replay_anonymizer::{
use serde_json::{json, Value};
const TS0: f64 = 1_700_000_000_000.0;
-const REF: &str = "image:0123456789abcdef0123456789abcdef:AAAAAAAAAAAAAAAAAAAAAA";
+const REF: &str = "image:42:AAAAAAAAAAAAAAAAAAAAAA";
const URL_REF: &str = "imageurl:AAAAAAAAAAAAAAAAAAAAAA";
const LEGACY_URL_REF: &str = "imageurl:0123456789abcdef0123456789abcdef:AAAAAAAAAAAAAAAAAAAAAA";
const NUMBERED_PLACEHOLDER: &str = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 80 80'><rect width='80' height='80' fill='%23f3f4f6'/><rect x='6' y='6' width='68' height='68' fill='none' stroke='%23d1d5db' stroke-width='2' rx='6'/><circle cx='26' cy='26' r='6' fill='%239ca3af'/><path d='M14 60 L34 40 L48 50 L66 32 L66 66 L14 66 Z' fill='%239ca3af'/><metadata id='anon-image-slot-0'/></svg>";
diff --git a/rust/replay-anonymizer/tests/snapshot.rs b/rust/replay-anonymizer/tests/snapshot.rs
index 76c2e178fec4..f34016869259 100644
--- a/rust/replay-anonymizer/tests/snapshot.rs
+++ b/rust/replay-anonymizer/tests/snapshot.rs
@@ -868,15 +868,12 @@ fn collect_payload() -> String {
fn image_collection_replaces_images_with_refs_and_returns_the_bytes() {
use base64::Engine;
let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
- let pseudo_team = "0123456789abcdef0123456789abcdef".to_string();
+ let team_id = "42".to_string();
let content_key = "fedcba9876543210fedcba9876543210".to_string();
let png = base64::engine::general_purpose::STANDARD
.decode(COLLECT_PNG_B64)
.unwrap();
- let expected_ref = image_ref(
- &pseudo_team,
- &hash_image_bytes(content_key.as_bytes(), &png),
- );
+ let expected_ref = image_ref(&team_id, &hash_image_bytes(content_key.as_bytes(), &png));
// Both image policies: collection must take precedence over the parallel worker pool — a
// collected image needs no blur, so it must come back as a ref, never a pool token.
@@ -891,7 +888,7 @@ fn image_collection_replaces_images_with_refs_and_returns_the_bytes() {
image_policy,
},
Some(ImageCollection {
- pseudo_team: pseudo_team.clone(),
+ team_id: team_id.clone(),
content_key: content_key.clone(),
}),
)
@@ -983,7 +980,7 @@ fn image_collection_svg_stays_on_the_inline_scrub_path() {
&mut bytes,
AnonymizeOpts::default(),
Some(ImageCollection {
- pseudo_team: "0123456789abcdef0123456789abcdef".to_string(),
+ team_id: "0123456789abcdef0123456789abcdef".to_string(),
content_key: "fedcba9876543210fedcba9876543210".to_string(),
}),
)
diff --git a/rust/replay-anonymizer/tests/url_collection.rs b/rust/replay-anonymizer/tests/url_collection.rs
index 2d4cd7204e6a..48387fa4230e 100644
--- a/rust/replay-anonymizer/tests/url_collection.rs
+++ b/rust/replay-anonymizer/tests/url_collection.rs
@@ -53,6 +53,7 @@ fn collect_urls_of(tag: &str, attrs: Value) -> Vec<String> {
None,
None,
Some(UrlCollection {
+ reference_namespace: None,
url_key: URL_KEY.to_string(),
}),
)
@@ -165,6 +166,7 @@ fn picture_source_srcset_is_collected_when_its_parent_is_known() {
None,
None,
Some(UrlCollection {
+ reference_namespace: None,
url_key: URL_KEY.to_string(),
}),
)
@@ -210,6 +212,7 @@ fn run(attrs: Value, collect: bool) -> Vec<(String, Value)> {
for byte_walk in [true, false] {
let mut bytes = payload(attrs.clone());
let collection = collect.then(|| UrlCollection {
+ reference_namespace: None,
url_key: URL_KEY.to_string(),
});
let msg = anonymize_kafka_payload_collecting(
@@ -401,6 +404,7 @@ fn an_escaped_or_repeated_dimension_key_still_declines_a_hidden_pixel() {
None,
None,
Some(UrlCollection {
+ reference_namespace: None,
url_key: URL_KEY.to_string(),
}),
)
@@ -621,6 +625,7 @@ fn a_refusal_is_counted_with_a_reason() {
None,
None,
Some(UrlCollection {
+ reference_namespace: None,
url_key: URL_KEY.to_string(),
}),
)
@@ -635,3 +640,63 @@ fn a_refusal_is_counted_with_a_reason() {
.collect();
assert!(reasons.contains(&"non_public_host"), "{reasons:?}");
}
+
+#[test]
+fn monthly_refs_survive_compressed_snapshot_fields() {
+ use posthog_replay_anonymizer::{compression, ImageCollection};
+ let namespace = "v2:7:2026-09";
+ let snapshot = json!({"node": {"type": 2, "tagName": "div", "id": 1,
+ "attributes": {}, "childNodes": [
+ {"type": 2, "tagName": "img", "id": 2, "attributes": {"src": "https://cdn.example.com/a.png"}, "childNodes": []},
+ {"type": 2, "tagName": "img", "id": 3, "attributes": {"src": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/l1sAAAAASUVORK5CYII="}, "childNodes": []}
+ ]}, "initialOffset": {"top": 0, "left": 0}});
+ let compressed = zstd::stream::encode_all(snapshot.to_string().as_bytes(), 1).unwrap();
+ let wire: String = compressed.iter().map(|byte| char::from(*byte)).collect();
+ for byte_walk in [true, false] {
+ let data = json!({"event": "$snapshot_items", "properties": {"$session_id": "s", "$window_id": "w",
+ "$snapshot_items": [{"type": 2, "timestamp": TS0, "cv": "2024-10", "data": wire}]}});
+ let mut payload = json!({"distinct_id": "d", "data": data.to_string()})
+ .to_string()
+ .into_bytes();
+ let output = anonymize_kafka_payload_collecting(
+ &AllowLists::default(),
+ &mut payload,
+ AnonymizeOpts {
+ byte_walk,
+ image_policy: ImagePolicy::Inline,
+ },
+ None,
+ Some(ImageCollection {
+ team_id: namespace.to_string(),
+ content_key: URL_KEY.to_string(),
+ }),
+ Some(UrlCollection {
+ url_key: URL_KEY.to_string(),
+ reference_namespace: Some(namespace.to_string()),
+ }),
+ )
+ .unwrap();
+ let event: Value =
+ serde_json::from_slice(output.lines.split(|byte| *byte == b'\n').next().unwrap())
+ .unwrap();
+ let stored: Vec<u8> = event[1]["data"]
+ .as_str()
+ .unwrap()
+ .chars()
+ .map(|character| character as u8)
+ .collect();
+ let decoded: Value =
+ serde_json::from_slice(&compression::decompress_by_magic(&stored).unwrap()).unwrap();
+ let nodes = &decoded["node"]["childNodes"];
+ assert!(nodes[0]["attributes"]["data-anon-image-ref-src"]
+ .as_str()
+ .unwrap()
+ .starts_with("imageurl:v2:7:2026-09:"));
+ assert!(nodes[1]["attributes"]["src"]
+ .as_str()
+ .unwrap()
+ .starts_with("image:v2:7:2026-09:"));
+ assert_eq!(output.meta.urls.len(), 1);
+ assert_eq!(output.meta.images.len(), 1);
+ }
+}