:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ai-research): add the image fetch topic and the mirror producer (#80909)
Robbie39a2fd00be2e
diff --git a/nodejs/src/common/config/kafka-topics.ts b/nodejs/src/common/config/kafka-topics.tsindex 9ff9db30182c..c27be037384d 100644--- a/nodejs/src/common/config/kafka-topics.ts+++ b/nodejs/src/common/config/kafka-topics.ts@@ -43,6 +43,13 @@ export const KAFKA_SESSION_REPLAY_ML_BLOCK_METADATA = `${prefix}session_replay_m// raw inlined replay images: ml-mirror producer -> image-scrub workerexport const KAFKA_SESSION_REPLAY_IMAGE_SCRUB = `${prefix}session_replay_image_scrub${suffix}`+// remote image URLs: ml-mirror producer -> image-fetch worker. The Kafka key is the registrable+// domain, not the host. All URLs of one operator therefore go to one partition, and one pod owns+// the request rate of that operator. A CDN that shards over img1..img8.cdn.example.com keys to+// example.com, so it gets one budget rather than eight. A record holds an original, unscrubbed+// URL, so this topic is as sensitive as the raw replay topic.+export const KAFKA_SESSION_REPLAY_IMAGE_FETCH = `${prefix}session_replay_image_fetch${suffix}`+// images the scrub sidecar cannot process, parked so they stop holding the head of their partition.// The original bytes are kept: unscrubbed content must never reach the ML bucket, but it must not be// thrown away either, so it waits here for the sidecar bug behind it to be fixed and replayed.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/config.tsindex 3c354ba40ee2..5c29aa7a6596 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/config.ts@@ -8,14 +8,17 @@ import {KAFKA_SESSION_RECORDING_SNAPSHOT_ITEM_DLQ,KAFKA_SESSION_RECORDING_SNAPSHOT_ITEM_EVENTS,KAFKA_SESSION_RECORDING_SNAPSHOT_ITEM_OVERFLOW,+ KAFKA_SESSION_REPLAY_IMAGE_FETCH,KAFKA_SESSION_REPLAY_IMAGE_SCRUB,KAFKA_SESSION_REPLAY_ML_BLOCK_METADATA,} from '~/common/config/kafka-topics'import { isDevEnv } from '~/common/utils/env-utils'import { INGESTION_DOWNSTREAM_PRODUCER, type IngestionDownstreamProducer } from '~/ingestion/common/outputs/producers'import {+ INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER,INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER,INGESTION_SESSIONREPLAY_PRODUCER,+ type IngestionSessionreplayMlImageFetchProducer,type IngestionSessionreplayMlImageScrubProducer,type IngestionSessionreplayProducer,} from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'@@ -31,6 +34,7 @@ export type SessionReplayProducerName =| IngestionDownstreamProducer| IngestionSessionreplayProducer| IngestionSessionreplayMlImageScrubProducer+ | IngestionSessionreplayMlImageFetchProducerexport type SessionRecordingApiConfig = {SESSION_RECORDING_API_REDIS_HOST: string@@ -193,6 +197,9 @@ export type SessionReplayOutputsConfig = {INGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_SCRUB_TOPIC: stringINGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_SCRUB_PRODUCER: SessionReplayProducerName++ INGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_FETCH_TOPIC: string+ INGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_FETCH_PRODUCER: SessionReplayProducerName}export function getDefaultSessionReplayOutputsConfig(): SessionReplayOutputsConfig {@@ -216,5 +223,9 @@ export function getDefaultSessionReplayOutputsConfig(): SessionReplayOutputsConfINGESTION_SESSIONREPLAY_OUTPUT_ML_BLOCK_METADATA_PRODUCER: INGESTION_SESSIONREPLAY_PRODUCER,INGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_SCRUB_TOPIC: KAFKA_SESSION_REPLAY_IMAGE_SCRUB,INGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_SCRUB_PRODUCER: INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER,+ INGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_FETCH_TOPIC: KAFKA_SESSION_REPLAY_IMAGE_FETCH,+ // Its own producer instance, not the scrub lane's. See the doc block on+ // INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER for why the two must not share a queue.+ INGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_FETCH_PRODUCER: INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER,}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.tsindex 70570b1cc103..a010750627ff 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts@@ -14,7 +14,7 @@ export type MlImageLaneStage = 'collected' | 'deduped' | 'queued' | 'produced' |/** Stages of the URL lane. Deliberately the same vocabulary as {@link MlImageLaneStage}, so the two* lanes read the same way on a dashboard even though only `collected` exists until the fetch lane* ships. */-export type MlUrlLaneStage = 'collected' | 'deduped' | 'queued' | 'produced' | 'produce_failed'+export type MlUrlLaneStage = 'collected' | 'deduped' | 'queued' | 'produced' | 'produce_failed' | 'ref_unusable'export class SessionRecordingIngesterMetrics {private static readonly sessionsHandled = new Gauge({diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.tsindex 3412a06c95c4..8841dc9be461 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts@@ -55,6 +55,26 @@ export type MlMirrorConfig = {* URLs and how many distinct hosts real traffic carries.*/SESSION_RECORDING_ML_URL_COLLECTION_ENABLED: boolean++ /**+ * Send the collected URLs to the fetch topic.+ *+ * This flag is separate from the collection flag, because the two steps have different risks.+ * Collection changes only the mirrored data. A produce puts original, unscrubbed URLs onto a+ * Kafka topic, so the fetch topic is as sensitive as the raw replay topic. Turn this flag on+ * only after the topic exists with the retention that section 2.5 of the plan gives it.+ *+ * The flag does nothing unless SESSION_RECORDING_ML_URL_COLLECTION_ENABLED is also on, because+ * the anonymizer collects no URLs until then.+ */+ SESSION_RECORDING_ML_URL_PRODUCER_ENABLED: boolean++ /**+ * Capacity of the mirror's produced-URL ref cache, which bounds re-produces onto the fetch+ * topic. Tunable for the same reason as its image-lane twin below: it trades memory for topic+ * volume, so a mirror memory incident must be able to shed it without a code deploy.+ */+ SESSION_RECORDING_ML_URL_PRODUCED_REF_CACHE_MAX: numberSESSION_RECORDING_ML_IMAGE_SCRUB_GROUP_ID: stringSESSION_RECORDING_ML_IMAGE_SCRUB_PREFIX: stringSESSION_RECORDING_ML_IMAGE_SCRUB_SIDECAR_URL: string@@ -123,6 +143,8 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {SESSION_RECORDING_ML_REDIS_PORT: 6379,SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED: false,SESSION_RECORDING_ML_URL_COLLECTION_ENABLED: false,+ SESSION_RECORDING_ML_URL_PRODUCER_ENABLED: false,+ SESSION_RECORDING_ML_URL_PRODUCED_REF_CACHE_MAX: 500_000,SESSION_RECORDING_ML_IMAGE_SCRUB_GROUP_ID: 'session-replay-ml-image-scrub',SESSION_RECORDING_ML_IMAGE_SCRUB_PREFIX: 'scrubbed-images',// 127.0.0.1, not localhost: the sidecar binds IPv4 loopback, and localhost can resolve to ::1 first.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.tsindex e2e00d6ccd74..d24d9bd0a064 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts@@ -15,6 +15,7 @@ import {} from '~/ingestion/pipelines/sessionreplay'import { createAiTrainingOptInFilterStep } from '~/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step'import { createProduceCollectedImagesStep } from '~/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step'+import { createProduceCollectedUrlsStep } from '~/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step'import { createParseAndAnonymizeMessageStep } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'import { MessageContext } from '~/ingestion/pipelines/sessionreplay/pipeline-types'import { createRecordSessionEventStep } from '~/ingestion/pipelines/sessionreplay/record-session-event-step'@@ -22,7 +23,7 @@ import { createMarkSeenStep } from '~/ingestion/pipelines/sessionreplay/session-import { createResolveRetentionStep } from '~/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step'import { createTrackAndGateStep } from '~/ingestion/pipelines/sessionreplay/session-batch-track-and-gate-step'import { createResolveKeyStep } from '~/ingestion/pipelines/sessionreplay/session-resolve-key-step'-import { MlImageScrubOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'+import { MlImageFetchOutput, MlImageScrubOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'import { createTeamFilterStep } from '~/ingestion/pipelines/sessionreplay/team-filter-step'import { createValidateSessionReplayHeadersStep } from '~/ingestion/pipelines/sessionreplay/validate-headers-step'@@ -33,7 +34,14 @@ export interface MlMirrorPipelineOptions {/** Enables the image-collection lane: inlined images become refs, originals go to the scrub topic. */export interface MlMirrorImageScrubProducer {- outputs: IngestionOutputs<MlImageScrubOutput>+ outputs: IngestionOutputs<MlImageFetchOutput | MlImageScrubOutput>+ producedRefCacheMax: number+}++/** Enables the fetch lane's producer: collected URLs go to the fetch topic, keyed by the+ * registrable domain of each URL. */+export interface MlMirrorUrlFetchProducer {+ outputs: IngestionOutputs<MlImageFetchOutput | MlImageScrubOutput>producedRefCacheMax: number}@@ -41,9 +49,11 @@ export interface MlMirrorImageScrubProducer {* Which collection lanes the anonymizer runs, and the key they derive their per-team ref prefix* from.*- * Separate from {@link MlMirrorImageScrubProducer} because collecting and producing are separate- * decisions. The URL lane collects and measures before any topic exists. A requirement to turn the- * scrub producer on first would make that measurement impossible to take on its own.+ * Separate from the two producer settings, because collecting and producing are separate+ * decisions. Collection alone measures. A produce puts original, unscrubbed URLs onto Kafka.+ *+ * The URL lane measures before any topic exists. A requirement to turn a producer on first would+ * make that measurement impossible to take on its own.*/export interface MlMirrorCollection {/** The ML pseudonym HMAC key (also used by the block-metadata sink), for the per-team ref prefix. */@@ -56,7 +66,8 @@ export function createMlMirrorReplayPipeline(config: SessionReplayPipelineConfig,mlOptions: MlMirrorPipelineOptions,imageScrub?: MlMirrorImageScrubProducer,- collection?: MlMirrorCollection+ collection?: MlMirrorCollection,+ urlFetch?: MlMirrorUrlFetchProducer): SessionReplayPipeline {const {outputs,@@ -175,7 +186,15 @@ export function createMlMirrorReplayPipeline()): parsed- return withImagesProduced.pipe(+ const withUrlsProduced = urlFetch+ ? withImagesProduced.pipe(+ createProduceCollectedUrlsStep(+ urlFetch.outputs,+ urlFetch.producedRefCacheMax+ )+ )+ : withImagesProduced+ return withUrlsProduced.pipe(topHogWrapper(createRecordSessionEventStep({isDebugLoggingEnabled,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.tsnew file mode 100644index 000000000000..a1467a991971--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.ts@@ -0,0 +1,230 @@+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'+import { parseJSON } from '~/common/utils/json-parse'+import { PipelineResultType } from '~/ingestion/framework/results'+import { CollectedUrl } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'+import { MlImageFetchOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'++import { createProduceCollectedUrlsStep } from './produce-collected-urls-step'++describe('produceCollectedUrlsStep', () => {+ const PSEUDO_TEAM = 'a'.repeat(32)+ const CAPTURED_AT = 1_700_000_000_000+ let queued: { key: string; value: Buffer }[][]+ let outputs: IngestionOutputs<MlImageFetchOutput>+ let queueMessages: jest.Mock++ beforeEach(() => {+ queued = []+ queueMessages = jest.fn((_output: string, messages: { key: string; value: Buffer }[]) => {+ queued.push(messages)+ return Promise.resolve()+ })+ outputs = { queueMessages } as unknown as IngestionOutputs<MlImageFetchOutput>+ })++ function collected(hash: string, host: string, url: string, domain = host): CollectedUrl {+ return { ref: `imageurl:${PSEUDO_TEAM}:${hash.padEnd(22, 'x')}`, url, host, domain }+ }++ function decode(batch: { key: string; value: Buffer }[]) {+ return batch.map((message) => ({ key: message.key, value: parseJSON(message.value.toString()) }))+ }++ async function run<T extends { collectedUrls?: CollectedUrl[]; message: { timestamp?: number } }>(+ step: ReturnType<typeof createProduceCollectedUrlsStep<T>>,+ input: T+ ) {+ const result = await step(input)+ if (result.type !== PipelineResultType.OK) {+ throw new Error(`expected ok, got ${result.type}`)+ }+ await Promise.all(result.sideEffects)+ return result+ }++ it('sends one message per operator, keyed by the domain, and strips the URLs from the element', async () => {+ // The clock is moved far from CAPTURED_AT on purpose: the record must carry the capture+ // time of the replay message, not the time the mirror produced it.+ jest.useFakeTimers().setSystemTime(new Date('2026-08-10T00:00:00.000Z'))+ try {+ const step = createProduceCollectedUrlsStep(outputs)+ const result = await run(step, {+ message: { timestamp: CAPTURED_AT },+ collectedUrls: [+ collected('h1', 'cdn.example.com', 'https://cdn.example.com/a.jpg?sig=1'),+ collected('h2', 'img.other.com', 'https://img.other.com/b.png'),+ collected('h3', 'cdn.example.com', 'https://cdn.example.com/c.jpg'),+ ],+ })++ expect(result.value.collectedUrls).toBeUndefined()+ expect(queued).toHaveLength(1)+ expect(decode(queued[0])).toEqual([+ {+ key: 'cdn.example.com',+ value: {+ v: 1,+ pseudoTeam: PSEUDO_TEAM,+ capturedAtMs: CAPTURED_AT,+ urls: [+ {+ ref: `imageurl:${PSEUDO_TEAM}:h1xxxxxxxxxxxxxxxxxxxx`,+ url: 'https://cdn.example.com/a.jpg?sig=1',+ host: 'cdn.example.com',+ },+ {+ ref: `imageurl:${PSEUDO_TEAM}:h3xxxxxxxxxxxxxxxxxxxx`,+ url: 'https://cdn.example.com/c.jpg',+ host: 'cdn.example.com',+ },+ ],+ },+ },+ {+ key: 'img.other.com',+ value: {+ v: 1,+ pseudoTeam: PSEUDO_TEAM,+ capturedAtMs: CAPTURED_AT,+ urls: [+ {+ ref: `imageurl:${PSEUDO_TEAM}:h2xxxxxxxxxxxxxxxxxxxx`,+ url: 'https://img.other.com/b.png',+ host: 'img.other.com',+ },+ ],+ },+ },+ ])+ } finally {+ jest.useRealTimers()+ }+ })++ it('passes through elements with no collected URLs without producing', async () => {+ const step = createProduceCollectedUrlsStep(outputs)+ await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: undefined })+ await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [] })+ expect(queueMessages).not.toHaveBeenCalled()+ })++ it('dedups refs it already produced across messages', async () => {+ const step = createProduceCollectedUrlsStep(outputs)+ const first = collected('h1', 'cdn.example.com', 'https://cdn.example.com/a.jpg')+ const second = collected('h2', 'cdn.example.com', 'https://cdn.example.com/b.jpg')+ await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [first] })+ await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [first, second] })+ expect(+ queued.map((batch) => decode(batch).map((m) => m.value.urls.map((u: { ref: string }) => u.ref)))+ ).toEqual([[[first.ref]], [[second.ref]]])+ })++ it('swallows a failed produce and un-marks its refs so a later sighting produces again', async () => {+ queueMessages.mockRejectedValueOnce(new Error('broker down'))+ const step = createProduceCollectedUrlsStep(outputs)+ const entry = collected('h1', 'cdn.example.com', 'https://cdn.example.com/a.jpg')++ const result = await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [entry] })+ expect(result.type).toBe(PipelineResultType.OK)++ await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [entry] })+ expect(queueMessages).toHaveBeenCalledTimes(2)+ // The second produce succeeded, so the ref dedups from then on.+ await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [entry] })+ expect(queueMessages).toHaveBeenCalledTimes(2)+ })++ it('refuses to produce a ref whose hash names bytes rather than a URL', async () => {+ // A bytes ref comes from an image the page inlined, and its hash cannot be reproduced from+ // any URL. Producing one would put a record on the fetch topic that the fetcher indexes+ // under a hash nothing will ever match. Both prefixes parse, so only the source check+ // separates them.+ const step = createProduceCollectedUrlsStep(outputs, 100)++ await run(step, {+ message: { timestamp: CAPTURED_AT },+ collectedUrls: [+ {+ ref: `image:${PSEUDO_TEAM}:h1xxxxxxxxxxxxxxxxxxxx`,+ url: 'https://img.example.com/a.png',+ host: 'img.example.com',+ domain: 'example.com',+ },+ ],+ })++ expect(queueMessages).not.toHaveBeenCalled()+ })++ it('drops a bytes ref that follows a usable one, and keeps the rest', async () => {+ // A guard that reads only the first entry passes this array and produces the bytes ref.+ const step = createProduceCollectedUrlsStep(outputs, 100)++ await run(step, {+ message: { timestamp: CAPTURED_AT },+ collectedUrls: [+ collected('h1', 'img.example.com', 'https://img.example.com/a.png'),+ {+ ref: `image:${PSEUDO_TEAM}:h2xxxxxxxxxxxxxxxxxxxx`,+ url: 'https://img.example.com/inlined.png',+ host: 'img.example.com',+ domain: 'example.com',+ },+ collected('h3', 'img.example.com', 'https://img.example.com/c.png'),+ ],+ })++ const sent = decode(queued[0])+ expect(sent).toHaveLength(1)+ expect(sent[0].value.urls.map((u: { ref: string }) => u.ref)).toEqual([+ `imageurl:${PSEUDO_TEAM}:h1xxxxxxxxxxxxxxxxxxxx`,+ `imageurl:${PSEUDO_TEAM}:h3xxxxxxxxxxxxxxxxxxxx`,+ ])+ })++ it('drops an entry whose ref names another team', async () => {+ const step = createProduceCollectedUrlsStep(outputs, 100)+ const otherTeam = 'b'.repeat(32)++ await run(step, {+ message: { timestamp: CAPTURED_AT },+ collectedUrls: [+ collected('h1', 'img.example.com', 'https://img.example.com/a.png'),+ {+ ref: `imageurl:${otherTeam}:h2xxxxxxxxxxxxxxxxxxxx`,+ url: 'https://img.example.com/b.png',+ host: 'img.example.com',+ domain: 'img.example.com',+ },+ ],+ })++ const sent = decode(queued[0])+ expect(sent[0].value.pseudoTeam).toBe(PSEUDO_TEAM)+ expect(sent[0].value.urls).toHaveLength(1)+ })++ it('puts a sharded CDN on one key, and keeps each host on its record', async () => {+ // A CDN that shards over numbered subdomains is one operator. Keying by host gave it one+ // budget per subdomain, which is the fragmentation this key exists to prevent. Each entry+ // still carries its own host, because robots.txt and the connection limit are per host.+ const step = createProduceCollectedUrlsStep(outputs, 100)++ await run(step, {+ message: { timestamp: CAPTURED_AT },+ collectedUrls: [+ collected('h1', 'img1.cdn.example.com', 'https://img1.cdn.example.com/a.png', 'example.com'),+ collected('h2', 'img8.cdn.example.com', 'https://img8.cdn.example.com/b.png', 'example.com'),+ collected('h3', 'assets.other.org', 'https://assets.other.org/c.png', 'other.org'),+ ],+ })++ const sent = decode(queued[0])+ expect(sent.map((m) => m.key).sort()).toEqual(['example.com', 'other.org'])+ const shared = sent.find((m) => m.key === 'example.com')!+ expect(shared.value.urls.map((u: { host: string }) => u.host)).toEqual([+ 'img1.cdn.example.com',+ 'img8.cdn.example.com',+ ])+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.tsnew file mode 100644index 000000000000..4e1e7450e25d--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts@@ -0,0 +1,194 @@+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'+import { logger } from '~/common/utils/logger'+import { ok } from '~/ingestion/framework/results'+import { ProcessingStep } from '~/ingestion/framework/steps'+import { SessionRecordingIngesterMetrics } from '~/ingestion/pipelines/sessionreplay/metrics'+import { parseImageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'+import { CollectedUrl } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'+import { ML_IMAGE_FETCH_OUTPUT, MlImageFetchOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'+import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'++/**+ * The same trade as the image lane's cache, at a much lower cost per entry: a record here holds a+ * ref of approximately 60 bytes and no image bytes. A ref that this cache drops before its next+ * sighting produces a second time, which costs topic volume and one more ledger read in the+ * fetcher, but never correctness. The fetcher dedupes on the same ref again.+ */+const PRODUCED_REF_CACHE_MAX = 500_000++/**+ * Records for one host per Kafka message.+ *+ * The Rust collector caps one replay message at 256 URLs of up to 2048 bytes each, which is about+ * 540 KB if they all share one host. That is under librdkafka's 1 MB default, but only just, and+ * the bound lives in another crate. This cap keeps the record size inside this file, where the+ * produce happens.+ */+const MAX_URLS_PER_RECORD = 64++/** One record on the fetch topic. The Kafka key is the registrable domain, so every URL here+ * belongs to one operator. Hosts can differ within it: a CDN sharding over img1..img8 keeps one+ * budget but still needs its own robots.txt and connection limit per host. */+export interface CollectedUrlsMessage {+ /**+ * The wire format version. The fetcher reads this topic from another deployment, so the two+ * sides roll separately and a reader needs to know what it is holding.+ */+ v: 1+ /** The HMAC pseudonym of the team. The raw team id must not go onto this topic. */+ pseudoTeam: string+ /**+ * When capture recorded the replay message these URLs came from, not when the mirror produced+ * them. The fetcher drops a record that is too old, and produce time cannot answer that: a+ * mirror replaying a backlog would stamp hours-old URLs as fresh, which is the one case the+ * age check exists for.+ */+ capturedAtMs: number+ urls: { ref: string; url: string; host: string }[]+}++/**+ * Produce the collected URLs of remote images to the fetch topic, keyed by registrable domain.+ *+ * The URLs of one replay message go into groups by domain, and each group becomes one Kafka+ * message. A Kafka message has one key, so a group holds one domain. A page usually loads its+ * images from one or two operators, so this makes tens of URLs into one or two records.+ *+ * The key is the operator rather than the host, because that is what a rate limit protects. A CDN+ * that shards over img1..img8.cdn.example.com keys to one partition, so one pod holds one budget+ * for it. The anonymizer computes the domain from the public suffix list and sends it with the+ * URL, so this step never repeats that rule.+ *+ * The step does not hold URLs across replay messages. The produce goes back as a pipeline side+ * effect, and the pipeline waits for the side effects of a batch before it commits the offsets of+ * that batch. A buffer that spans messages would break that guarantee, because the pipeline could+ * commit the offset of a message while the URLs of that message were still in the buffer. A crash+ * would then lose them. The group-by-host step already removes most of the record count, `linger.ms`+ * makes the batches on the wire, and the ref cache stops a repeated image before it produces at all.+ *+ * Delivery is not awaited and never fails the message. The mirrored lines already carry the refs,+ * and a ref with no image behind it renders as a placeholder.+ *+ * The `url` field is the original, unscrubbed URL. It is as sensitive as the raw replay payload, so+ * it goes only into the Kafka value. Log lines and metrics carry hosts and counts only.+ */+export function createProduceCollectedUrlsStep<+ T extends { collectedUrls?: CollectedUrl[]; message: { timestamp?: number } },+>(+ outputs: IngestionOutputs<MlImageFetchOutput>,+ producedRefCacheMax: number = PRODUCED_REF_CACHE_MAX+): ProcessingStep<T, T> {+ const producedRefs = new RefDedupCache('image_fetch_producer', producedRefCacheMax)++ return function produceCollectedUrlsStep(input) {+ const collected = input.collectedUrls+ if (!collected?.length) {+ return Promise.resolve(ok(input))+ }++ const fresh = collected.filter((entry) => !producedRefs.has(entry.ref))+ SessionRecordingIngesterMetrics.incrementMlUrlsCollected('deduped', collected.length - fresh.length)+ if (fresh.length === 0) {+ return Promise.resolve(ok({ ...input, collectedUrls: undefined }))+ }++ // Each entry is checked, not just the first. A `bytes` ref names an image the page+ // inlined, and its hash can never be reproduced from a URL, so a record carrying one+ // reaches the fetcher under a hash nothing will ever match. Both kinds parse, so only+ // `source` separates them, and checking one entry would let every later one through.+ //+ // The pseudonym comes back out of the ref, because the ref is the only place the collector+ // puts it. Every entry must agree on it: one replay message belongs to one team, and a+ // record stamped with another team's pseudonym is a tenant-attribution error that nothing+ // downstream can detect.+ const usable: CollectedUrl[] = []+ let pseudoTeam: string | undefined+ for (const entry of fresh) {+ const parsed = parseImageRef(entry.ref)+ if (!parsed || parsed.source !== 'url' || (pseudoTeam && parsed.pseudoTeam !== pseudoTeam)) {+ continue+ }+ pseudoTeam ??= parsed.pseudoTeam+ usable.push(entry)+ }+ const unusable = fresh.length - usable.length+ if (unusable > 0) {+ SessionRecordingIngesterMetrics.incrementMlUrlsCollected('ref_unusable', unusable)+ // Warn, not error: this is per replay message, so an addon-side format drift would+ // otherwise write an error line at full ingest rate for as long as it lasted.+ logger.warn('🌐', 'ml_image_fetch_ref_unusable', { count: unusable })+ }+ if (!pseudoTeam || usable.length === 0) {+ return Promise.resolve(ok({ ...input, collectedUrls: undefined }))+ }++ const byDomain = new Map<string, { ref: string; url: string; host: string }[]>()+ for (const entry of usable) {+ producedRefs.add(entry.ref)+ const group = byDomain.get(entry.domain)+ const record = { ref: entry.ref, url: entry.url, host: entry.host }+ if (group) {+ group.push(record)+ } else {+ byDomain.set(entry.domain, [record])+ }+ }+ SessionRecordingIngesterMetrics.incrementMlUrlsCollected('queued', usable.length)++ // The capture timestamp of the source Kafka record, so the fetcher's age check measures the+ // age of the replay data rather than the age of this produce. librdkafka reports an absent+ // timestamp as -1, which is not nullish, so a plain ?? would ship a negative age.+ const messageTimestamp = input.message.timestamp+ const capturedAtMs = messageTimestamp !== undefined && messageTimestamp > 0 ? messageTimestamp : Date.now()+ const messages = [...byDomain].flatMap(([domain, urls]) =>+ chunk(urls, MAX_URLS_PER_RECORD).map((slice) => ({+ key: domain,+ value: Buffer.from(+ JSON.stringify({+ v: 1,+ pseudoTeam,+ capturedAtMs,+ urls: slice,+ } satisfies CollectedUrlsMessage)+ ),+ }))+ )++ // The failure handler captures only the refs, so that a produce which is not yet delivered+ // does not hold the URL strings alive longer than the messages themselves.+ const refs = usable.map((entry) => entry.ref)+ const produce = outputs+ .queueMessages(ML_IMAGE_FETCH_OUTPUT, messages)+ .then(() => {+ // queueMessages resolves on the delivery acks, so `produced` counts what landed.+ SessionRecordingIngesterMetrics.incrementMlUrlsCollected('produced', refs.length)+ })+ .catch((error) => {+ // A dangling ref renders as a placeholder, so a failed produce is logged and never+ // thrown back into the pipeline. Un-mark the refs: the same image in a later+ // snapshot then produces again, one attempt for each recurrence and no retry loop.+ // A duplicate costs the fetcher one ledger read, because the ledger is keyed by ref.+ for (const ref of refs) {+ producedRefs.delete(ref)+ }+ logger.warn('🌐', 'ml_image_fetch_produce_failed', {+ count: refs.length,+ domains: byDomain.size,+ error: String(error),+ })+ SessionRecordingIngesterMetrics.incrementMlUrlsCollected('produce_failed', refs.length)+ })+ return Promise.resolve(ok({ ...input, collectedUrls: undefined }, [produce]))+ }+}++function chunk<T>(items: T[], size: number): T[][] {+ if (items.length <= size) {+ return [items]+ }+ const out: T[][] = []+ for (let i = 0; i < items.length; i += size) {+ out.push(items.slice(i, i + size))+ }+ return out+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/outputs/producer-registry.ts b/nodejs/src/ingestion/pipelines/sessionreplay/outputs/producer-registry.tsindex 266b717721b6..363eba503b14 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/outputs/producer-registry.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/outputs/producer-registry.ts@@ -4,6 +4,8 @@ import {INGESTION_DOWNSTREAM_PRODUCER_CONFIG_MAP,} from '~/ingestion/common/outputs/producers'import {+ INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER,+ INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_CONFIG_MAP,INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER,INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_CONFIG_MAP,INGESTION_SESSIONREPLAY_PRODUCER,@@ -25,4 +27,8 @@ export function createProducerRegistry(kafkaClientRack: string | undefined) {INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER,INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_CONFIG_MAP)+ .register(+ INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER,+ INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_CONFIG_MAP+ )}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/outputs/registry.ts b/nodejs/src/ingestion/pipelines/sessionreplay/outputs/registry.tsindex 69b7542957ad..2146cfb02b77 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/outputs/registry.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/outputs/registry.ts@@ -8,6 +8,7 @@ import {import { IngestionOutputsBuilder } from '~/common/outputs/ingestion-outputs-builder'import {ML_BLOCK_METADATA_OUTPUT,+ ML_IMAGE_FETCH_OUTPUT,ML_IMAGE_SCRUB_OUTPUT,REPLAY_EVENTS_OUTPUT,SESSION_FEATURES_OUTPUT,@@ -52,4 +53,8 @@ export function createOutputsRegistry() {topicKey: 'INGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_SCRUB_TOPIC',producerKey: 'INGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_SCRUB_PRODUCER',})+ .register(ML_IMAGE_FETCH_OUTPUT, {+ topicKey: 'INGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_FETCH_TOPIC',+ producerKey: 'INGESTION_SESSIONREPLAY_OUTPUT_ML_IMAGE_FETCH_PRODUCER',+ })}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/index.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/index.tsindex f0fa62a83be7..4c3eb0f1c932 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/index.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/index.ts@@ -16,3 +16,11 @@ export type MlBlockMetadataOutput = typeof ML_BLOCK_METADATA_OUTPUT// only the mirror deployment produces to it.export const ML_IMAGE_SCRUB_OUTPUT = 'ml_image_scrub' as constexport type MlImageScrubOutput = typeof ML_IMAGE_SCRUB_OUTPUT++// Original URLs of remote images for the fetch lane (key = registrable domain); only the mirror+// deployment produces to it. The key is the domain and not the ref, because the fetcher controls+// its request rate for each operator. One pod must own one operator to do that without a+// distributed lock. A record carries the host of each URL, because robots.txt and the connection+// limit are scoped to the host.+export const ML_IMAGE_FETCH_OUTPUT = 'ml_image_fetch' as const+export type MlImageFetchOutput = typeof ML_IMAGE_FETCH_OUTPUTdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.tsindex e21178bd5a57..81736a4fd8c9 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts@@ -38,11 +38,13 @@ export type KafkaSessionreplayProducerEnvConfig = Record<(typeof INGESTION_SESSIONREPLAY_PRODUCER_CONFIG_MAP)[keyof typeof INGESTION_SESSIONREPLAY_PRODUCER_CONFIG_MAP],string> &- KafkaMlImageScrubProducerEnvConfig+ KafkaMlImageScrubProducerEnvConfig &+ KafkaMlImageFetchProducerEnvConfigexport function getDefaultKafkaSessionreplayProducerEnvConfig(): KafkaSessionreplayProducerEnvConfig {return {...getDefaultKafkaMlImageScrubProducerEnvConfig(),+ ...getDefaultKafkaMlImageFetchProducerEnvConfig(),KAFKA_INGESTION_SESSIONREPLAY_PRODUCER_CLIENT_ID: '',KAFKA_INGESTION_SESSIONREPLAY_PRODUCER_METADATA_BROKER_LIST: '',KAFKA_INGESTION_SESSIONREPLAY_PRODUCER_SECURITY_PROTOCOL: '',@@ -115,3 +117,53 @@ export function getDefaultKafkaMlImageScrubProducerEnvConfig(): KafkaMlImageScruKAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_MESSAGE_TIMEOUT_MS: '20000',}}++/**+ * ML_IMAGE_FETCH producer — the fetch lane's own client instance on the replay cluster.+ *+ * It does not share the ML_IMAGE_SCRUB producer, whose settings are tuned for the opposite payload.+ * That producer sets `compression.codec: none`, which is right for image bytes that are already+ * compressed and wrong for a record of JSON URLs, which compress well. Its queue is also sized in+ * messages for a lane whose records are ~900 KB each, so this lane's much smaller records would+ * share a byte budget shaped for something else, and a scrub-topic backlog would fail URL produces+ * that have nothing to do with it.+ *+ * Broker and security config are shared with the SESSIONREPLAY producer, as on the scrub lane.+ */+export const INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER = 'INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH' as const+export type IngestionSessionreplayMlImageFetchProducer = typeof INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER++export const INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_CONFIG_MAP = {+ 'client.id': 'KAFKA_INGESTION_SESSIONREPLAY_PRODUCER_CLIENT_ID',+ 'metadata.broker.list': 'KAFKA_INGESTION_SESSIONREPLAY_PRODUCER_METADATA_BROKER_LIST',+ 'security.protocol': 'KAFKA_INGESTION_SESSIONREPLAY_PRODUCER_SECURITY_PROTOCOL',+ 'compression.codec': 'KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_COMPRESSION_CODEC',+ 'linger.ms': 'KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_LINGER_MS',+ 'queue.buffering.max.messages':+ 'KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES',+ 'queue.buffering.max.kbytes': 'KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES',+ 'message.timeout.ms': 'KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_MESSAGE_TIMEOUT_MS',+} as const satisfies Partial<Record<AllowedConfigKey, string>>++export type KafkaMlImageFetchProducerEnvConfig = {+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_COMPRESSION_CODEC: string+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_LINGER_MS: string+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES: string+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES: string+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_MESSAGE_TIMEOUT_MS: string+}++export function getDefaultKafkaMlImageFetchProducerEnvConfig(): KafkaMlImageFetchProducerEnvConfig {+ return {+ // JSON URLs compress well, unlike the image bytes on the scrub lane.+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_COMPRESSION_CODEC: 'snappy',+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_LINGER_MS: '',+ // Records here are small, so the queue is sized by count rather than by bytes.+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES: '50000',+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES: '32768',+ // 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.+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_MESSAGE_TIMEOUT_MS: '20000',+ }+}diff --git a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.tsindex dc74fb27c3fe..b4daa90af8c0 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts@@ -176,11 +176,20 @@ export class IngestionSessionReplayMlMirrorServer implements NodeServer {{pseudonymSecret,// Producing the images is what makes collecting them useful, so the image- // lane follows its producer flag. The URL lane has no producer yet and- // measures on its own, so it follows only its own flag.+ // lane follows its producer flag. The URL lane collects on its own flag,+ // because collecting alone measures without sending anything anywhere.collectImages: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED,collectUrls: this.config.SESSION_RECORDING_ML_URL_COLLECTION_ENABLED,- }+ },+ // Producing needs collection: without it the anonymizer returns no URLs, and+ // the step would have nothing to send.+ this.config.SESSION_RECORDING_ML_URL_COLLECTION_ENABLED &&+ this.config.SESSION_RECORDING_ML_URL_PRODUCER_ENABLED+ ? {+ outputs,+ producedRefCacheMax: this.config.SESSION_RECORDING_ML_URL_PRODUCED_REF_CACHE_MAX,+ }+ : undefined),// Isolate the mirror's session tracker/filter keys from the main lane. Sharing them would let// the cleartext mirror mark a session seen without the main lane's KMS key, so the main lane