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): add the image fetch lane in dry run (#81188)

Robbie66c471925b9c
diff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.ts
index e111f14b4cae..22a6b76312d6 100644
--- a/nodejs/src/capabilities.ts
+++ b/nodejs/src/capabilities.ts
@@ -196,6 +196,7 @@ export function getPluginServerCapabilities(
case PluginServerMode.recordings_blob_ingestion_v2_ml_parquet_sink:
case PluginServerMode.recordings_blob_ingestion_v2_ml_image_scrub:
case PluginServerMode.recordings_blob_ingestion_v2_ml_image_scrub_dlq_replay:
+ case PluginServerMode.recordings_blob_ingestion_v2_ml_image_fetch:
case PluginServerMode.recording_api:
throw new Error(`Mode ${mode} is handled by IngestionSessionReplayServer, not PluginServer`)
}
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.ts
index 6994e3521213..018e45a1932b 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -40,6 +40,7 @@ export enum PluginServerMode {
recordings_blob_ingestion_v2_ml_parquet_sink = 'recordings-blob-ingestion-v2-ml-parquet-sink',
recordings_blob_ingestion_v2_ml_image_scrub = 'recordings-blob-ingestion-v2-ml-image-scrub',
recordings_blob_ingestion_v2_ml_image_scrub_dlq_replay = 'recordings-blob-ingestion-v2-ml-image-scrub-dlq-replay',
+ recordings_blob_ingestion_v2_ml_image_fetch = 'recordings-blob-ingestion-v2-ml-image-fetch',
cdp_processed_events = 'cdp-processed-events',
cdp_person_updates = 'cdp-person-updates',
cdp_data_warehouse_events = 'cdp-data-warehouse-events',
diff --git a/nodejs/src/common/utils/db/redis.ts b/nodejs/src/common/utils/db/redis.ts
index 72acf7a65bf7..cfe7b7ce6fd0 100644
--- a/nodejs/src/common/utils/db/redis.ts
+++ b/nodejs/src/common/utils/db/redis.ts
@@ -28,6 +28,13 @@ export interface RedisPoolConfig {
connection: RedisConnectionConfig
poolMinSize: number
poolMaxSize: number
+ /**
+ * Rejects a caller that waits this long for a connection. Prefer this to racing `acquire()`
+ * against your own timer: generic-pool has no cancellation, so a caller that walks away from a
+ * pending `acquire()` is still handed the next free connection and is still counted as
+ * borrowing it. Enough of those and the pool is empty for good.
+ */
+ acquireTimeoutMillis?: number
}
export async function createRedisFromConfig(config: RedisConnectionConfig): Promise<Redis.Redis> {
@@ -46,6 +53,7 @@ export function createRedisPoolFromConfig(config: RedisPoolConfig): RedisPool {
min: config.poolMinSize,
max: config.poolMaxSize,
autostart: true,
+ ...(config.acquireTimeoutMillis !== undefined ? { acquireTimeoutMillis: config.acquireTimeoutMillis } : {}),
}
)
}
diff --git a/nodejs/src/index.ts b/nodejs/src/index.ts
index d43e010d9329..3d6b14ae19a8 100644
--- a/nodejs/src/index.ts
+++ b/nodejs/src/index.ts
@@ -12,6 +12,7 @@ import { IngestionApiServer } from '~/servers/ingestion-api-server'
import { IngestionGeneralServer } from '~/servers/ingestion-general-server'
import { IngestionLogsServer } from '~/servers/ingestion-logs-server'
import { IngestionMetricsServer } from '~/servers/ingestion-metrics-server'
+import { IngestionSessionReplayMlImageFetchServer } from '~/servers/ingestion-session-replay-ml-image-fetch-server'
import { IngestionSessionReplayMlImageScrubDlqReplayServer } from '~/servers/ingestion-session-replay-ml-image-scrub-dlq-replay-server'
import { IngestionSessionReplayMlImageScrubServer } from '~/servers/ingestion-session-replay-ml-image-scrub-server'
import { IngestionSessionReplayMlMirrorServer } from '~/servers/ingestion-session-replay-ml-mirror-server'
@@ -48,6 +49,9 @@ function createServer(): NodeServer {
case PluginServerMode.recordings_blob_ingestion_v2_ml_image_scrub_dlq_replay:
return new IngestionSessionReplayMlImageScrubDlqReplayServer()
+ case PluginServerMode.recordings_blob_ingestion_v2_ml_image_fetch:
+ return new IngestionSessionReplayMlImageFetchServer()
+
case PluginServerMode.recording_api:
return new RecordingApiServer()
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.ts
new file mode 100644
index 000000000000..34465017b2b0
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.ts
@@ -0,0 +1,31 @@
+import { parseCollectedUrlsRecord } from './collected-urls-record'
+
+const TEAM = '0123456789abcdef0123456789abcdef'
+const HASH = 'a'.padEnd(22, '0')
+
+function body(fields: string): Buffer {
+ return Buffer.from(
+ `{"v":1,"pseudoTeam":"${TEAM}",${fields},` +
+ `"urls":[{"ref":"imageurl:${TEAM}:${HASH}","url":"https://cdn.example.com/a.png","host":"cdn.example.com"}]}`
+ )
+}
+
+describe('parseCollectedUrlsRecord', () => {
+ it.each([
+ ['a magnitude no double can hold', '"capturedAtMs":-1e400'],
+ ['a positive one', '"capturedAtMs":1e400'],
+ ])('refuses %s rather than passing a non-finite timestamp on', (_name, fields) => {
+ // JSON.stringify cannot produce these, so the record is written by hand. They parse to
+ // Infinity, which reaches a histogram as an infinite observation, and prom-client throws
+ // there. A throw inside a batch stops the consumer and replays the same record forever.
+ const parsed = parseCollectedUrlsRecord(body(fields), 'example.com')
+
+ expect(parsed).toEqual({ ok: false, reason: 'malformed' })
+ })
+
+ it('accepts an ordinary timestamp', () => {
+ const parsed = parseCollectedUrlsRecord(body('"capturedAtMs":1700000000000'), 'example.com')
+
+ expect(parsed.ok).toBe(true)
+ })
+})
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
new file mode 100644
index 000000000000..87a5760b7c2a
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts
@@ -0,0 +1,132 @@
+import { parseJSON } from '~/common/utils/json-parse'
+import { parseImageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'
+
+import { UrlDropReason } from './metrics'
+
+/** Beyond this the URL is not something the mirror produced, so it is a format disagreement. */
+const MAX_URL_LENGTH = 2048
+
+const FETCHABLE_SCHEMES = new Set(['http:', 'https:'])
+
+/**
+ * The producer splits a record at 64 URLs. A record above this came from a producer that does not
+ * agree with this one, and its size drives a Redis pipeline and a batch's memory, so it is refused
+ * rather than trusted.
+ */
+const MAX_URLS_PER_RECORD = 128
+
+export interface FetchCandidate {
+ ref: string
+ urlHash: string
+ url: string
+ host: string
+ domain: string
+ pseudoTeam: string
+ capturedAtMs: number
+}
+
+export type RecordParse =
+ | { ok: true; candidates: FetchCandidate[]; urlCount: number; rejected: { reason: UrlDropReason }[] }
+ | { ok: false; reason: Extract<UrlDropReason, 'malformed' | 'unsupported_version' | 'oversized_record'> }
+
+function isStringRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+/**
+ * Read one record off the fetch topic.
+ *
+ * The producer and this consumer ship from separate deployments, so a record can arrive from a
+ * mirror older or newer than this code. Every field is therefore checked rather than trusted, and a
+ * record that does not parse is counted and dropped instead of throwing: one bad record must not
+ * stall the partition it shares with every other site.
+ *
+ * `domain` comes from the Kafka key rather than the record body, because the key is what routed the
+ * record to this partition and so is what the politeness budget must be scoped to.
+ */
+export function parseCollectedUrlsRecord(value: Buffer | null, key: string | null): RecordParse {
+ if (!value || !key) {
+ return { ok: false, reason: 'malformed' }
+ }
+ let parsed: unknown
+ try {
+ parsed = parseJSON(value.toString())
+ } catch {
+ return { ok: false, reason: 'malformed' }
+ }
+ if (!isStringRecord(parsed)) {
+ return { ok: false, reason: 'malformed' }
+ }
+ if (parsed.v !== 1) {
+ return { ok: false, reason: 'unsupported_version' }
+ }
+ const { pseudoTeam, capturedAtMs, urls } = parsed
+ if (typeof pseudoTeam !== 'string' || !pseudoTeam || typeof capturedAtMs !== 'number' || !Array.isArray(urls)) {
+ return { ok: false, reason: 'malformed' }
+ }
+ // Finite, not merely a number: JSON carries `-1e400`, which parses to -Infinity and would reach
+ // a histogram as an infinite age. prom-client throws on that, and a throw here stops the
+ // consumer and replays the same record forever.
+ if (!Number.isFinite(capturedAtMs)) {
+ return { ok: false, reason: 'malformed' }
+ }
+ if (urls.length > MAX_URLS_PER_RECORD) {
+ return { ok: false, reason: 'oversized_record' }
+ }
+
+ const candidates: FetchCandidate[] = []
+ const rejected: { reason: UrlDropReason }[] = []
+ for (const entry of urls) {
+ if (!isStringRecord(entry) || typeof entry.ref !== 'string' || typeof entry.url !== 'string') {
+ rejected.push({ reason: 'bad_ref' })
+ continue
+ }
+ const ref = parseImageRef(entry.ref)
+ if (!ref || ref.source !== 'url' || ref.pseudoTeam !== pseudoTeam) {
+ rejected.push({ reason: 'bad_ref' })
+ continue
+ }
+ const host = typeof entry.host === 'string' ? entry.host : ''
+ if (!isFetchableUrl(entry.url, host)) {
+ rejected.push({ reason: 'bad_url' })
+ continue
+ }
+ // The key is what the per-site budget is scoped to, so a host outside it would be rate
+ // limited against another site's allowance.
+ if (!hostBelongsToDomain(host, key)) {
+ rejected.push({ reason: 'foreign_domain' })
+ continue
+ }
+ candidates.push({
+ ref: entry.ref,
+ urlHash: ref.hash,
+ url: entry.url,
+ host,
+ domain: key,
+ pseudoTeam,
+ capturedAtMs,
+ })
+ }
+ return { ok: true, candidates, urlCount: urls.length, rejected }
+}
+
+function hostBelongsToDomain(host: string, domain: string): boolean {
+ return host === domain || host.endsWith(`.${domain}`)
+}
+
+/**
+ * The mirror already applied the full URL policy before producing, so this repeats only the checks
+ * that a wrong or stale producer could get past. It is not the SSRF gate: that belongs immediately
+ * before a request goes out, against the host of every redirect, and no request goes out here.
+ */
+function isFetchableUrl(url: string, host: string): boolean {
+ if (url.length > MAX_URL_LENGTH || !host) {
+ return false
+ }
+ try {
+ const parsed = new URL(url)
+ return FETCHABLE_SCHEMES.has(parsed.protocol) && parsed.hostname === host
+ } catch {
+ return false
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts
new file mode 100644
index 000000000000..cd3adbb73d46
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts
@@ -0,0 +1,114 @@
+import { Counter, Gauge, Histogram } from 'prom-client'
+
+export type UrlDropReason =
+ | 'malformed'
+ | 'unsupported_version'
+ | 'stale'
+ | 'bad_ref'
+ | 'bad_url'
+ | 'foreign_domain'
+ | 'oversized_record'
+
+export type DedupScope = 'batch' | 'pod' | 'store'
+
+export class ImageFetchConsumerMetrics {
+ /**
+ * URLs that reached the end of the dry run, meaning the lane would have sent a request for them.
+ *
+ * This is the phase 0 headline. Divided by the window it gives the request rate the fetcher would
+ * offer, which is the number that decides whether the politeness budget of section 4.5 can carry
+ * real traffic.
+ */
+ private static readonly fetchable = new Counter({
+ name: 'ml_image_fetch_consumer_fetchable_total',
+ help: 'URLs that passed every check and would have been fetched. In dry run no request is sent, so this is the offered rate rather than the sent rate',
+ })
+ /**
+ * Duplicates split by which layer caught them.
+ *
+ * The split is the measurement, not the total. `batch` and `pod` are free and bounded by memory,
+ * `store` costs a Redis read, and anything the store catches that the pod cache did not is what
+ * the shared store is buying. A high `store` share against a full pod cache says the cache is
+ * undersized; a low one says it is already holding the working set.
+ */
+ private static readonly deduped = new Counter({
+ name: 'ml_image_fetch_consumer_deduped_total',
+ help: 'URLs skipped as already known, by the layer that caught them: "batch" (another copy in the same poll batch), "pod" (this pod saw it earlier), "store" (another pod saw it, or this pod before a restart)',
+ labelNames: ['scope'],
+ })
+ /**
+ * URLs the lane refused before any dedup decision.
+ *
+ * `stale` is the expected one under a backlog and is working as designed. The others mean the
+ * producer and this consumer disagree about the wire format, so a sustained rate on any of them
+ * zeroes the lane while looking healthy from the Kafka side.
+ */
+ private static readonly dropped = new Counter({
+ name: 'ml_image_fetch_consumer_dropped_total',
+ help: 'URLs refused before dedup, by reason: "stale" (older than the age limit), "malformed" / "unsupported_version" / "oversized_record" (the record did not parse), "bad_ref" / "bad_url" (an entry inside a record did not parse), "foreign_domain" (the host sits outside the domain the record is keyed by)',
+ labelNames: ['reason'],
+ })
+ /**
+ * Distinct registrable domains seen per poll batch.
+ *
+ * The topic is keyed by domain, so one partition carries a small number of domains and one pod
+ * holds their whole request rate. A batch spanning many domains means the key is spreading work
+ * more finely than the partition count can express, which is what would let one pod exceed a
+ * single site's budget.
+ */
+ private static readonly domainsPerBatch = new Histogram({
+ name: 'ml_image_fetch_consumer_domains_per_batch',
+ help: 'Distinct registrable domains in one poll batch. The politeness budget is per domain and held by the pod owning the partition, so this bounds how many budgets one pod runs at once',
+ buckets: [1, 2, 4, 8, 16, 32, 64],
+ })
+ private static readonly urlsPerRecord = new Histogram({
+ name: 'ml_image_fetch_consumer_urls_per_record',
+ help: 'URLs carried by one Kafka record. The producer caps this, so a distribution pinned at the cap means records are being split and the cap is the binding constraint',
+ buckets: [1, 2, 4, 8, 16, 32, 64],
+ })
+ private static readonly storeErrors = new Counter({
+ name: 'ml_image_fetch_consumer_store_errors_total',
+ help: 'Sighting-store keys that failed, by operation. A failed read makes the lane treat a known URL as new, so the measured hit rate understates the real one. A failed write leaves the URL unrecorded, so the next pod to see it counts it again',
+ labelNames: ['operation'],
+ })
+ private static readonly batchDuration = new Histogram({
+ name: 'ml_image_fetch_consumer_batch_duration_seconds',
+ help: 'Wall time per poll batch. Read against CONSUMER_MAX_HEARTBEAT_INTERVAL_MS (30s), which binds long before max.poll.interval.ms: the batch refreshes the heartbeat from inside itself, so a batch past this means that refresh stopped',
+ buckets: [0.01, 0.05, 0.1, 0.5, 1, 5, 15, 30, 60],
+ })
+ private static readonly ageSeconds = new Histogram({
+ name: 'ml_image_fetch_consumer_url_age_seconds',
+ help: 'Age of a URL when this lane reached it, measured from capture rather than from produce. The tail against the configured age limit says how much of a backlog would be dropped rather than fetched',
+ buckets: [1, 10, 60, 300, 900, 3600, 6 * 3600, 24 * 3600],
+ })
+ private static readonly dryRun = new Gauge({
+ name: 'ml_image_fetch_consumer_dry_run',
+ help: '1 while the lane sends no outbound request, 0 once fetching is enabled. Every other metric of this lane means something different either side of this value',
+ })
+
+ public static setDryRun(enabled: boolean): void {
+ this.dryRun.set(enabled ? 1 : 0)
+ }
+ public static incFetchable(count: number): void {
+ this.fetchable.inc(count)
+ }
+ public static incDeduped(scope: DedupScope, count: number): void {
+ this.deduped.labels(scope).inc(count)
+ }
+ public static incDropped(reason: UrlDropReason, count: number): void {
+ this.dropped.labels(reason).inc(count)
+ }
+ public static incStoreError(operation: 'read' | 'write', count: number): void {
+ this.storeErrors.labels(operation).inc(count)
+ }
+ public static observeBatch(domains: number, durationSeconds: number): void {
+ this.domainsPerBatch.observe(domains)
+ this.batchDuration.observe(durationSeconds)
+ }
+ public static observeRecord(urls: number): void {
+ this.urlsPerRecord.observe(urls)
+ }
+ public static observeAge(ageSeconds: number): void {
+ this.ageSeconds.observe(ageSeconds)
+ }
+}
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
new file mode 100644
index 000000000000..15536ac842b3
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts
@@ -0,0 +1,222 @@
+import { Message } from 'node-rdkafka'
+
+import { UrlFetchConsumer } from './url-fetch-consumer'
+import { SightingStore, sightingKey } from './url-sightings'
+
+const TEAM = '0123456789abcdef0123456789abcdef'
+const OTHER_TEAM = 'fedcba9876543210fedcba9876543210'
+const NOW = 1_700_000_000_000
+
+/** The ref format fixes the hash at 22 base64url characters, so a short test name has to be padded. */
+const hash = (name: string): string => name.padEnd(22, '0')
+
+function ref(name: string, team: string = TEAM): string {
+ return `imageurl:${team}:${hash(name)}`
+}
+
+class FakeSightings implements SightingStore {
+ public readonly stored = new Map<string, number>()
+ public readFailure: Error | null = null
+ public writeFailure: Error | null = null
+ /** Keys whose individual write reports a per-command failure, as ioredis does inside a pipeline. */
+ public partialWriteFailures = new Set<string>()
+ public reads = 0
+
+ read(keys: string[]): Promise<{ known: Set<number>; failed: number }> {
+ this.reads++
+ if (this.readFailure) {
+ return Promise.reject(this.readFailure)
+ }
+ const known = new Set<number>()
+ keys.forEach((key, index) => {
+ if (this.stored.has(key)) {
+ known.add(index)
+ }
+ })
+ return Promise.resolve({ known, failed: 0 })
+ }
+
+ record(keys: string[], nowMs: number): Promise<{ failed: Set<number> }> {
+ if (this.writeFailure) {
+ return Promise.reject(this.writeFailure)
+ }
+ const failed = new Set<number>()
+ keys.forEach((key, index) => {
+ if (this.partialWriteFailures.has(key)) {
+ failed.add(index)
+ return
+ }
+ this.stored.set(key, nowMs)
+ })
+ return Promise.resolve({ failed })
+ }
+}
+
+/** A real Message, so a field the consumer starts reading cannot be missing without the type saying so. */
+function message(value: Buffer | null, key: string | null): Message {
+ return {
+ value,
+ key: key === null ? null : Buffer.from(key),
+ size: value?.length ?? 0,
+ topic: 'session_replay_image_fetch',
+ partition: 0,
+ offset: 0,
+ }
+}
+
+function record(
+ urls: { ref: string; url: string; host: string }[],
+ overrides: { v?: unknown; pseudoTeam?: string; capturedAtMs?: number; key?: string | null } = {}
+): Message {
+ const body = {
+ v: overrides.v ?? 1,
+ pseudoTeam: overrides.pseudoTeam ?? TEAM,
+ capturedAtMs: overrides.capturedAtMs ?? NOW,
+ urls,
+ }
+ return message(Buffer.from(JSON.stringify(body)), overrides.key === null ? null : (overrides.key ?? 'example.com'))
+}
+
+function url(name: string, host = 'cdn.example.com'): { ref: string; url: string; host: string } {
+ return { ref: ref(name), url: `https://${host}/${name}.png`, host }
+}
+
+describe('UrlFetchConsumer', () => {
+ let sightings: FakeSightings
+ let consumer: UrlFetchConsumer
+
+ const build = (dedupMaxRefs = 1000): UrlFetchConsumer =>
+ new UrlFetchConsumer(sightings, {
+ maxAgeMs: 6 * 60 * 60 * 1000,
+ dedupMaxRefs,
+ dryRun: true,
+ })
+
+ beforeEach(() => {
+ sightings = new FakeSightings()
+ consumer = build()
+ })
+
+ const hashOf = (key: string): string => key.split(':').pop() as string
+
+ it.each([NaN, 0, -1])('refuses to start with an age limit of %p', (maxAgeMs) => {
+ // The knob arrives from env, where a typo parses to NaN. A NaN limit makes every comparison
+ // false, so the lane silently stops shedding a backlog instead of failing.
+ expect(() => new UrlFetchConsumer(sightings, { maxAgeMs, dedupMaxRefs: 10, dryRun: true })).toThrow(
+ 'SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS'
+ )
+ })
+
+ it('writes one ledger entry per URL it would fetch', async () => {
+ await consumer.handleBatch([record([url('a'), url('b')])], NOW)
+
+ expect([...sightings.stored.keys()].map(hashOf).sort()).toEqual([hash('a'), hash('b')])
+ })
+
+ it('does not re-record a URL another pod already reached', async () => {
+ sightings.stored.set(sightingKey(TEAM, hash('a')), NOW - 1000)
+
+ await consumer.handleBatch([record([url('a'), url('b')])], NOW)
+
+ // 'a' keeps the earlier entry rather than being counted and written again, which is what
+ // makes the ledger measure the hit rate instead of the sighting rate.
+ expect(sightings.stored.get(sightingKey(TEAM, hash('a')))).toBe(NOW - 1000)
+ expect(sightings.stored.get(sightingKey(TEAM, hash('b')))).toBe(NOW)
+ })
+
+ it('collapses a repeated URL inside one batch into a single ledger write', async () => {
+ await consumer.handleBatch([record([url('a')]), record([url('a')]), record([url('a')])], NOW)
+
+ expect([...sightings.stored.keys()]).toEqual([sightingKey(TEAM, hash('a'))])
+ })
+
+ it('does not consult the store for a URL this pod already handled', async () => {
+ await consumer.handleBatch([record([url('a')])], NOW)
+ const readsAfterFirst = sightings.reads
+
+ await consumer.handleBatch([record([url('a')])], NOW)
+
+ expect(sightings.reads).toBe(readsAfterFirst)
+ })
+
+ it('drops a URL older than the age limit without recording it', async () => {
+ const sevenHoursAgo = NOW - 7 * 60 * 60 * 1000
+
+ await consumer.handleBatch([record([url('a')], { capturedAtMs: sevenHoursAgo })], NOW)
+
+ expect(sightings.stored.size).toBe(0)
+ })
+
+ it.each([
+ ['an unsupported version', record([url('a')], { v: 2 })],
+ ['a missing kafka key', record([url('a')], { key: null })],
+ ['a body that is not json', message(Buffer.from('{oh no'), 'example.com')],
+ ['an empty value', message(null, 'example.com')],
+ ])('drops %s without throwing', async (_name, message) => {
+ await expect(consumer.handleBatch([message], NOW)).resolves.toBeUndefined()
+
+ expect(sightings.stored.size).toBe(0)
+ })
+
+ it.each([
+ [
+ 'a ref belonging to another team',
+ { ref: ref('a', OTHER_TEAM), url: 'https://cdn.example.com/a.png', host: 'cdn.example.com' },
+ ],
+ [
+ 'a bytes ref rather than a url ref',
+ { ref: `image:${TEAM}:${hash('a')}`, url: 'https://cdn.example.com/a.png', host: 'cdn.example.com' },
+ ],
+ [
+ 'a url whose host contradicts the entry',
+ { ref: ref('a'), url: 'https://evil.example.net/a.png', host: 'cdn.example.com' },
+ ],
+ ['a scheme we never fetch', { ref: ref('a'), url: 'ftp://cdn.example.com/a.png', host: 'cdn.example.com' }],
+ ])('rejects %s while keeping the rest of the record', async (_name, bad) => {
+ await consumer.handleBatch([record([bad as ReturnType<typeof url>, url('good')])], NOW)
+
+ expect([...sightings.stored.keys()].map(hashOf)).toEqual([hash('good')])
+ })
+
+ it('does not mark the pod cache for a URL whose write failed', async () => {
+ sightings.partialWriteFailures.add(sightingKey(TEAM, hash('a')))
+
+ await consumer.handleBatch([record([url('a')])], NOW)
+ const readsAfterFirst = sightings.reads
+ await consumer.handleBatch([record([url('a')])], NOW)
+
+ // The URL is in no durable store, so the next sighting has to reach the store again rather
+ // than be suppressed locally and vanish from the measurement.
+ expect(sightings.reads).toBe(readsAfterFirst + 1)
+ })
+
+ it('rejects a host outside the domain the record is keyed by', async () => {
+ // The key scopes the per-site budget, so a foreign host would spend another site's allowance.
+ await consumer.handleBatch(
+ [record([url('a', 'img.other-site.net'), url('good', 'cdn.example.com')], { key: 'example.com' })],
+ NOW
+ )
+
+ expect([...sightings.stored.keys()].map(hashOf)).toEqual([hash('good')])
+ })
+
+ it('drops a record carrying more URLs than any producer sends', async () => {
+ const many = Array.from({ length: 300 }, (_value, index) => url(`u${index}`))
+
+ await consumer.handleBatch([record(many)], NOW)
+
+ expect(sightings.stored.size).toBe(0)
+ })
+
+ it('treats a URL as unseen when the store read fails, rather than stalling the partition', async () => {
+ sightings.readFailure = new Error('redis down')
+
+ await expect(consumer.handleBatch([record([url('a')])], NOW)).resolves.toBeUndefined()
+ })
+
+ it('survives a store write failure', async () => {
+ sightings.writeFailure = new Error('redis down')
+
+ await expect(consumer.handleBatch([record([url('a')])], NOW)).resolves.toBeUndefined()
+ })
+})
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
new file mode 100644
index 000000000000..3d40236c145d
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts
@@ -0,0 +1,174 @@
+import { Message } from 'node-rdkafka'
+
+import { logger } from '~/common/utils/logger'
+import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'
+
+import { FetchCandidate, parseCollectedUrlsRecord } from './collected-urls-record'
+import { ImageFetchConsumerMetrics, UrlDropReason } from './metrics'
+import { SIGHTING_TTL_SECONDS, SightingStore, sightingKey } from './url-sightings'
+
+export interface UrlFetchConsumerOptions {
+ /** A URL older than this is dropped rather than fetched, so a backlog sheds work instead of downloading stale work. */
+ maxAgeMs: number
+ dedupMaxRefs: number
+ /** While true no request leaves this process. Everything else, including the sighting write, still runs. */
+ dryRun: boolean
+}
+
+/**
+ * The dry run of the image fetch lane.
+ *
+ * It runs every decision the fetcher will make up to the point of sending a request, and stops
+ * there. What survives to the end is counted as `fetchable`, which is the offered request rate that
+ * phase 0 exists to measure, and recorded so the rate phase 1 sees is the rate after dedup rather
+ * than before it.
+ *
+ * A bad record and an unreachable Redis are both handled rather than thrown. This lane shares a
+ * partition with every site whose URLs key to it, and a throw here stops the consumer, replays the
+ * same batch, and holds that partition against all of them.
+ */
+export class UrlFetchConsumer {
+ private readonly seenRefs: RefDedupCache
+
+ constructor(
+ private readonly sightings: SightingStore,
+ private readonly options: UrlFetchConsumerOptions
+ ) {
+ // These arrive from env, where a typo parses to NaN. A NaN age limit makes every comparison
+ // false, which silently disables the shed that lets the lane drop a backlog.
+ if (!Number.isFinite(options.maxAgeMs) || options.maxAgeMs <= 0) {
+ throw new Error(
+ `SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS must be a positive number, got ${options.maxAgeMs}`
+ )
+ }
+ this.seenRefs = new RefDedupCache('image_fetch_consumer', options.dedupMaxRefs)
+ ImageFetchConsumerMetrics.setDryRun(options.dryRun)
+ }
+
+ public async handleBatch(messages: Message[], nowMs: number): Promise<void> {
+ // Wall clock, not the caller's nowMs: nowMs dates the URLs and a test is free to set it far
+ // from the present, which would make the duration meaningless.
+ const startedAt = process.hrtime.bigint()
+ const drops = new Map<UrlDropReason, number>()
+ const countDrop = (reason: UrlDropReason, count = 1): void => {
+ drops.set(reason, (drops.get(reason) ?? 0) + count)
+ }
+
+ const domains = new Set<string>()
+ const seenInBatch = new Set<string>()
+ const candidates: FetchCandidate[] = []
+ let dedupedInBatch = 0
+ let dedupedInPod = 0
+
+ for (const message of messages) {
+ const parsed = parseCollectedUrlsRecord(message.value, message.key?.toString() ?? null)
+ if (!parsed.ok) {
+ countDrop(parsed.reason)
+ continue
+ }
+ ImageFetchConsumerMetrics.observeRecord(parsed.urlCount)
+ for (const { reason } of parsed.rejected) {
+ countDrop(reason)
+ }
+ for (const candidate of parsed.candidates) {
+ domains.add(candidate.domain)
+ if (nowMs - candidate.capturedAtMs > this.options.maxAgeMs) {
+ countDrop('stale')
+ continue
+ }
+ if (seenInBatch.has(candidate.ref)) {
+ dedupedInBatch++
+ continue
+ }
+ seenInBatch.add(candidate.ref)
+ if (this.seenRefs.has(candidate.ref)) {
+ dedupedInPod++
+ continue
+ }
+ // After dedup, so the distribution describes the URLs this lane acts on rather than
+ // being weighted by how often a popular image reappears.
+ ImageFetchConsumerMetrics.observeAge(Math.max(0, nowMs - candidate.capturedAtMs) / 1000)
+ candidates.push(candidate)
+ }
+ }
+
+ const { fetchable, readFailed } = await this.removeAlreadySeen(candidates)
+ if (fetchable.length > 0) {
+ ImageFetchConsumerMetrics.incFetchable(fetchable.length)
+ }
+ // A store that just failed a read gets no writes: the un-deduped write volume is the largest
+ // this lane ever offers, and sending it to a struggling Redis makes it slower still.
+ if (fetchable.length > 0 && !readFailed) {
+ await this.recordSightings(fetchable, nowMs)
+ }
+
+ if (dedupedInBatch > 0) {
+ ImageFetchConsumerMetrics.incDeduped('batch', dedupedInBatch)
+ }
+ if (dedupedInPod > 0) {
+ ImageFetchConsumerMetrics.incDeduped('pod', dedupedInPod)
+ }
+ for (const [reason, count] of drops) {
+ ImageFetchConsumerMetrics.incDropped(reason, count)
+ }
+ ImageFetchConsumerMetrics.observeBatch(domains.size, Number(process.hrtime.bigint() - startedAt) / 1e9)
+ }
+
+ /**
+ * A URL whose read failed comes back as fetchable, which overstates the offered rate. That is
+ * the safe direction while nothing is being sent, and it is not once requests go out, so the
+ * failure is counted rather than only logged.
+ */
+ private async removeAlreadySeen(
+ candidates: FetchCandidate[]
+ ): Promise<{ fetchable: FetchCandidate[]; readFailed: boolean }> {
+ if (candidates.length === 0) {
+ return { fetchable: [], readFailed: false }
+ }
+ const keys = candidates.map((candidate) => sightingKey(candidate.pseudoTeam, candidate.urlHash))
+ let result
+ try {
+ result = await this.sightings.read(keys)
+ } catch (error) {
+ ImageFetchConsumerMetrics.incStoreError('read', keys.length)
+ logger.warn('🌐', 'ml_image_fetch_sighting_read_failed', { count: keys.length, error: String(error) })
+ return { fetchable: candidates, readFailed: true }
+ }
+ if (result.failed > 0) {
+ ImageFetchConsumerMetrics.incStoreError('read', result.failed)
+ }
+ if (result.known.size > 0) {
+ ImageFetchConsumerMetrics.incDeduped('store', result.known.size)
+ }
+ return {
+ fetchable: candidates.filter((_candidate, index) => !result.known.has(index)),
+ readFailed: result.failed > 0,
+ }
+ }
+
+ /**
+ * The pod cache is marked only for a URL whose sighting was stored. A URL held locally but
+ * absent from the shared store is invisible to every other pod and to this one after a restart,
+ * so marking it before the write is confirmed would drop it from the measurement and, later,
+ * from fetching.
+ */
+ private async recordSightings(candidates: FetchCandidate[], nowMs: number): Promise<void> {
+ const keys = candidates.map((candidate) => sightingKey(candidate.pseudoTeam, candidate.urlHash))
+ let failed: Set<number>
+ try {
+ failed = (await this.sightings.record(keys, nowMs, SIGHTING_TTL_SECONDS)).failed
+ } catch (error) {
+ ImageFetchConsumerMetrics.incStoreError('write', keys.length)
+ logger.warn('🌐', 'ml_image_fetch_sighting_write_failed', { count: keys.length, error: String(error) })
+ return
+ }
+ if (failed.size > 0) {
+ ImageFetchConsumerMetrics.incStoreError('write', failed.size)
+ }
+ candidates.forEach((candidate, index) => {
+ if (!failed.has(index)) {
+ this.seenRefs.add(candidate.ref)
+ }
+ })
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-sightings.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-sightings.test.ts
new file mode 100644
index 000000000000..3994c5ef456f
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-sightings.test.ts
@@ -0,0 +1,116 @@
+import { SightingRedis, SightingRedisPool, UrlSightings } from './url-sightings'
+
+/** Above one round trip's key limit, so every test crosses a chunk boundary. */
+const KEYS = Array.from({ length: 600 }, (_value, index) => `k${index}`)
+
+type ExecResult = [Error | null, unknown][] | null
+
+class FakeClient implements SightingRedis {
+ public readonly pipelined: string[] = []
+ constructor(
+ private readonly behavior: {
+ mget?: (keys: string[]) => (string | null)[] | Promise<(string | null)[]>
+ exec?: (keys: string[]) => ExecResult
+ }
+ ) {}
+
+ mget(...keys: string[]): Promise<(string | null)[]> {
+ return Promise.resolve(this.behavior.mget?.(keys) ?? keys.map(() => null))
+ }
+
+ pipeline(): { set: (key: string) => void; exec: () => Promise<ExecResult> } {
+ const keys: string[] = []
+ return {
+ set: (key: string) => {
+ keys.push(key)
+ this.pipelined.push(key)
+ },
+ exec: () =>
+ Promise.resolve(
+ 'exec' in this.behavior ? this.behavior.exec!(keys) : keys.map(() => [null, 'OK'] as [null, string])
+ ),
+ }
+ }
+}
+
+function poolOf(client: FakeClient): SightingRedisPool {
+ return {
+ acquire: () => Promise.resolve(client),
+ release: () => Promise.resolve(),
+ destroy: () => Promise.resolve(),
+ }
+}
+
+describe('UrlSightings', () => {
+ const build = (client: FakeClient, budgetMs = 60_000): UrlSightings =>
+ new UrlSightings(poolOf(client), 1_000, budgetMs)
+
+ it('reports the index of every key that exists, across chunk boundaries', async () => {
+ // The one place a silent mistake is possible: the caller maps these indexes back onto its
+ // own candidate list, so an off-by-one skips the wrong URL and nothing surfaces it.
+ const present = new Set(['k0', 'k255', 'k256', 'k599'])
+ const client = new FakeClient({ mget: (keys) => keys.map((key) => (present.has(key) ? '{}' : null)) })
+
+ const result = await build(client).read(KEYS)
+
+ expect([...result.known].sort((a, b) => a - b)).toEqual([0, 255, 256, 599])
+ expect(result.failed).toBe(0)
+ })
+
+ it('counts a chunk that throws as failed rather than as absent', async () => {
+ const client = new FakeClient({
+ mget: (keys) => {
+ if (keys.includes('k256')) {
+ throw new Error('redis down')
+ }
+ return keys.map(() => null)
+ },
+ })
+
+ const result = await build(client).read(KEYS)
+
+ expect(result.failed).toBe(256)
+ expect(result.known.size).toBe(0)
+ })
+
+ it('reports the index of a single command that failed inside a write pipeline', async () => {
+ const client = new FakeClient({
+ exec: (keys) => keys.map((key) => (key === 'k300' ? [new Error('nope'), null] : [null, 'OK'])),
+ })
+
+ const { failed } = await build(client).record(KEYS, 1, 60)
+
+ expect([...failed]).toEqual([300])
+ })
+
+ it('treats a pipeline that answers with nothing as a whole failed chunk', async () => {
+ const client = new FakeClient({ exec: () => null })
+
+ const { failed } = await build(client).record(KEYS, 1, 60)
+
+ expect(failed.size).toBe(KEYS.length)
+ })
+
+ it('stops issuing round trips once the batch budget is spent', async () => {
+ // A batch that outruns the heartbeat gets the pod restarted onto the same offsets, so the
+ // lane sheds the rest of the work instead.
+ const client = new FakeClient({
+ mget: async (keys) => {
+ await new Promise((resolve) => setTimeout(resolve, 20))
+ return keys.map(() => null)
+ },
+ })
+
+ const result = await build(client, 30).read(KEYS)
+
+ expect(result.failed).toBeGreaterThan(0)
+ })
+
+ it('writes every key exactly once', async () => {
+ const client = new FakeClient({})
+
+ await build(client).record(KEYS, 1, 60)
+
+ expect(client.pipelined).toEqual(KEYS)
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-sightings.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-sightings.ts
new file mode 100644
index 000000000000..7ced023d7069
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-sightings.ts
@@ -0,0 +1,182 @@
+import { Pool } from 'generic-pool'
+
+/**
+ * The dry run records sightings under their own prefix, separate from the fetch results a later
+ * lane will write.
+ *
+ * Two stores rather than one outcome value, because they answer different questions and only one of
+ * them may suppress a request. A sighting says this lane has handled a URL, which is what the phase
+ * 0 dedup measurement counts. It says nothing about bytes, because none were downloaded. Sharing a
+ * keyspace would leave whoever enables fetching with 30 days of entries that look like completed
+ * work, and every URL behind them would be skipped with no error and no metric to show it.
+ */
+const SIGHTING_PREFIX = 'imgfetch:seen'
+
+/**
+ * Long enough that the key count converges on the distinct-URL count of the window, which is the
+ * number that sizes the Redis. Short enough that sightings cannot outlive the phase that wrote them.
+ */
+export const SIGHTING_TTL_SECONDS = 30 * 24 * 60 * 60
+
+/** Bounds one round trip. A poll batch can carry thousands of URLs, and one pipeline holding all of them times out as a unit. */
+const MAX_KEYS_PER_ROUND_TRIP = 256
+
+export function sightingKey(pseudoTeam: string, urlHash: string): string {
+ return `${SIGHTING_PREFIX}:${pseudoTeam}:${urlHash}`
+}
+
+function chunk<T>(items: T[], size: number): T[][] {
+ const out: T[][] = []
+ for (let i = 0; i < items.length; i += size) {
+ out.push(items.slice(i, i + size))
+ }
+ return out
+}
+
+export interface SightingReadResult {
+ /** Indexes of the keys that were already recorded. */
+ known: Set<number>
+ /** Keys whose read did not complete, which the caller must treat as unknown rather than as absent. */
+ failed: number
+}
+
+/**
+ * The two commands this store issues. Narrower than `Redis` so a test supplies exactly these, and a
+ * command added here has to be added to the fake before it compiles.
+ */
+export interface SightingRedis {
+ mget(...keys: string[]): Promise<(string | null)[]>
+ pipeline(): {
+ set(key: string, value: string, expiryMode: 'EX', seconds: number): unknown
+ exec(): Promise<[Error | null, unknown][] | null>
+ }
+}
+
+/** The three pool operations this store uses. Narrow so a test needs no cast to supply them. */
+export type SightingRedisPool = Pick<Pool<SightingRedis>, 'acquire' | 'release' | 'destroy'>
+
+/** What the consumer needs of the store, so its tests exercise the real contract rather than a cast. */
+export interface SightingStore {
+ read(keys: string[]): Promise<SightingReadResult>
+ record(keys: string[], nowMs: number, ttlSeconds: number): Promise<{ failed: Set<number> }>
+}
+
+/**
+ * The record of which image URLs this lane has already reached, shared by every pod.
+ *
+ * The in-memory cache in front of it holds only what one pod saw since it started, so a rebalance
+ * or a restart would otherwise count every URL again. Losing this store costs an overstated
+ * measurement now, and outbound requests once fetching is on. It never costs correctness.
+ *
+ * Both methods stop early once the batch budget is spent and report the rest as failed. A batch that
+ * runs past Kafka's max.poll.interval.ms gets the pod evicted mid-batch, and the partition is then
+ * replayed by a pod that will take just as long, so offered load rises while throughput falls.
+ */
+export class UrlSightings implements SightingStore {
+ constructor(
+ private readonly pool: SightingRedisPool,
+ private readonly commandTimeoutMs: number,
+ private readonly batchBudgetMs: number
+ ) {}
+
+ public async read(keys: string[]): Promise<SightingReadResult> {
+ const known = new Set<number>()
+ let failed = 0
+ await this.forEachChunk(keys, {
+ onChunk: async (client, batch, base) => {
+ const values = await client.mget(...batch)
+ values.forEach((value, index) => {
+ if (value !== null) {
+ known.add(base + index)
+ }
+ })
+ },
+ onChunkFailed: (batch) => {
+ failed += batch.length
+ },
+ })
+ return { known, failed }
+ }
+
+ public async record(keys: string[], nowMs: number, ttlSeconds: number): Promise<{ failed: Set<number> }> {
+ const failed = new Set<number>()
+ const value = JSON.stringify({ seenAtMs: nowMs })
+ await this.forEachChunk(keys, {
+ onChunk: async (client, batch, base) => {
+ const pipeline = client.pipeline()
+ for (const key of batch) {
+ // One command, so a key can never be left without its expiry. A separate EXPIRE
+ // can be the command that fails, and the key it leaves behind is never reclaimed.
+ pipeline.set(key, value, 'EX', ttlSeconds)
+ }
+ const results = (await pipeline.exec()) as [Error | null, unknown][] | null
+ batch.forEach((_key, index) => {
+ const result = results?.[index]
+ if (!result || result[0]) {
+ failed.add(base + index)
+ }
+ })
+ },
+ onChunkFailed: (batch, base) => {
+ batch.forEach((_key, index) => failed.add(base + index))
+ },
+ })
+ return { failed }
+ }
+
+ private async forEachChunk(
+ keys: string[],
+ handlers: {
+ onChunk: (client: SightingRedis, batch: string[], base: number) => Promise<void>
+ onChunkFailed: (batch: string[], base: number) => void
+ }
+ ): Promise<void> {
+ const startedAt = process.hrtime.bigint()
+ const spentMs = (): number => Number(process.hrtime.bigint() - startedAt) / 1e6
+ let base = 0
+ for (const batch of chunk(keys, MAX_KEYS_PER_ROUND_TRIP)) {
+ const at = base
+ base += batch.length
+ if (spentMs() > this.batchBudgetMs) {
+ handlers.onChunkFailed(batch, at)
+ continue
+ }
+ try {
+ await this.withClient((client) => handlers.onChunk(client, batch, at))
+ } catch {
+ handlers.onChunkFailed(batch, at)
+ }
+ }
+ }
+
+ /**
+ * The pool rejects rather than queues once its own acquire timeout passes, so this never races
+ * `acquire()`. generic-pool cannot cancel one, and a caller that walked away from a pending
+ * acquire is still handed the next free connection and still counted as borrowing it.
+ *
+ * A connection whose command was abandoned is destroyed rather than returned, because its reply
+ * is still in flight and would be read as the answer to whichever command borrowed it next.
+ */
+ private async withClient(run: (client: SightingRedis) => Promise<void>): Promise<void> {
+ const client = await this.pool.acquire()
+ let timer: NodeJS.Timeout | undefined
+ try {
+ await Promise.race([
+ run(client),
+ new Promise<never>((_resolve, reject) => {
+ timer = setTimeout(
+ () => reject(new Error('sighting store command timed out')),
+ this.commandTimeoutMs
+ )
+ timer.unref()
+ }),
+ ])
+ } catch (error) {
+ await this.pool.destroy(client).catch(() => undefined)
+ throw error
+ } finally {
+ clearTimeout(timer)
+ }
+ await this.pool.release(client)
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
index 8841dc9be461..6d00d5858613 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
@@ -69,6 +69,24 @@ export type MlMirrorConfig = {
*/
SESSION_RECORDING_ML_URL_PRODUCER_ENABLED: boolean
+ /**
+ * While true the fetch lane sends no outbound request. It reads the topic, dedupes, writes the
+ * ledger and reports the metrics, which is the phase 0 measurement: how many requests the
+ * fetcher would offer, and how many of those dedup away before one is needed.
+ *
+ * Turning it off makes this deployment send requests to customer sites, so it stays on until
+ * those numbers have been read and the per-site budget has been sized against them.
+ */
+ SESSION_RECORDING_ML_IMAGE_FETCH_DRY_RUN: boolean
+ SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID: string
+ SESSION_RECORDING_ML_IMAGE_FETCH_BATCH_SIZE: number
+ /** A URL older than this is dropped, so a lane with a backlog sheds work rather than fetching stale work. */
+ SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS: number
+ /** Capacity of the per-pod seen-ref cache that sits in front of the Redis ledger. */
+ SESSION_RECORDING_ML_IMAGE_FETCH_DEDUP_MAX_REFS: number
+ /** Bounds one round trip to the sighting store, including waiting for a pooled connection, so a Redis stall cannot hold the poll loop. */
+ SESSION_RECORDING_ML_IMAGE_FETCH_REDIS_TIMEOUT_MS: number
+
/**
* 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
@@ -144,6 +162,12 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {
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_IMAGE_FETCH_DRY_RUN: true,
+ SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID: 'session-replay-ml-image-fetch',
+ SESSION_RECORDING_ML_IMAGE_FETCH_BATCH_SIZE: 500,
+ SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS: 6 * 60 * 60 * 1000,
+ SESSION_RECORDING_ML_IMAGE_FETCH_DEDUP_MAX_REFS: 500_000,
+ SESSION_RECORDING_ML_IMAGE_FETCH_REDIS_TIMEOUT_MS: 5_000,
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',
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
new file mode 100644
index 000000000000..e66db4f9c428
--- /dev/null
+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
@@ -0,0 +1,125 @@
+import { initializePrometheusLabels } from '~/common/api/router'
+import { KAFKA_SESSION_REPLAY_IMAGE_FETCH } from '~/common/config/kafka-topics'
+import { KafkaConsumer, KafkaConsumerConfig } from '~/common/kafka/consumer/consumer-v1'
+import { createRedisPoolFromConfig } from '~/common/utils/db/redis'
+import { logger } from '~/common/utils/logger'
+import { UrlFetchConsumer } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer'
+import { UrlSightings } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-sightings'
+import { resolveMlMirrorRedisConnection } from '~/ingestion/pipelines/sessionreplay/ml-mirror/config'
+
+import { RedisPool } from '../types'
+import { CleanupResources, NodeServer, ServerLifecycle } from './base-server'
+import {
+ IngestionSessionReplayMlMirrorServerConfig,
+ buildMlMirrorServerConfig,
+} from './ingestion-session-replay-ml-mirror-server'
+
+// The poll loop only heartbeats between batches, so a slow batch is refreshed from inside it. Must
+// stay under CONSUMER_MAX_HEARTBEAT_INTERVAL_MS (30s), which binds long before max.poll.interval.ms.
+const BATCH_HEARTBEAT_INTERVAL_MS = 10_000
+
+/**
+ * How long the store may spend on one batch, well inside Kafka's max.poll.interval.ms of 300s.
+ *
+ * That is the bound that matters rather than the health check, because the heartbeat above keeps the
+ * health check satisfied through a long batch. A batch that passes the poll interval gets the
+ * partition revoked mid-batch and replayed by a pod that will be just as slow, so the lane sheds the
+ * rest of a batch instead.
+ */
+const STORE_BATCH_BUDGET_MS = 50_000
+
+export function buildImageFetchConsumerConfig(config: IngestionSessionReplayMlMirrorServerConfig): KafkaConsumerConfig {
+ return {
+ topic: KAFKA_SESSION_REPLAY_IMAGE_FETCH,
+ groupId: config.SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID,
+ autoCommit: true,
+ autoOffsetStore: true,
+ fetchBatchSize: config.SESSION_RECORDING_ML_IMAGE_FETCH_BATCH_SIZE,
+ }
+}
+
+/**
+ * The image fetch lane.
+ *
+ * It has its own deployment because it waits on network IO and wants many small pods, where the
+ * scrub sidecar it feeds uses CPU and ML models and wants few large ones.
+ *
+ * The lane starts in dry run and sends no request. See
+ * `SESSION_RECORDING_ML_IMAGE_FETCH_DRY_RUN`.
+ */
+export class IngestionSessionReplayMlImageFetchServer implements NodeServer {
+ readonly lifecycle: ServerLifecycle
+ private config: IngestionSessionReplayMlMirrorServerConfig
+ private sightingPool?: 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)
+
+ // Before anything connects: a cleared flag is a configuration mistake, and this lane has no
+ // request path yet, so it would report itself as fetching while downloading nothing.
+ const dryRun = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_DRY_RUN
+ if (!dryRun) {
+ throw new Error('SESSION_RECORDING_ML_IMAGE_FETCH_DRY_RUN cannot be cleared yet: this lane cannot fetch')
+ }
+
+ // The ml-mirror's instance, which is deliberately not the cluster that serves the primary
+ // replay lane: this store holds one key per distinct image URL, and its eviction pressure
+ // must not be able to reach the lane that gates replay ingestion.
+ const connection = resolveMlMirrorRedisConnection(this.config)
+ if (!connection) {
+ throw new Error('SESSION_RECORDING_ML_REDIS_HOST must be set for the image-fetch consumer')
+ }
+ const redisTimeoutMs = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_REDIS_TIMEOUT_MS
+ this.sightingPool = createRedisPoolFromConfig({
+ // The lane's own command timeout, not the mirror's 200ms: one round trip here carries a
+ // whole chunk of keys rather than a single per-session command.
+ connection: { ...connection, options: { ...connection.options, commandTimeout: redisTimeoutMs } },
+ poolMinSize: this.config.REDIS_POOL_MIN_SIZE,
+ poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,
+ acquireTimeoutMillis: redisTimeoutMs,
+ })
+ const sightings = new UrlSightings(this.sightingPool, redisTimeoutMs, STORE_BATCH_BUDGET_MS)
+
+ const fetchConsumer = new UrlFetchConsumer(sightings, {
+ maxAgeMs: this.config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS,
+ dedupMaxRefs: this.config.SESSION_RECORDING_ML_IMAGE_FETCH_DEDUP_MAX_REFS,
+ dryRun,
+ })
+ logger.info('🌐', 'ml_image_fetch_started', { dryRun })
+
+ const consumer = new KafkaConsumer(buildImageFetchConsumerConfig(this.config))
+ await consumer.connect((messages) => {
+ const heartbeat = setInterval(() => consumer.heartbeat(), BATCH_HEARTBEAT_INTERVAL_MS)
+ return fetchConsumer.handleBatch(messages, Date.now()).finally(() => clearInterval(heartbeat))
+ })
+
+ this.lifecycle.services.push({
+ id: 'session-replay-ml-image-fetch',
+ onShutdown: () => consumer.disconnect(),
+ healthcheck: () => consumer.isHealthy(),
+ })
+ }
+
+ private getCleanupResources(): CleanupResources {
+ return {
+ kafkaProducers: [],
+ redisPools: this.sightingPool ? [this.sightingPool] : [],
+ }
+ }
+}