: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
fix(ai-research): dedupe image work across the sessions of a team month (#106877)
Robbie7041c156a82a
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.tsindex 3dd4ed5fea3d..a3c474fcae5a 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts@@ -2,7 +2,6 @@ import type { UrlPolicyDecline } from '@posthog/replay-anonymizer'import { parseJSON } from '~/common/utils/json-parse'import { parseImageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'-import { identityDigest } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema'import { ImageFetchBlockReason, isImageFetchBlockReason } from './block-reason'import { tryCanonicalizeUrl } from './politeness-key'@@ -302,9 +301,3 @@ export function serializeFrontierRecord(candidates: FetchCandidate[]): Buffer {}return Buffer.from(JSON.stringify(record))}--export function fetchCandidateHistoryKey(candidate: FetchCandidate): string {- return candidate.sessionId- ? `${candidate.originalRef}:session:${identityDigest(candidate.sessionId)}`- : candidate.originalRef-}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.tsindex 293df89aabed..d6578c07558e 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.ts@@ -1,4 +1,3 @@-import { fetchCandidateHistoryKey } from './collected-urls-record'import { FetchCandidate } from './collected-urls-record'export interface FetchCandidateLease {@@ -144,15 +143,12 @@ export function deduplicateFetchCandidates(candidates: FetchCandidate[]): Deduplconst candidatesByCanonicalRef = new Map<string, FetchCandidate>()let duplicateCount = 0for (const candidate of candidates) {- const existing = candidatesByCanonicalRef.get(fetchCandidateHistoryKey(candidate))+ const existing = candidatesByCanonicalRef.get(candidate.originalRef)if (existing) {duplicateCount += 1- candidatesByCanonicalRef.set(- fetchCandidateHistoryKey(candidate),- mergeDuplicateFetchCandidates(existing, candidate)- )+ candidatesByCanonicalRef.set(candidate.originalRef, mergeDuplicateFetchCandidates(existing, candidate))} else {- candidatesByCanonicalRef.set(fetchCandidateHistoryKey(candidate), candidate)+ candidatesByCanonicalRef.set(candidate.originalRef, candidate)}}return { candidates: [...candidatesByCanonicalRef.values()], duplicateCount }diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.tsindex 6975e6c0423a..cc74d2428ed6 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.ts@@ -841,9 +841,10 @@ describe('FetchRunner', () => {it.each([['2023-11', undefined, Date.UTC(2023, 11, 9)],['2024-02', undefined, Date.UTC(2024, 2, 9)],- ['2023-11', 'max-age=60', NOW_MS + 60_000],+ ['2023-11', 'max-age=60', Date.UTC(2023, 11, 9)],['2023-11', 'max-age=99999999', Date.UTC(2023, 11, 9)],- ['2023-11', 'no-store', NOW_MS],+ ['2023-11', 'no-cache', Date.UTC(2023, 11, 9)],+ ['2023-11', 'no-store', Date.UTC(2023, 11, 9)],])('expires month %s history with cache control %s', async (month, cacheControl, expiresAt) => {const harness = build({ cache: { requestTimeMs: NOW_MS, responseTimeMs: NOW_MS, cacheControl } })const [attempt] = await harness.runner.run(@@ -854,6 +855,17 @@ describe('FetchRunner', () => {expect(attempt.history?.storageExpiresAtMs).toBe(expiresAt)})+ it('keeps no cache metadata for a no-store response to a month-scoped ref', async () => {+ const harness = build({+ cache: { requestTimeMs: NOW_MS, responseTimeMs: NOW_MS, etag: '"v1"', cacheControl: 'no-store' },+ })+ const [attempt] = await harness.runner.run(+ [candidate({ originalRef: `imageurl:v2:7:2023-11:${'a'.repeat(22)}` })],+ new Map()+ )+ expect(attempt.history).toMatchObject({ outcome: 'ok', cache: undefined })+ })+it('extends URL history to the end of explicit freshness', async () => {const fortyDaysMs = 40 * 24 * 60 * 60 * 1000const harness = build({diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.tsindex 6364727b628e..e139bb2eb651 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.ts@@ -2,7 +2,6 @@ import { ConcurrencyController } from '~/common/utils/concurrencyController'import { logger } from '~/common/utils/logger'import type { ImageFetchBlockReason } from './block-reason'-import { fetchCandidateHistoryKey } from './collected-urls-record'import { FetchCandidate, MAX_HOPS, RepublishReason } from './collected-urls-record'import { ConfigurationPolicyPass, ConfigurationPolicyService } from './configuration-policy'import { ConfigurationCacheItem, CrawlHistoryItem, HttpCacheMetadata, UrlCrawlHistoryItem } from './crawl-history'@@ -27,7 +26,7 @@ import { OriginRequestScheduler } from './origin-request-scheduler'import { canonicalizeUrl } from './politeness-key'import { ImageFetchProcessingMetrics } from './processing-metrics'import { ImageFetchTopHogMetrics } from './tophog-metrics'-import { urlHistoryExpiresAtMs } from './url-history-expiry'+import { storedUrlHistoryCache, urlHistoryExpiresAtMs } from './url-history-expiry'export type ShedReason =| 'breaker_open'@@ -545,7 +544,7 @@ export class FetchRunner implements FetchPass {)}- const previous = stored.get(fetchCandidateHistoryKey(candidate))+ const previous = stored.get(candidate.originalRef)const previousUrl = previous?.kind === 'url' ? previous : undefinedconst result = await ImageFetchProcessingMetrics.measure('candidate_fetch', () =>this.fetcher.fetch(candidate.currentUrl, {@@ -818,11 +817,11 @@ export class FetchRunner implements FetchPass {lost: false,history: {kind: 'url',- key: fetchCandidateHistoryKey(candidate),+ key: candidate.originalRef,nextFetchAtMs,storageExpiresAtMs: nextFetchAtMs,outcome: String(outcome),- cache,+ cache: storedUrlHistoryCache(candidate.originalRef, cache),},configurationUpdates,}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.tsindex ed4ca32172b0..a10d9fad994c 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts@@ -230,7 +230,7 @@ class BufferedRepublishBatch implements RepublishBatch {private planMessages(): PlannedRepublishMessage[] {const groups = new Map<string, PendingRepublish[]>()for (const item of this.pending) {- const key = `${item.destination.topic}\0${item.candidate.registrableDomain}\0${item.candidate.sessionId ?? ''}`+ const key = `${item.destination.topic}\0${item.candidate.registrableDomain}\0${item.candidate.sessionId ? '2' : '1'}`const group = groups.get(key)if (group) {group.push(item)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.tsindex b87754326ea8..5a1559a5f791 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts@@ -2,6 +2,7 @@ import { Message } from 'node-rdkafka'import { register } from 'prom-client'import { INGESTION_VERSION_HEADER } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema'+import { MlKafkaTransport } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport'import { RecordedTopHogMetric, createRecordingTopHog } from '~/tests/helpers/tophog'import { FetchCandidate, MAX_HOPS, serializeFrontierRecord } from './collected-urls-record'@@ -33,6 +34,17 @@ function candidate(name: string, overrides: Partial<FetchCandidate> = {}): Fetch}}+const V3_REF = `imageurl:v3:42:2026-09:${'a'.padEnd(22, '0')}`++function sessionCandidate(sessionId: string, overrides: Partial<FetchCandidate> = {}): FetchCandidate {+ return candidate('a', { originalRef: V3_REF, sessionId, ...overrides })+}++const cleartextV2Transport = {+ read: (messages: Message[]) =>+ Promise.resolve(messages.map((message) => ({ message, original: message, version: 2 as const }))),+} as unknown as MlKafkaTransport+function message(candidates: FetchCandidate[], key = 'example.com', partition = 0): Message {const value = serializeFrontierRecord(candidates)return {@@ -101,7 +113,7 @@ interface Harness {topHogRecords: Map<string, RecordedTopHogMetric[]>}-function build(dryRun = false, deadLettersEnabled = true): Harness {+function build(dryRun = false, deadLettersEnabled = true, keyManager?: MlKafkaTransport): Harness {const history = new FakeCrawlHistory()const run = jest.fn((candidates: FetchCandidate[], _stored: Map<string, CrawlHistoryItem>) =>Promise.resolve(candidates.map((item) => terminal(item)))@@ -117,7 +129,8 @@ function build(dryRun = false, deadLettersEnabled = true): Harness {{ seenTtlSeconds: 30 * 24 * 60 * 60, dryRun },dryRun ? undefined : ({ run } as FetchPass),deadLettersEnabled ? ({ park } as FrontierDeadLetterSink) : null,- topHogMetrics+ topHogMetrics,+ keyManager)return { consumer, history, run, republish, flush, park, topHogRecords: recordingTopHog.records }}@@ -296,12 +309,20 @@ describe('UrlFetchConsumer', () => {}})- it('deduplicates one global ref within the batch', async () => {- const harness = build()+ it.each([+ ['a v1 global ref', undefined, candidate('a'), candidate('a')],+ [+ 'a v3 ref from two sessions',+ cleartextV2Transport,+ sessionCandidate('01a0c669-8800-7000-8000-000000000001'),+ sessionCandidate('01a0c669-8800-7000-8000-000000000002'),+ ],+ ])('deduplicates %s within the batch', async (_name, keyManager, first, second) => {+ const harness = build(false, true, keyManager)- await harness.consumer.handleBatch([message([candidate('a')]), message([candidate('a')])], NOW_MS)+ await harness.consumer.handleBatch([message([first]), message([second])], NOW_MS)- expect(harness.run.mock.calls[0][0]).toEqual([candidate('a', { sourcePartitions: [0] })])+ expect(harness.run.mock.calls[0][0]).toEqual([{ ...first, sourcePartitions: [0] }])})it('keeps the most conservative durable state from duplicate jobs', async () => {@@ -342,19 +363,30 @@ describe('UrlFetchConsumer', () => {)})- it('skips a URL whose crawl-history interval has not ended', async () => {- const harness = build()- harness.history.items.set(candidate('a').originalRef, {+ it.each([+ ['a v1 global ref', undefined, candidate('a'), candidate('b')],+ [+ 'a v3 ref fetched for another session',+ cleartextV2Transport,+ sessionCandidate('01a0c669-8800-7000-8000-000000000001'),+ candidate('b', {+ originalRef: `imageurl:v3:42:2026-09:${'b'.padEnd(22, '0')}`,+ sessionId: '01a0c669-8800-7000-8000-000000000001',+ }),+ ],+ ])('skips %s whose crawl-history interval has not ended', async (_name, keyManager, stored, fresh) => {+ const harness = build(false, true, keyManager)+ harness.history.items.set(stored.originalRef, {kind: 'url',- key: candidate('a').originalRef,+ key: stored.originalRef,nextFetchAtMs: NOW_MS + 1,storageExpiresAtMs: NOW_MS + 1,outcome: 'ok',})- await harness.consumer.handleBatch([message([candidate('a'), candidate('b')])], NOW_MS)+ await harness.consumer.handleBatch([message([stored, fresh])], NOW_MS)- expect(harness.run.mock.calls[0][0]).toEqual([candidate('b', { sourcePartitions: [0] })])+ expect(harness.run.mock.calls[0][0]).toEqual([{ ...fresh, sourcePartitions: [0] }])})it('republishes a job that arrives before its durable not-before time', async () => {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.tsindex 4cad6e669110..4158965dc5fc 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts@@ -9,7 +9,6 @@ import {validateImageRefVersion,} from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport'-import { fetchCandidateHistoryKey } from './collected-urls-record'import {FetchCandidate,MAX_HOPS,@@ -151,15 +150,15 @@ export class UrlFetchConsumer {}for (const candidate of parsed.candidates) {const partitionCandidate = { ...candidate, sourcePartitions: [message.partition] }- const existing = candidatesByRef.get(fetchCandidateHistoryKey(partitionCandidate))+ const existing = candidatesByRef.get(partitionCandidate.originalRef)if (existing) {dedupedInBatch += 1candidatesByRef.set(- fetchCandidateHistoryKey(partitionCandidate),+ partitionCandidate.originalRef,mergeDuplicateFetchCandidates(existing, partitionCandidate))} else {- candidatesByRef.set(fetchCandidateHistoryKey(partitionCandidate), partitionCandidate)+ candidatesByRef.set(partitionCandidate.originalRef, partitionCandidate)}}}@@ -202,7 +201,7 @@ export class UrlFetchConsumer {}const keys = [- ...candidates.map(fetchCandidateHistoryKey),+ ...candidates.map((candidate) => candidate.originalRef),...[...origins.keys()].flatMap((origin) => [configurationCacheKey(origin, 'robots'),configurationCacheKey(origin, 'tdmrep'),@@ -215,7 +214,7 @@ export class UrlFetchConsumer {const fetchable: FetchCandidate[] = []const notReady: FetchCandidate[] = []for (const candidate of candidates) {- const history = stored.get(fetchCandidateHistoryKey(candidate))+ const history = stored.get(candidate.originalRef)if (history?.kind === 'url' && history.nextFetchAtMs > nowMs) {ImageFetchConsumerMetrics.incDeduped('store', 1)for (const sourcePartition of candidate.sourcePartitions ?? []) {@@ -477,7 +476,7 @@ export class UrlFetchConsumer {const nextFetchAtMs = urlHistoryExpiresAtMs(candidate.originalRef, nowMs, this.options.seenTtlSeconds)return {kind: 'url',- key: fetchCandidateHistoryKey(candidate),+ key: candidate.originalRef,nextFetchAtMs,storageExpiresAtMs: nextFetchAtMs,outcome,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-history-expiry.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-history-expiry.tsindex 046da5e3b0f5..113973da26c3 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-history-expiry.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-history-expiry.ts@@ -9,21 +9,24 @@ export function urlHistoryExpiresAtMs(seenTtlSeconds: number,cache?: HttpCacheMetadata): number {- const minimumNextFetchAtMs = nowMs + seenTtlSeconds * 1000- const explicitNextFetchAtMs = cache ? nowMs + explicitFreshnessLifetimeMs(cache, nowMs) : 0const month = parseImageRef(ref)?.sessionMonth- const partitionExpiresAtMs = month ? Date.parse(`${month}-01T00:00:00Z`) : undefined- let nextFetchAtMs = Math.max(minimumNextFetchAtMs, explicitNextFetchAtMs)- if (partitionExpiresAtMs !== undefined) {- const end = new Date(partitionExpiresAtMs)+ if (month !== undefined) {+ // The stored image is write-once per team, month and URL, so a fetch before the month partition ends cannot change it, and HTTP freshness does not shorten this.+ const end = new Date(`${month}-01T00:00:00Z`)end.setUTCMonth(end.getUTCMonth() + 1)end.setUTCDate(end.getUTCDate() + 8)- const hasExplicitFreshness =- cache?.expires !== undefined ||- /(?:^|,)\s*(?:s-maxage|max-age|no-cache|no-store|private|must-revalidate)(?:\s*(?:=|,|$))/i.test(- cache?.cacheControl ?? ''- )- nextFetchAtMs = Math.min(end.getTime(), hasExplicitFreshness ? explicitNextFetchAtMs : Infinity)+ return end.getTime()}- return nextFetchAtMs+ const minimumNextFetchAtMs = nowMs + seenTtlSeconds * 1000+ const explicitNextFetchAtMs = cache ? nowMs + explicitFreshnessLifetimeMs(cache, nowMs) : 0+ return Math.max(minimumNextFetchAtMs, explicitNextFetchAtMs)+}++export function storedUrlHistoryCache(+ ref: string,+ cache: HttpCacheMetadata | undefined+): HttpCacheMetadata | undefined {+ const isMonthScoped = parseImageRef(ref)?.sessionMonth !== undefined+ const forbidsStoring = /(?:^|,)\s*no-store\s*(?:,|$)/i.test(cache?.cacheControl ?? '')+ return isMonthScoped && forbidsStoring ? undefined : cache}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/versioned-crawl-history.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/versioned-crawl-history.tsindex f9f5f5e5d560..c2c5927e3126 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/versioned-crawl-history.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/versioned-crawl-history.ts@@ -6,20 +6,20 @@ const SCOPED_URL_REF = /^imageurl:v[23]:/export class VersionedCrawlHistory implements CrawlHistoryStore {constructor(private readonly legacy: CrawlHistoryStore,- private readonly v2: CrawlHistoryStore+ private readonly v3: CrawlHistoryStore) {}public async read(keys: string[]): Promise<Map<string, CrawlHistoryItem>> {const scoped = keys.filter((key) => SCOPED_URL_REF.test(key))const legacy = keys.filter((key) => !SCOPED_URL_REF.test(key))- const results = await Promise.all([this.legacy.read(legacy), this.v2.read(scoped)])+ const results = await Promise.all([this.legacy.read(legacy), this.v3.read(scoped)])return new Map(results.flatMap((result) => [...result]))}public async write(items: CrawlHistoryItem[]): Promise<void> {await Promise.all([this.legacy.write(items.filter((item) => !SCOPED_URL_REF.test(item.key))),- this.v2.write(items.filter((item) => SCOPED_URL_REF.test(item.key))),+ this.v3.write(items.filter((item) => SCOPED_URL_REF.test(item.key))),])}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.tsindex 754fa083b019..0dada6106c5d 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts@@ -894,6 +894,7 @@ export class ImageBatcher {tableKeyString(imageKeyId(Number(item.image.teamId), item.image.sessionMonth!))))+ ImageScrubConsumerMetrics.incUrlImageWrite(outcome)if (outcome === 'created' && item.capturedAtMs !== undefined) {ImageScrubConsumerMetrics.observeCaptureToS3('url', item.capturedAtMs, Date.now())}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.tsindex 146fb92cada9..d1db1035acac 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts@@ -2,6 +2,7 @@ import { Counter, Gauge, Histogram } from 'prom-client'import type { MlWireVersion } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema'+import { type UrlImageWriteOutcome } from './image-shard-store'import { type ImageTransportRejectionReason } from './image-transport'import { ScrubWaitReason } from './scrub-client'@@ -42,6 +43,11 @@ export class ImageScrubConsumerMetrics {help: 'Messages per non-empty poll batch. Read alongside deduped{scope="batch"}: consistently small batches cap how much intra-batch dedup can collapse, whatever the duplicate rate is',buckets: [1, 10, 50, 100, 200, 300, 400, 500],})+ private static readonly urlImageWrites = new Counter({+ name: 'ml_mirror_image_scrub_consumer_url_image_writes_total',+ help: 'URL image writes to S3 by outcome. The object key names the team, month and URL and is written once, so already_exists counts a scrubbed image that S3 already held. A repeated fetch, a duplicate ref in one poll batch, and a replay after a rebalance all end this way. A write that fails is not counted. already_exists / (created + already_exists) is the share of completed URL image writes that stored nothing new',+ labelNames: ['outcome'],+ })private static readonly invalidKey = new Counter({name: 'ml_mirror_image_scrub_consumer_invalid_key_total',help: 'Messages dropped because the key is missing, not an image ref, or the value is empty — a sustained rate means producer/consumer ref-format drift is zeroing the lane',@@ -229,6 +235,10 @@ export class ImageScrubConsumerMetrics {public static incDeduped(scope: 'batch' | 'pod'): void {this.deduped.labels(scope).inc()}+ public static incUrlImageWrite(outcome: UrlImageWriteOutcome): void {+ this.urlImageWrites.labels(outcome).inc()+ }+public static incInvalidKey(): void {this.invalidKey.inc()}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.test.tsindex 1e8284c6a872..bafb3f1dd115 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.test.ts@@ -94,6 +94,29 @@ describe('produceCollectedImagesStep', () => {])})+ it('dedups a ref that another session of the team produced', async () => {+ const step = createProduceCollectedImagesStep(outputs)+ const ref = `image:v3:42:2026-09:${'h1'.padEnd(22, 'x')}`+ const sessionInput = (sessionId: string) => {+ const key = {+ identity: { teamId: 42, sessionId, sessionMonth: '2026-09' },+ plaintext: Buffer.alloc(32),+ wrapped: Buffer.alloc(0),+ }+ return {+ message: { timestamp: CAPTURED_AT },+ headers: { session_id: sessionId },+ mlKeys: { session: key, image: key },+ collectedImages: [image(ref)],+ }+ }++ await run(step, sessionInput('01a0c669-8800-7000-8000-000000000001'))+ await run(step, sessionInput('01a0c669-8800-7000-8000-000000000002'))++ expect(queued).toHaveLength(1)+ })+it('evicts oldest refs at capacity instead of forgetting the whole working set', async () => {const step = createProduceCollectedImagesStep(outputs, 2)await run(step, {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.tsindex 72cae1ea2aca..d8460b2de489 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts@@ -51,8 +51,7 @@ export function createProduceCollectedImagesStep<return Promise.resolve(ok(input))}- const cacheRef = (ref: string): string => (key ? `${key.identity.sessionId}:${ref}` : ref)- const fresh = images.filter((image) => !producedRefs.has(cacheRef(image.ref)))+ const fresh = images.filter((image) => !producedRefs.has(image.ref))MlMirrorMetrics.incrementMlImagesCollected('deduped', images.length - fresh.length)if (fresh.length === 0) {return Promise.resolve(ok({ ...input, collectedImages: undefined }))@@ -60,7 +59,7 @@ export function createProduceCollectedImagesStep<let bytes = 0for (const image of fresh) {- producedRefs.add(cacheRef(image.ref))+ producedRefs.add(image.ref)bytes += image.bytes.length}MlMirrorMetrics.incrementMlImagesCollected('queued', fresh.length)@@ -74,7 +73,7 @@ export function createProduceCollectedImagesStep<// whole packed FFI buffer (up to 32 MB per source message), and queueMessages copies the// slices synchronously — a closure holding `fresh` would pin the full packed buffer per// in-flight produce, unbounded by the producer queue's byte accounting.- const refs = fresh.map((image) => cacheRef(image.ref))+ const refs = fresh.map((image) => image.ref)const produce = outputs.queueMessages(ML_IMAGE_SCRUB_OUTPUT,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.tsindex 513dc947cf77..4b3a57367328 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@@ -34,6 +34,31 @@ describe('produceCollectedUrlsStep', () => {return { ref: `imageurl:${hash.padEnd(22, 'x')}`, teamId: TEAM_ID, url, host, domain }}+ function collectedV3(hash: string, url: string): CollectedUrl {+ const host = new URL(url).host+ return {+ ref: `imageurl:v3:${TEAM_ID}:2026-09:${hash.padEnd(22, 'x')}`,+ teamId: TEAM_ID,+ url,+ host,+ domain: host,+ }+ }++ function v3SessionInput(sessionId: string, collectedUrls: CollectedUrl[]) {+ const key = {+ identity: { teamId: Number(TEAM_ID), sessionId, sessionMonth: '2026-09' },+ plaintext: Buffer.alloc(32),+ wrapped: Buffer.alloc(0),+ }+ return {+ message: { timestamp: CAPTURED_AT },+ headers: { session_id: sessionId },+ mlKeys: { session: key, image: key },+ collectedUrls,+ }+ }+function decode(batch: { key: string; value: Buffer }[]) {return batch.map((message) => ({key: message.key,@@ -130,6 +155,44 @@ describe('produceCollectedUrlsStep', () => {).toEqual([[[first.url]], [[replacement.url]]])})+ it('dedups an identical transport URL that another session of the team collected', async () => {+ const step = createProduceCollectedUrlsStep(outputs, topHog)+ const url = collectedV3('h1', 'https://cdn.example.com/a.jpg')++ await run(step, v3SessionInput('01a0c669-8800-7000-8000-000000000001', [url]))+ await run(step, v3SessionInput('01a0c669-8800-7000-8000-000000000002', [url]))++ expect(queued).toHaveLength(1)+ })++ it('skips a v3 ref whose crawl history is fresh', async () => {+ const fresh = collectedV3('h1', 'https://cdn.example.com/fresh.jpg')+ const missing = collectedV3('h2', 'https://cdn.example.com/missing.jpg')+ 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: Number.MAX_SAFE_INTEGER,+ storageExpiresAtMs: Number.MAX_SAFE_INTEGER,+ outcome: 'ok',+ },+ ],+ ])+ )+ const step = createProduceCollectedUrlsStep(outputs, topHog, { crawlHistory: { read } })++ await run(step, v3SessionInput('01a0c669-8800-7000-8000-000000000001', [fresh, missing]))++ expect(decode(queued[0])[0].value.jobs.map((job) => job.originalRef)).toEqual([missing.ref])+ })+it('produces an identical transport URL again after the dedup window', async () => {jest.useFakeTimers().setSystemTime(10_000)try {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.tsindex 6bfb466f8128..10521fc3929d 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@@ -180,7 +180,7 @@ export function createProduceCollectedUrlsStep<const fresh = collected.map((entry) => ({entry,- cacheKey: `${key?.identity.sessionId ?? ''}:${producedUrlCacheKey(entry, timeBucket)}`,+ cacheKey: producedUrlCacheKey(entry, timeBucket),})).filter(({ cacheKey }) => !producedTransportUrls.has(cacheKey))MlMirrorMetrics.incrementMlUrlsCollected('deduped', collected.length - fresh.length)@@ -227,18 +227,13 @@ export function createProduceCollectedUrlsStep<for (const { cacheKey } of usable) {producedTransportUrls.add(cacheKey)}- const publishable = await excludeFreshCrawlHistory(- usable,- key ? undefined : crawlHistory,- nowMs,- (error, count) => {- if (nowMs < nextCrawlHistoryWarningAtMs) {- return- }- nextCrawlHistoryWarningAtMs = nowMs + CRAWL_HISTORY_WARNING_INTERVAL_MS- logger.warn('🌐', 'ml_image_fetch_crawl_history_precheck_failed', { count, error: String(error) })+ 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 })}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.tsindex 447d051249be..6d71ce9a7954 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts@@ -310,18 +310,18 @@ export class IngestionSessionReplayMlImageFetchServer extends MlMirrorConsumerSe!this.config.AI_RESEARCH_REPLAY_IMAGE_FETCH_V2_DYNAMODB_TABLE ||this.config.AI_RESEARCH_REPLAY_IMAGE_FETCH_V2_DYNAMODB_TABLE === tableName) {- throw new Error('ML v2 requires a separate image fetch history table')+ throw new Error('ML v3 requires a separate image fetch history table')}this.keyManager = new MlKeyManager(this.config)await this.keyManager.start()- const v2 = new DynamoDBCrawlHistory(+ const v3 = new DynamoDBCrawlHistory(this.crawlHistoryClient,this.config.AI_RESEARCH_REPLAY_IMAGE_FETCH_V2_DYNAMODB_TABLE,dynamoDBTimeoutMs,STORE_BATCH_BUDGET_MS)- await v2.validateAccess(Date.now())- crawlHistory = new VersionedCrawlHistory(legacyCrawlHistory, v2)+ await v3.validateAccess(Date.now())+ crawlHistory = new VersionedCrawlHistory(legacyCrawlHistory, v3)}// Built even in dry run, so the wiring is exercised by every start rather than only by thediff --git a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.tsindex bbe9b9d7d5b8..e54f7ca0ac6c 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts@@ -15,6 +15,7 @@ import {} 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 { VersionedCrawlHistory } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/versioned-crawl-history'import { ML_BLOCK_COMPRESSION } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-compression'import { resolveMlMirrorRedisConnection } from '~/ingestion/pipelines/sessionreplay/ml-mirror/config'import { MlKeyManager } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime'@@ -220,7 +221,15 @@ export class IngestionSessionReplayMlMirrorServer extends MlMirrorConsumerServermaxAttempts: 5,requestHandler: new NodeHttpHandler(),})- return new DynamoDBCrawlHistory(this.crawlHistoryClient, tableName, timeoutMs, timeoutMs)+ const legacy = new DynamoDBCrawlHistory(this.crawlHistoryClient, tableName, timeoutMs, timeoutMs)+ const v3TableName = this.config.AI_RESEARCH_REPLAY_IMAGE_FETCH_V2_DYNAMODB_TABLE+ if (!v3TableName) {+ return legacy+ }+ return new VersionedCrawlHistory(+ legacy,+ new DynamoDBCrawlHistory(this.crawlHistoryClient, v3TableName, timeoutMs, timeoutMs)+ )}protected getCleanupResources(): CleanupResources {diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.mdindex 0238ac2120d9..84b9e5e481c3 100644--- a/products/ai_training/docs/replay-data.md+++ b/products/ai_training/docs/replay-data.md@@ -230,10 +230,12 @@ Inline images have an encrypted lookup for each reference, published after the sReaders fetch that lookup directly; a missing image does not require a scan of the team's image history.The image scrubber hands the images it scrubbed to a write lane every 30 seconds or when its buffer is full, writes them while it scrubs the next batches, and writes the shard groups of one hand-off concurrently.The offsets of a hand-off are stored after its writes complete, in hand-off order, so a failed write stops every later store and the pod replays from the last stored offset.-Source deduplication includes the session, so deleting one source session cannot suppress another session's copy.+Source deduplication uses the image reference, which names the team and the session month, so one fetch serves every session of that team month.+Session deletion does not remove images, so a session cannot lose an image that another session fetched.The v2 image-fetch frontier uses a separate, initially empty DynamoDB history table.Its URL history expires eight days after the end of the session's UTC month.-Explicit HTTP freshness or cache restrictions can shorten this expiry; they cannot extend it.+HTTP freshness and cache directives do not change this expiry, because the stored image for a team, month and URL is write-once.+A `no-store` response leaves no cache metadata in that history.Robots.txt and TDM reservation caches keep their shared origin keys and existing expiry rules.It does not inherit v1 seen flags or successful fetch results.