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(session-replay): filter fetched image URLs before Kafka (#88823)

Robbie25ae404abe65
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
index 56693e84110b..78293b5b3888 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
@@ -15,6 +15,7 @@ export type MlImageLaneStage = 'collected' | 'deduped' | 'queued' | 'produced' |
* 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' | 'ref_unusable'
+export type MlUrlCrawlHistoryOutcome = 'fresh' | 'miss' | 'error'
const URL_BYTES_SAMPLE_RATE = 16
@@ -96,6 +97,19 @@ export class SessionRecordingIngesterMetrics {
labelNames: ['outcome'],
})
+ private static readonly mlUrlCrawlHistory = new Counter({
+ name: 'recording_blob_ingestion_v2_ml_url_crawl_history_total',
+ help: 'URL jobs checked by the mirror before Kafka: fresh jobs are suppressed, misses are produced, and errors fail open',
+ labelNames: ['outcome'],
+ })
+
+ private static readonly mlUrlCrawlHistoryDuration = new Histogram({
+ name: 'recording_blob_ingestion_v2_ml_url_crawl_history_duration_seconds',
+ help: 'Wall time for one mirror crawl-history read by outcome',
+ labelNames: ['outcome'],
+ buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],
+ })
+
private static readonly mlUrlsDeclined = new Counter({
name: 'recording_blob_ingestion_v2_ml_urls_declined',
help: 'Remote image URLs the anonymizer refused to collect, by reason. A decline is invisible in the collected count, so without this the lane looks like traffic carries fewer images than it does',
@@ -207,6 +221,14 @@ export class SessionRecordingIngesterMetrics {
this.mlUrlsCollected.labels(outcome).inc(count)
}
+ public static incrementMlUrlCrawlHistory(outcome: MlUrlCrawlHistoryOutcome, count: number): void {
+ this.mlUrlCrawlHistory.labels(outcome).inc(count)
+ }
+
+ public static observeMlUrlCrawlHistoryDuration(outcome: 'success' | 'error', durationSeconds: number): void {
+ this.mlUrlCrawlHistoryDuration.labels(outcome).observe(durationSeconds)
+ }
+
public static incrementMlUrlsDeclined(reason: string, count: number): void {
if (count > 0) {
this.mlUrlsDeclined.inc({ reason }, count)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
index e5038a153d93..c650e54f0c98 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
@@ -10,6 +10,8 @@ The shared Rust URL policy performs admission, canonicalization, and global ref
The mirror emits versioned frontier jobs. Each job carries the original ref, current URL, remaining hops, timing, and amplification counters.
+The mirror can read crawl history after its local URL cache and before Kafka. It suppresses URLs whose next fetch time is still in the future. A timeout or store error publishes every candidate. The fetch consumer repeats the read because a completion can race with the mirror.
+
Kafka uses the registrable domain as the frontier key. Rate, burst, active-request, transient back-off, and circuit-breaker state use that registrable domain. Policy caches and crawl delay use the full origin.
### Policy and network boundary
@@ -70,7 +72,7 @@ The ML data-preparation resolver reads URL images by global ref. It removes sibl
### Operations
-Metrics cover terminal outcomes, requests, origin policy, registrable-domain request state, retries, amplification, system time, and DynamoDB failures. Every metric label defined by this lane uses a fixed category.
+Metrics cover terminal outcomes, requests, origin policy, registrable-domain request state, retries, amplification, system time, and DynamoDB failures. Mirror metrics separate fresh history, misses, errors, and read duration. Every metric label defined by this lane uses a fixed category.
Batch-diversity histograms record the top 1, 5, and 10 URL shares and the inverse Simpson effective count for origins and registrable domains. Fetch-pass histograms record immediately schedulable slots and their ratio to the pod request limit. These metrics use only fixed scope and top-count labels.
@@ -120,6 +122,7 @@ The pass-budget alert is inactive in dry-run mode. Delay-topic lag has no alert
- The fetch deployment uses Smokescreen without proxy credentials. The lane does not send `Proxy-Authorization`.
- The Web Bot Auth private key and Kubernetes secret remain operator-managed. No private key material belongs in these repositories.
- The DynamoDB table and its workload identity permissions exist before the fetch deployment becomes active.
+- The mirror workload has DynamoDB read permission before deployment.
- The shared ML bucket grants the data-preparation workload read access to the deterministic URL-image prefix.
- Retry topics use the `ai_research_session_replay_` naming convention.
- Replacement infrastructure provisions the required topics before consumers start. No deployed producer or consumer uses the deprecated names.
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
index f0c49b1ccf75..6b5126189d67 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
@@ -69,6 +69,14 @@ export type MlMirrorConfig = {
* the anonymizer collects no URLs until then.
*/
SESSION_RECORDING_ML_URL_PRODUCER_ENABLED: boolean
+ /**
+ * Read crawl history before the mirror sends URLs to Kafka.
+ *
+ * Read failures publish every candidate, so the lookup cannot lose fetch work.
+ */
+ SESSION_RECORDING_ML_URL_CRAWL_HISTORY_PRECHECK_ENABLED: boolean
+ /** Bounds one producer-side crawl-history read. */
+ SESSION_RECORDING_ML_URL_CRAWL_HISTORY_PRECHECK_TIMEOUT_MS: number
// US-only, PEM, multiple keys allowed (comma-separated)
WEB_BOT_AUTH_PRIVATE_KEYS: string
@@ -218,6 +226,8 @@ 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_URL_CRAWL_HISTORY_PRECHECK_ENABLED: true,
+ SESSION_RECORDING_ML_URL_CRAWL_HISTORY_PRECHECK_TIMEOUT_MS: 500,
WEB_BOT_AUTH_PRIVATE_KEYS: '',
SESSION_RECORDING_ML_IMAGE_FETCH_DRY_RUN: true,
SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID: 'session-replay-ml-image-fetch',
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts
index ecb9fb371950..024ce34e708f 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
@@ -14,6 +14,7 @@ import {
SessionReplayPipelineOutput,
} from '~/ingestion/pipelines/sessionreplay'
import { createAiTrainingOptInFilterStep } from '~/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step'
+import type { CrawlHistoryStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history'
import { createProduceCollectedImagesStep } from '~/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step'
import { createProduceCollectedUrlsStep } from '~/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step'
import { createParseAndAnonymizeMessageStep } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'
@@ -44,6 +45,7 @@ export interface MlMirrorUrlFetchProducer {
outputs: IngestionOutputs<MlImageFetchOutput | MlImageScrubOutput>
producedRefCacheMax: number
producedRefCacheWindowMs: number
+ crawlHistory?: Pick<CrawlHistoryStore, 'read'>
}
/**
@@ -190,12 +192,12 @@ export function createMlMirrorReplayPipeline(
: parsed
const withUrlsProduced = urlFetch
? withImagesProduced.pipe(
- createProduceCollectedUrlsStep(
- urlFetch.outputs,
- topHog,
- urlFetch.producedRefCacheMax,
- urlFetch.producedRefCacheWindowMs
- )
+ createProduceCollectedUrlsStep(urlFetch.outputs, topHog, {
+ producedRefCacheMax: urlFetch.producedRefCacheMax,
+ producedRefCacheWindowMs:
+ urlFetch.producedRefCacheWindowMs,
+ crawlHistory: urlFetch.crawlHistory,
+ })
)
: withImagesProduced
return withUrlsProduced.pipe(
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.ts
index 07b0195a5b4a..0e04a255d417 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.ts
@@ -2,6 +2,7 @@ import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { parseJSON } from '~/common/utils/json-parse'
import { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'
import { PipelineResultType } from '~/ingestion/framework/results'
+import type { CrawlHistoryStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history'
import { CollectedUrl } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'
import { MlImageFetchOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
import { RecordedTopHogMetric, createRecordingTopHog } from '~/tests/helpers/tophog'
@@ -132,7 +133,10 @@ describe('produceCollectedUrlsStep', () => {
it('produces an identical transport URL again after the dedup window', async () => {
jest.useFakeTimers().setSystemTime(10_000)
try {
- const step = createProduceCollectedUrlsStep(outputs, topHog, 100, 1_000)
+ const step = createProduceCollectedUrlsStep(outputs, topHog, {
+ producedRefCacheMax: 100,
+ producedRefCacheWindowMs: 1_000,
+ })
const entry = collected('h1', 'cdn.example.com', 'https://cdn.example.com/a.jpg')
await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [entry] })
@@ -163,11 +167,76 @@ describe('produceCollectedUrlsStep', () => {
expect(queueMessages).toHaveBeenCalledTimes(2)
})
+ it('skips fresh crawl history and preserves expired or missing refs', async () => {
+ const nowMs = 1_800_000_000_000
+ jest.useFakeTimers().setSystemTime(nowMs)
+ try {
+ const fresh = collected('h1', 'img.example.com', 'https://img.example.com/fresh.png')
+ const freshReplacement = collected('h1', 'img.example.com', 'https://img.example.com/fresh-v2.png')
+ const expired = collected('h2', 'img.example.com', 'https://img.example.com/expired.png')
+ const missing = collected('h3', 'img.example.com', 'https://img.example.com/missing.png')
+ const read = jest.fn<
+ ReturnType<Pick<CrawlHistoryStore, 'read'>['read']>,
+ Parameters<Pick<CrawlHistoryStore, 'read'>['read']>
+ >()
+ read.mockResolvedValue(
+ new Map([
+ [
+ fresh.ref,
+ {
+ kind: 'url' as const,
+ key: fresh.ref,
+ nextFetchAtMs: nowMs + 1,
+ storageExpiresAtMs: nowMs + 1,
+ outcome: 'ok',
+ },
+ ],
+ [
+ expired.ref,
+ {
+ kind: 'url' as const,
+ key: expired.ref,
+ nextFetchAtMs: nowMs,
+ storageExpiresAtMs: nowMs,
+ outcome: 'ok',
+ },
+ ],
+ ])
+ )
+ const step = createProduceCollectedUrlsStep(outputs, topHog, { crawlHistory: { read } })
+
+ await run(step, {
+ message: { timestamp: CAPTURED_AT },
+ collectedUrls: [fresh, freshReplacement, expired, missing],
+ })
+
+ expect(read).toHaveBeenCalledWith([fresh.ref, expired.ref, missing.ref])
+ expect(decode(queued[0])[0].value.jobs.map((job) => job.originalRef)).toEqual([expired.ref, missing.ref])
+
+ await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [fresh] })
+ expect(read).toHaveBeenCalledTimes(1)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('produces every URL when the crawl-history read fails', async () => {
+ const entry = collected('h1', 'img.example.com', 'https://img.example.com/a.png')
+ const read = jest.fn().mockRejectedValue(new Error('store unavailable'))
+ const step = createProduceCollectedUrlsStep(outputs, topHog, { crawlHistory: { read } })
+
+ const result = await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [entry] })
+
+ expect(result.type).toBe(PipelineResultType.OK)
+ expect(queueMessages).toHaveBeenCalledTimes(1)
+ expect(decode(queued[0])[0].value.jobs.map((job) => job.originalRef)).toEqual([entry.ref])
+ })
+
test.each([
['inline image', `image:${PSEUDO_TEAM}:h1xxxxxxxxxxxxxxxxxxxx`],
['legacy team-scoped URL', `imageurl:${PSEUDO_TEAM}:h1xxxxxxxxxxxxxxxxxxxx`],
])('refuses to produce a %s ref', async (_name, ref) => {
- const step = createProduceCollectedUrlsStep(outputs, topHog, 100)
+ const step = createProduceCollectedUrlsStep(outputs, topHog, { producedRefCacheMax: 100 })
await run(step, {
message: { timestamp: CAPTURED_AT },
@@ -187,7 +256,7 @@ describe('produceCollectedUrlsStep', () => {
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, topHog, 100)
+ const step = createProduceCollectedUrlsStep(outputs, topHog, { producedRefCacheMax: 100 })
await run(step, {
message: { timestamp: CAPTURED_AT },
@@ -215,7 +284,7 @@ describe('produceCollectedUrlsStep', () => {
it('packs many short urls into one record', async () => {
// A fixed count would have cut this into several records and used a fraction of each. The
// budget is bytes, so ordinary URLs pack until the bytes run out.
- const step = createProduceCollectedUrlsStep(outputs, topHog, 100_000)
+ const step = createProduceCollectedUrlsStep(outputs, topHog, { producedRefCacheMax: 100_000 })
const many = Array.from({ length: 400 }, (_v, i) =>
collected(`h${i}`.padEnd(22, 'x'), 'img.example.com', `https://img.example.com/${i}.png`)
)
@@ -228,7 +297,7 @@ describe('produceCollectedUrlsStep', () => {
it('splits on the count bound even when the bytes would fit', async () => {
// The fetcher refuses a record above its own count cap, whole. Byte packing alone would let
// the collector's per-message cap in another crate decide how many entries a record holds.
- const step = createProduceCollectedUrlsStep(outputs, topHog, 100_000)
+ const step = createProduceCollectedUrlsStep(outputs, topHog, { producedRefCacheMax: 100_000 })
const many = Array.from({ length: 1200 }, (_v, i) =>
collected(`h${i}`.padEnd(22, 'x'), 'img.example.com', `https://img.example.com/${i}.png`)
)
@@ -243,7 +312,7 @@ describe('produceCollectedUrlsStep', () => {
})
it('splits when the urls are long enough to fill a record', async () => {
- const step = createProduceCollectedUrlsStep(outputs, topHog, 100_000)
+ const step = createProduceCollectedUrlsStep(outputs, topHog, { producedRefCacheMax: 100_000 })
const long = 'x'.repeat(2000)
const many = Array.from({ length: 400 }, (_v, i) =>
collected(`h${i}`.padEnd(22, 'x'), 'img.example.com', `https://img.example.com/${long}${i}.png`)
@@ -260,7 +329,7 @@ describe('produceCollectedUrlsStep', () => {
})
it('drops an entry whose ref names another team', async () => {
- const step = createProduceCollectedUrlsStep(outputs, topHog, 100)
+ const step = createProduceCollectedUrlsStep(outputs, topHog, { producedRefCacheMax: 100 })
const otherTeam = 'b'.repeat(32)
await run(step, {
@@ -286,7 +355,7 @@ describe('produceCollectedUrlsStep', () => {
// 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, topHog, 100)
+ const step = createProduceCollectedUrlsStep(outputs, topHog, { producedRefCacheMax: 100 })
await run(step, {
message: { timestamp: CAPTURED_AT },
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts
index f2f8a77ed58b..e60406e8ec34 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts
@@ -6,6 +6,7 @@ import { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'
import { ok } from '~/ingestion/framework/results'
import { ProcessingStep } from '~/ingestion/framework/steps'
import { SessionRecordingIngesterMetrics } from '~/ingestion/pipelines/sessionreplay/metrics'
+import type { CrawlHistoryStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history'
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'
@@ -24,6 +25,7 @@ const DEFAULT_PRODUCED_REF_CACHE_WINDOW_MS = 15 * 24 * 60 * 60 * 1000
const MAX_RECORD_BYTES = 512 * 1024
const TOP_REGISTRABLE_DOMAINS = 10
const MAX_TRACKED_REGISTRABLE_DOMAINS = 1_000
+const CRAWL_HISTORY_WARNING_INTERVAL_MS = 60_000
/**
* The URL count one record may carry. Without it the collector's cap in another crate decides the
@@ -55,6 +57,17 @@ export interface CollectedUrlsMessage {
jobs: FrontierJob[]
}
+export interface ProduceCollectedUrlsOptions {
+ producedRefCacheMax?: number
+ producedRefCacheWindowMs?: number
+ crawlHistory?: Pick<CrawlHistoryStore, 'read'>
+}
+
+interface CachedCollectedUrl {
+ entry: CollectedUrl
+ cacheKey: string
+}
+
function producedUrlCacheKey(entry: CollectedUrl, timeBucket: number): string {
return createHash('sha256')
.update(entry.ref)
@@ -65,6 +78,42 @@ function producedUrlCacheKey(entry: CollectedUrl, timeBucket: number): string {
.digest('base64url')
}
+async function excludeFreshCrawlHistory(
+ candidates: CachedCollectedUrl[],
+ crawlHistory: Pick<CrawlHistoryStore, 'read'> | undefined,
+ nowMs: number,
+ onError: (error: unknown, count: number) => void
+): Promise<CachedCollectedUrl[]> {
+ if (!crawlHistory) {
+ return candidates
+ }
+
+ const startedAt = performance.now()
+ try {
+ const refs = [...new Set(candidates.map(({ entry }) => entry.ref))]
+ const stored = await crawlHistory.read(refs)
+ const publishable = candidates.filter(({ entry }) => {
+ const history = stored.get(entry.ref)
+ return history?.kind !== 'url' || history.nextFetchAtMs <= nowMs
+ })
+ SessionRecordingIngesterMetrics.incrementMlUrlCrawlHistory('fresh', candidates.length - publishable.length)
+ SessionRecordingIngesterMetrics.incrementMlUrlCrawlHistory('miss', publishable.length)
+ SessionRecordingIngesterMetrics.observeMlUrlCrawlHistoryDuration(
+ 'success',
+ (performance.now() - startedAt) / 1000
+ )
+ return publishable
+ } catch (error) {
+ SessionRecordingIngesterMetrics.incrementMlUrlCrawlHistory('error', candidates.length)
+ SessionRecordingIngesterMetrics.observeMlUrlCrawlHistoryDuration(
+ 'error',
+ (performance.now() - startedAt) / 1000
+ )
+ onError(error, candidates.length)
+ return candidates
+ }
+}
+
/**
* Produce the collected URLs of remote images to the fetch topic, keyed by registrable domain.
*
@@ -96,9 +145,13 @@ export function createProduceCollectedUrlsStep<
>(
outputs: IngestionOutputs<MlImageFetchOutput>,
topHog: TopHogRegistry,
- producedRefCacheMax: number = PRODUCED_REF_CACHE_MAX,
- producedRefCacheWindowMs: number = DEFAULT_PRODUCED_REF_CACHE_WINDOW_MS
+ options: ProduceCollectedUrlsOptions = {}
): ProcessingStep<T, T> {
+ const {
+ producedRefCacheMax = PRODUCED_REF_CACHE_MAX,
+ producedRefCacheWindowMs = DEFAULT_PRODUCED_REF_CACHE_WINDOW_MS,
+ crawlHistory,
+ } = options
if (!Number.isSafeInteger(producedRefCacheWindowMs) || producedRefCacheWindowMs <= 0) {
throw new Error(`produced URL cache window must be a positive safe integer, got ${producedRefCacheWindowMs}`)
}
@@ -108,20 +161,22 @@ export function createProduceCollectedUrlsStep<
maxKeys: MAX_TRACKED_REGISTRABLE_DOMAINS,
})
const producedUrlsTotal = topHog.registerSum('ml_image_fetch_produced_urls_total', { topN: 1, maxKeys: 1 })
+ let nextCrawlHistoryWarningAtMs = 0
- return function produceCollectedUrlsStep(input) {
+ return async function produceCollectedUrlsStep(input) {
const collected = input.collectedUrls
if (!collected?.length) {
- return Promise.resolve(ok(input))
+ return ok(input)
}
- const timeBucket = Math.floor(Date.now() / producedRefCacheWindowMs)
+ const nowMs = Date.now()
+ const timeBucket = Math.floor(nowMs / producedRefCacheWindowMs)
const fresh = collected
.map((entry) => ({ entry, cacheKey: producedUrlCacheKey(entry, timeBucket) }))
.filter(({ cacheKey }) => !producedTransportUrls.has(cacheKey))
SessionRecordingIngesterMetrics.incrementMlUrlsCollected('deduped', collected.length - fresh.length)
if (fresh.length === 0) {
- return Promise.resolve(ok({ ...input, collectedUrls: undefined }))
+ return ok({ ...input, collectedUrls: undefined })
}
// Each entry is checked, not just the first. A `bytes` ref names an image the page
@@ -156,14 +211,27 @@ export function createProduceCollectedUrlsStep<
logger.warn('🌐', 'ml_image_fetch_ref_unusable', { count: unusable })
}
if (!pseudoTeam || usable.length === 0) {
- return Promise.resolve(ok({ ...input, collectedUrls: undefined }))
+ return ok({ ...input, collectedUrls: undefined })
+ }
+
+ for (const { cacheKey } of usable) {
+ producedTransportUrls.add(cacheKey)
+ }
+ const publishable = await excludeFreshCrawlHistory(usable, crawlHistory, nowMs, (error, count) => {
+ if (nowMs < nextCrawlHistoryWarningAtMs) {
+ return
+ }
+ nextCrawlHistoryWarningAtMs = nowMs + CRAWL_HISTORY_WARNING_INTERVAL_MS
+ logger.warn('🌐', 'ml_image_fetch_crawl_history_precheck_failed', { count, error: String(error) })
+ })
+ if (publishable.length === 0) {
+ return ok({ ...input, collectedUrls: undefined })
}
const messageTimestamp = input.message.timestamp
- const firstSeenAtMs = messageTimestamp !== undefined && messageTimestamp > 0 ? messageTimestamp : Date.now()
+ const firstSeenAtMs = messageTimestamp !== undefined && messageTimestamp > 0 ? messageTimestamp : nowMs
const byDomain = new Map<string, FrontierJob[]>()
- for (const { entry, cacheKey } of usable) {
- producedTransportUrls.add(cacheKey)
+ for (const { entry } of publishable) {
const group = byDomain.get(entry.domain)
const record: FrontierJob = {
originalRef: entry.ref,
@@ -182,7 +250,7 @@ export function createProduceCollectedUrlsStep<
byDomain.set(entry.domain, [record])
}
}
- SessionRecordingIngesterMetrics.incrementMlUrlsCollected('queued', usable.length)
+ SessionRecordingIngesterMetrics.incrementMlUrlsCollected('queued', publishable.length)
const messages = [...byDomain].flatMap(([domain, jobs]) =>
packByBytes(jobs, MAX_RECORD_BYTES).map((slice) => {
@@ -199,7 +267,7 @@ export function createProduceCollectedUrlsStep<
// The failure handler captures only the cache keys, so that a produce which is not yet
// delivered does not hold the URL strings alive longer than the messages themselves.
- const producedCacheKeys = usable.map(({ cacheKey }) => cacheKey)
+ const producedCacheKeys = publishable.map(({ cacheKey }) => cacheKey)
const produce = outputs
.queueMessages(ML_IMAGE_FETCH_OUTPUT, messages)
.then(() => {
@@ -225,7 +293,7 @@ export function createProduceCollectedUrlsStep<
})
SessionRecordingIngesterMetrics.incrementMlUrlsCollected('produce_failed', producedCacheKeys.length)
})
- return Promise.resolve(ok({ ...input, collectedUrls: undefined }, [produce]))
+ return ok({ ...input, collectedUrls: undefined }, [produce])
}
}
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 a6b8acd0ef6e..20efe5436d92 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
@@ -1,4 +1,6 @@
+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'
@@ -19,6 +21,8 @@ import {
SessionRecordingIngester,
SessionRecordingIngesterCollaborators,
} from '~/ingestion/pipelines/sessionreplay/consumer'
+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,
@@ -91,6 +95,7 @@ export class IngestionSessionReplayMlMirrorServer implements NodeServer {
private postgres?: PostgresRouter
private producerRegistry?: KafkaProducerRegistry<SessionReplayProducerName>
+ private crawlHistoryClient?: DynamoDBClient
private redisPool?: RedisPool
private restrictionRedisPool?: RedisPool
@@ -145,6 +150,10 @@ export class IngestionSessionReplayMlMirrorServer implements NodeServer {
// Block metadata is produced to Kafka; the dedicated Parquet-sink deployment writes it to the ML bucket.
const metadataStore = new MlBlockMetadataSink(outputs, pseudonymSecret)
+ const urlProducerEnabled =
+ this.config.SESSION_RECORDING_ML_URL_COLLECTION_ENABLED &&
+ this.config.SESSION_RECORDING_ML_URL_PRODUCER_ENABLED
+ const urlCrawlHistory = urlProducerEnabled ? this.buildUrlCrawlHistory() : undefined
// Cleartext crypto: no encryption, deletions not honored (every session stays cleartext).
const keyStore = new CleartextKeyStore()
@@ -183,13 +192,13 @@ export class IngestionSessionReplayMlMirrorServer implements NodeServer {
},
// 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
+ urlProducerEnabled
? {
outputs,
producedRefCacheMax: this.config.SESSION_RECORDING_ML_URL_PRODUCED_REF_CACHE_MAX,
producedRefCacheWindowMs:
(this.config.AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS * 1000) / 2,
+ crawlHistory: urlCrawlHistory,
}
: undefined
),
@@ -223,12 +232,32 @@ export class IngestionSessionReplayMlMirrorServer implements NodeServer {
}
}
+ private buildUrlCrawlHistory(): Pick<CrawlHistoryStore, 'read'> | undefined {
+ if (!this.config.SESSION_RECORDING_ML_URL_CRAWL_HISTORY_PRECHECK_ENABLED) {
+ return undefined
+ }
+ const tableName = this.config.AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TABLE
+ const timeoutMs = this.config.SESSION_RECORDING_ML_URL_CRAWL_HISTORY_PRECHECK_TIMEOUT_MS
+ if (!tableName || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
+ logger.warn('🌐', 'ml_image_fetch_crawl_history_precheck_disabled', { tableConfigured: Boolean(tableName) })
+ return undefined
+ }
+ this.crawlHistoryClient = new DynamoDBClient({
+ region: this.config.SESSION_RECORDING_V2_S3_REGION || 'us-east-1',
+ endpoint: this.config.SESSION_RECORDING_DYNAMODB_ENDPOINT,
+ maxAttempts: 5,
+ requestHandler: new NodeHttpHandler(),
+ })
+ return new DynamoDBCrawlHistory(this.crawlHistoryClient, tableName, timeoutMs, timeoutMs)
+ }
+
private getCleanupResources(): CleanupResources {
return {
kafkaProducers: [],
redisPools: [this.redisPool, this.restrictionRedisPool].filter(Boolean) as RedisPool[],
postgres: this.postgres,
additionalCleanup: async () => {
+ this.crawlHistoryClient?.destroy()
await this.producerRegistry?.disconnectAll()
},
}