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.

perf(ai-research): hold the ml mirror ref dedup caches in rust (#109794)

Robbieb6cbae52b17a
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 86474d363400..5573a0cff021 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
@@ -31,6 +31,7 @@ import { MlBatchHandle, MlDeferrableInput } from './batch-handle'
import { MlKeyBatchController } from './keys/batch-controller'
import { MlSessionKeys } from './keys/key-store'
import { createParseAndAnonymizeMessageStep } from './parse-and-anonymize-step'
+import { ProducedImageRefs, ProducedRefs, ProducedTransportUrls } from './produced-refs'
import { mlSessionIdDropReason } from './session-identifier-format'
export interface MlMirrorPipelineOptions {
@@ -215,6 +216,11 @@ export function createMlMirrorAnonymizePipeline(
const pipelineConfig: PipelineConfig<OverflowOutput> = { outputs, promiseScheduler }
const topHogWrapper = createTopHogWrapper(topHog)
+ const producedImageRefs = imageScrub ? new ProducedImageRefs(imageScrub.producedRefCacheMax) : undefined
+ const producedTransportUrls = urlFetch
+ ? new ProducedTransportUrls(urlFetch.producedRefCacheMax, urlFetch.producedRefCacheWindowMs)
+ : undefined
+ const producedRefs: ProducedRefs = { images: producedImageRefs, urls: producedTransportUrls }
// The deferred step runs at commit time with the recorder current then, so it is typed on the full recorder while the element it is queued from only carries the retention lookup.
function deferPublication<T extends MlDeferrableInput & { mlBatch: MlBatchHandle }>(
step: ProcessingStep<T & SessionBatchContext, T & SessionBatchContext>
@@ -265,7 +271,8 @@ export function createMlMirrorAnonymizePipeline(
createParseAndAnonymizeMessageStep(
collection?.collectImages || collection?.collectUrls
? collection
- : undefined
+ : undefined,
+ producedRefs
),
[
timer('parse_time_ms_by_session_id', (input) => ({
@@ -275,28 +282,30 @@ export function createMlMirrorAnonymizePipeline(
]
)
)
- const withImagesProduced = imageScrub
- ? parsed.pipe(
- deferPublication(
- createProduceCollectedImagesStep(
- imageScrub.outputs,
- imageScrub.producedRefCacheMax
+ const withImagesProduced =
+ imageScrub && producedImageRefs
+ ? parsed.pipe(
+ deferPublication(
+ createProduceCollectedImagesStep(
+ imageScrub.outputs,
+ producedImageRefs
+ )
)
)
- )
- : parsed
- const withUrlsProduced = urlFetch
- ? withImagesProduced.pipe(
- deferPublication(
- createProduceCollectedUrlsStep(urlFetch.outputs, topHog, {
- producedRefCacheMax: urlFetch.producedRefCacheMax,
- producedRefCacheWindowMs:
- urlFetch.producedRefCacheWindowMs,
- crawlHistory: urlFetch.crawlHistory,
- })
+ : parsed
+ const withUrlsProduced =
+ urlFetch && producedTransportUrls
+ ? withImagesProduced.pipe(
+ deferPublication(
+ createProduceCollectedUrlsStep(
+ urlFetch.outputs,
+ topHog,
+ producedTransportUrls,
+ { crawlHistory: urlFetch.crawlHistory }
+ )
+ )
)
- )
- : withImagesProduced
+ : withImagesProduced
return withUrlsProduced.pipe(
deferRecording(
withSessionReplayRecordingMetrics(
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts
index a748317ac159..626533cbbb0d 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts
@@ -1,6 +1,6 @@
import { DateTime } from 'luxon'
-import type { AnonymizeMeta } from '@posthog/replay-anonymizer'
+import type { AnonymizeKafkaPayloadResult, AnonymizeMeta } from '@posthog/replay-anonymizer'
import { parseJSON } from '~/common/utils/json-parse'
import { logger } from '~/common/utils/logger'
@@ -26,6 +26,7 @@ import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
import { MlSessionKeys } from './keys/key-store'
import { MlMirrorMetrics } from './metrics'
+import { ProducedRefs, producedRefDedup } from './produced-refs'
import {
PSEUDONYM_IMAGE_CONTENT_KEY,
PSEUDONYM_IMAGE_URL_GLOBAL_VALUE,
@@ -33,21 +34,11 @@ import {
PSEUDONYM_TEAM,
pseudonymize,
} from './pseudonymize'
+import { getRustAnonymizer } from './rust-anonymizer'
import { mlDatasetVersion, sessionStartMonth, usesRawSessionIdentifiers } from './session-identifier-format'
const MESSAGE_TIMESTAMP_DIFF_THRESHOLD_DAYS = 7
-// Lazily loaded so deployments that never run this step don't pay the native-module load (and so a
-// missing addon only breaks the native path, not every import of this module).
-type RustAnonymizer = typeof import('@posthog/replay-anonymizer')
-let rustAnonymizer: RustAnonymizer | undefined
-function getRustAnonymizer(): RustAnonymizer {
- if (!rustAnonymizer) {
- rustAnonymizer = require('@posthog/replay-anonymizer') as RustAnonymizer
- }
- return rustAnonymizer
-}
-
// Addon failure reasons that map to a DLQ (mirroring the TS parse step's classifications).
const DLQ_REASONS = new Set([
'invalid_compressed_data',
@@ -113,7 +104,10 @@ export interface ImageCollectionConfig {
*/
export function createParseAndAnonymizeMessageStep<
T extends ParseMessageStepInput & { team: TeamForReplay; mlKeys?: MlSessionKeys },
->(imageCollection?: ImageCollectionConfig): ProcessingStep<T, T & ParseAndAnonymizeStepOutput> {
+>(
+ imageCollection?: ImageCollectionConfig,
+ producedRefs?: ProducedRefs
+): ProcessingStep<T, T & ParseAndAnonymizeStepOutput> {
const globalUrlKey =
imageCollection?.collectUrls === true
? pseudonymize(imageCollection.pseudonymSecret, PSEUDONYM_IMAGE_URL_KEY, PSEUDONYM_IMAGE_URL_GLOBAL_VALUE)
@@ -190,7 +184,8 @@ export function createParseAndAnonymizeMessageStep<
imageTeamId,
teamKeys?.contentKey,
globalUrlKey,
- ...(referenceNamespace ? ([referenceNamespace] as const) : [])
+ referenceNamespace,
+ producedRefDedup(producedRefs, Date.now())
)
} catch (error) {
// A rejected promise (native panic, addon load failure) must fail closed.
@@ -300,11 +295,11 @@ export function createParseAndAnonymizeMessageStep<
snapshot_library: meta.snapshotLibrary,
}
- const collectedImages = teamKeys?.contentKey
- ? unpackCollectedImages(imageTeamId!, meta, result.images)
- : undefined
+ const collectedImages = teamKeys?.contentKey ? unpackCollectedImages(imageTeamId!, meta, result) : undefined
const collectedUrls =
- globalUrlKey && teamKeys ? unpackCollectedUrls(teamKeys.teamId, meta, referenceNamespace) : undefined
+ globalUrlKey && teamKeys
+ ? unpackCollectedUrls(teamKeys.teamId, meta, result, referenceNamespace)
+ : undefined
return ok({ ...input, parsedMessage, collectedImages, collectedUrls })
}
@@ -325,13 +320,19 @@ function recordImageSources(meta: AnonymizeMeta): void {
* Slice the addon's packed image buffer into per-image produce records. The lines already carry the
* refs, so a skipped slice only means that ref stays dangling (same outcome as a failed produce) —
* never a blocked message.
+ *
+ * The addon left out the images an earlier message produced. They still count as collected.
*/
function unpackCollectedImages(
teamId: string,
meta: AnonymizeMeta,
- packed: Buffer | null
+ result: Pick<AnonymizeKafkaPayloadResult, 'images' | 'dedupedImageCount'>
): CollectedImage[] | undefined {
+ const deduped = result.dedupedImageCount ?? 0
+ MlMirrorMetrics.incrementMlImagesCollected('deduped', deduped)
+ const packed = result.images
if (!meta.images?.length || !packed) {
+ MlMirrorMetrics.incrementMlImagesCollected('collected', deduped)
return undefined
}
const images: CollectedImage[] = []
@@ -345,7 +346,7 @@ function unpackCollectedImages(
bytes: packed.subarray(entry.offset, entry.offset + entry.len),
})
}
- MlMirrorMetrics.incrementMlImagesCollected('collected', images.length)
+ MlMirrorMetrics.incrementMlImagesCollected('collected', images.length + deduped)
return images.length > 0 ? images : undefined
}
@@ -355,32 +356,36 @@ function unpackCollectedImages(
* The domain count is observed for a message with no URL too. A count taken only from messages
* that carry one describes an image-heavy page, and this number exists to size a topic that
* carries all the traffic.
+ *
+ * The addon left out the URLs an earlier message produced. They still count as collected, and the
+ * addon counted the domains before it left them out.
*/
function unpackCollectedUrls(
teamId: string,
meta: AnonymizeMeta,
+ result: Pick<AnonymizeKafkaPayloadResult, 'dedupedUrlCount' | 'collectedUrlDomainCount'>,
referenceNamespace?: string
): CollectedUrl[] | undefined {
- const urls: CollectedUrl[] = []
- const domains = new Set<string>()
- for (const entry of meta.urls ?? []) {
- urls.push({
- ref: referenceNamespace ? `imageurl:${referenceNamespace}:${entry.hash}` : urlRef(entry.hash),
- teamId,
- url: entry.url,
- host: entry.host,
- domain: entry.domain,
- })
- domains.add(entry.domain)
- }
+ const urls: CollectedUrl[] = (meta.urls ?? []).map((entry) => ({
+ ref: referenceNamespace ? `imageurl:${referenceNamespace}:${entry.hash}` : urlRef(entry.hash),
+ teamId,
+ url: entry.url,
+ host: entry.host,
+ domain: entry.domain,
+ }))
for (const decline of meta.urlDeclines ?? []) {
MlMirrorMetrics.incrementMlUrlsDeclined(decline.reason, decline.count)
}
- MlMirrorMetrics.observeMlUrlDomainsPerMessage(domains.size)
- if (urls.length === 0) {
+ const deduped = result.dedupedUrlCount ?? 0
+ const collected = urls.length + deduped
+ MlMirrorMetrics.observeMlUrlDomainsPerMessage(
+ result.collectedUrlDomainCount ?? new Set(urls.map(({ domain }) => domain)).size
+ )
+ if (collected === 0) {
return undefined
}
- MlMirrorMetrics.incrementMlUrlsCollected('collected', urls.length)
- MlMirrorMetrics.observeMlUrlsPerMessage(urls.length)
- return urls
+ MlMirrorMetrics.incrementMlUrlsCollected('collected', collected)
+ MlMirrorMetrics.incrementMlUrlsCollected('deduped', deduped)
+ MlMirrorMetrics.observeMlUrlsPerMessage(collected)
+ return urls.length > 0 ? urls : undefined
}
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.ts
index afadf7fd2710..b92ab3d2a921 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
@@ -6,6 +6,7 @@ import { MlImageScrubOutput } from '~/ingestion/pipelines/sessionreplay/shared/o
import { MlMirrorMetrics } from './metrics'
import { CollectedImage } from './parse-and-anonymize-step'
import { createProduceCollectedImagesStep } from './produce-collected-images-step'
+import { ProducedImageRefs } from './produced-refs'
describe('produceCollectedImagesStep', () => {
const CAPTURED_AT = 1_700_000_000_000
@@ -24,6 +25,10 @@ describe('produceCollectedImagesStep', () => {
outputs = { queueMessages } as unknown as IngestionOutputs<MlImageScrubOutput>
})
+ function createStep(producedRefCacheMax = 500_000) {
+ return createProduceCollectedImagesStep(outputs, new ProducedImageRefs(producedRefCacheMax))
+ }
+
function image(ref: string, byte = 1): CollectedImage {
return { ref, bytes: Buffer.from([byte]) }
}
@@ -41,7 +46,7 @@ describe('produceCollectedImagesStep', () => {
}
it('produces each image keyed by its ref as a side effect and strips them from the element', async () => {
- const step = createProduceCollectedImagesStep(outputs)
+ const step = createStep()
const images = [image('image:aa:h1', 1), image('image:aa:h2', 2)]
const result = await run(step, { collectedImages: images, message: { timestamp: CAPTURED_AT } })
@@ -63,14 +68,14 @@ describe('produceCollectedImagesStep', () => {
})
it('passes through elements with no collected images without producing', async () => {
- const step = createProduceCollectedImagesStep(outputs)
+ const step = createStep()
await run(step, { collectedImages: undefined, message: { timestamp: CAPTURED_AT } })
await run(step, { collectedImages: [], message: { timestamp: CAPTURED_AT } })
expect(queueMessages).not.toHaveBeenCalled()
})
it('dedups refs it already produced across messages', async () => {
- const step = createProduceCollectedImagesStep(outputs)
+ const step = createStep()
await run(step, { collectedImages: [image('image:aa:h1')], message: { timestamp: CAPTURED_AT } })
await run(step, {
collectedImages: [image('image:aa:h1'), image('image:aa:h2')],
@@ -95,7 +100,7 @@ describe('produceCollectedImagesStep', () => {
})
it('dedups a ref that another session of the team produced', async () => {
- const step = createProduceCollectedImagesStep(outputs)
+ const step = createStep()
const ref = `image:v3:42:2026-09:${'h1'.padEnd(22, 'x')}`
const sessionInput = (sessionId: string) => {
const key = {
@@ -118,7 +123,7 @@ describe('produceCollectedImagesStep', () => {
})
it('evicts oldest refs at capacity instead of forgetting the whole working set', async () => {
- const step = createProduceCollectedImagesStep(outputs, 2)
+ const step = createStep(2)
await run(step, {
collectedImages: [image('image:aa:h1'), image('image:aa:h2')],
message: { timestamp: CAPTURED_AT },
@@ -139,7 +144,7 @@ describe('produceCollectedImagesStep', () => {
it('swallows produce failures (a dangling ref reads as a placeholder downstream)', async () => {
queueMessages.mockRejectedValueOnce(new Error('broker down'))
- const step = createProduceCollectedImagesStep(outputs)
+ const step = createStep()
const result = await run(step, {
collectedImages: [image('image:aa:h1')],
message: { timestamp: CAPTURED_AT },
@@ -156,7 +161,7 @@ describe('produceCollectedImagesStep', () => {
}
const incrementVersion = jest.spyOn(MlMirrorMetrics, 'incrementMlProducedVersion')
try {
- const step = createProduceCollectedImagesStep(outputs)
+ const step = createStep()
await run(step, { collectedImages: [image('image:aa:h1')], message: { timestamp: CAPTURED_AT } })
expect(incrementVersion).toHaveBeenCalledTimes(expected)
} finally {
@@ -166,7 +171,7 @@ describe('produceCollectedImagesStep', () => {
it('un-marks refs whose produce failed so a recurring image re-produces naturally', async () => {
queueMessages.mockRejectedValueOnce(new Error('broker down'))
- const step = createProduceCollectedImagesStep(outputs)
+ const step = createStep()
await run(step, { collectedImages: [image('image:aa:h1')], message: { timestamp: CAPTURED_AT } })
await run(step, { collectedImages: [image('image:aa:h1')], message: { timestamp: CAPTURED_AT } })
expect(queueMessages).toHaveBeenCalledTimes(2)
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.ts
index 6f56b2ad12d8..31641d2cb9a3 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
@@ -4,30 +4,22 @@ import { ok } from '~/ingestion/framework/results'
import { ProcessingStep } from '~/ingestion/framework/steps'
import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'
import { ML_IMAGE_SCRUB_OUTPUT, MlImageScrubOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
-import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'
import { MlSessionKeys } from './keys/key-store'
import { mlKafkaRecord, mlWireVersion, validateImageOwner } from './keys/transport'
import { MlMirrorMetrics } from './metrics'
import { CollectedImage } from './parse-and-anonymize-step'
+import { ProducedImageRefs } from './produced-refs'
import { usesRawSessionIdentifiers } from './session-identifier-format'
-/**
- * The Rust collector only dedupes within one message, leaving this as the sole thing between a hot
- * sprite and one produce per recurrence, so capacity translates directly into scrub-topic volume: a
- * ref evicted before its next sighting is re-produced and re-scrubbed. Budget ~200 B per entry (the
- * LRU's bookkeeping dominates the ~60 B ref), so this is ~100 MB against the 8000M mirror container
- * in https://github.com/PostHog/charts/blob/main/apps/ingestion-sessionreplay-ml-mirror/values.yaml,
- * which also holds the anonymizer's packed image buffers. Overflowing it costs topic bytes rather
- * than correctness, since the consumer dedupes by ref too.
- */
-const PRODUCED_REF_CACHE_MAX = 500_000
-
/**
* Produce collected original images to the scrub topic as a fire-and-forget side effect, keyed by
* their `image:<teamId>:<hash>` ref. Delivery is deliberately not awaited and never blocks or
* fails the message: the mirrored lines already carry the refs, and a ref whose image never lands
* is defined as equivalent to a placeholder for training joins.
+ *
+ * The anonymize call already left out the refs an earlier batch produced. The claim here catches
+ * the ones that two messages of one batch share.
*/
export function createProduceCollectedImagesStep<
T extends {
@@ -37,12 +29,7 @@ export function createProduceCollectedImagesStep<
message: { timestamp?: number }
mlKeys?: MlSessionKeys
},
->(
- outputs: IngestionOutputs<MlImageScrubOutput>,
- producedRefCacheMax: number = PRODUCED_REF_CACHE_MAX
-): ProcessingStep<T, T> {
- const producedRefs = new RefDedupCache('image_scrub_producer', producedRefCacheMax)
-
+>(outputs: IngestionOutputs<MlImageScrubOutput>, producedRefs: ProducedImageRefs): ProcessingStep<T, T> {
return function produceCollectedImagesStep(input) {
const sessionId = input.headers?.session_id
const key = sessionId && usesRawSessionIdentifiers(sessionId) ? input.mlKeys?.session : undefined
@@ -51,7 +38,8 @@ export function createProduceCollectedImagesStep<
return Promise.resolve(ok(input))
}
- const fresh = images.filter((image) => !producedRefs.has(image.ref))
+ const claimed = producedRefs.claim(images.map((image) => image.ref))
+ const fresh = images.filter((_image, index) => claimed[index])
MlMirrorMetrics.incrementMlImagesCollected('deduped', images.length - fresh.length)
if (fresh.length === 0) {
return Promise.resolve(ok({ ...input, collectedImages: undefined }))
@@ -59,7 +47,6 @@ export function createProduceCollectedImagesStep<
let bytes = 0
for (const image of fresh) {
- producedRefs.add(image.ref)
bytes += image.bytes.length
}
MlMirrorMetrics.incrementMlImagesCollected('queued', fresh.length)
@@ -94,9 +81,7 @@ export function createProduceCollectedImagesStep<
// never re-thrown into the pipeline. Un-mark the refs: the same image recurring in
// a later snapshot then re-produces naturally (one attempt per recurrence, no retry
// loop), and duplicates are idempotent downstream (S3 keyed by hash).
- for (const ref of refs) {
- producedRefs.delete(ref)
- }
+ producedRefs.release(refs)
logger.warn('🖼️', 'ml_image_scrub_produce_failed', { count: refs.length, error: String(error) })
MlMirrorMetrics.incrementMlImagesCollected('produce_failed', refs.length)
if (key) {
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 4d0413df3b3c..7fdd9a5717c0 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
@@ -9,6 +9,7 @@ import { RecordedTopHogMetric, createRecordingTopHog } from '~/tests/helpers/top
import { CollectedUrl } from './parse-and-anonymize-step'
import { CollectedUrlsMessage, createProduceCollectedUrlsStep } from './produce-collected-urls-step'
+import { ProducedTransportUrls } from './produced-refs'
describe('produceCollectedUrlsStep', () => {
const TEAM_ID = '42'
@@ -31,6 +32,23 @@ describe('produceCollectedUrlsStep', () => {
topHogRecords = recordingTopHog.records
})
+ function createStep({
+ producedRefCacheMax = 500_000,
+ producedRefCacheWindowMs = 15 * 24 * 60 * 60 * 1000,
+ crawlHistory,
+ }: {
+ producedRefCacheMax?: number
+ producedRefCacheWindowMs?: number
+ crawlHistory?: Pick<CrawlHistoryStore, 'read'>
+ } = {}) {
+ return createProduceCollectedUrlsStep(
+ outputs,
+ topHog,
+ new ProducedTransportUrls(producedRefCacheMax, producedRefCacheWindowMs),
+ { crawlHistory }
+ )
+ }
+
function collected(hash: string, host: string, url: string, domain = host): CollectedUrl {
return { ref: `imageurl:${hash.padEnd(22, 'x')}`, teamId: TEAM_ID, url, host, domain }
}
@@ -97,7 +115,7 @@ describe('produceCollectedUrlsStep', () => {
// time of the replay message, not the time the mirror produced it.
jest.useFakeTimers().setSystemTime(new Date('2026-08-10T00:00:00.000Z'))
try {
- const step = createProduceCollectedUrlsStep(outputs, topHog)
+ const step = createStep()
const result = await run(step, {
message: { timestamp: CAPTURED_AT },
collectedUrls: [
@@ -143,14 +161,14 @@ describe('produceCollectedUrlsStep', () => {
})
it('passes through elements with no collected URLs without producing', async () => {
- const step = createProduceCollectedUrlsStep(outputs, topHog)
+ const step = createStep()
await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: undefined })
await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [] })
expect(queueMessages).not.toHaveBeenCalled()
})
it('dedups an identical transport URL but produces a new URL for the same ref', async () => {
- const step = createProduceCollectedUrlsStep(outputs, topHog)
+ const step = createStep()
const first = collected('h1', 'cdn.example.com', 'https://cdn.example.com/a.jpg?cb=old')
const replacement = collected('h1', 'cdn.example.com', 'https://cdn.example.com/a.jpg?cb=new')
await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [first] })
@@ -161,7 +179,7 @@ describe('produceCollectedUrlsStep', () => {
})
it('dedups an identical transport URL that another session of the team collected', async () => {
- const step = createProduceCollectedUrlsStep(outputs, topHog)
+ const step = createStep()
const url = collectedV3('h1', 'https://cdn.example.com/a.jpg')
await run(step, v3SessionInput('01a0c669-8800-7000-8000-000000000001', [url]))
@@ -191,7 +209,7 @@ describe('produceCollectedUrlsStep', () => {
],
])
)
- const step = createProduceCollectedUrlsStep(outputs, topHog, { crawlHistory: { read } })
+ const step = createStep({ crawlHistory: { read } })
await run(step, v3SessionInput('01a0c669-8800-7000-8000-000000000001', [fresh, missing]))
@@ -201,7 +219,7 @@ 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, {
+ const step = createStep({
producedRefCacheMax: 100,
producedRefCacheWindowMs: 1_000,
})
@@ -220,7 +238,7 @@ describe('produceCollectedUrlsStep', () => {
it('swallows a failed produce and un-marks its refs so a later sighting produces again', async () => {
queueMessages.mockRejectedValueOnce(new Error('broker down'))
- const step = createProduceCollectedUrlsStep(outputs, topHog)
+ const step = createStep()
const entry = collected('h1', 'cdn.example.com', 'https://cdn.example.com/a.jpg')
const result = await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [entry] })
@@ -271,7 +289,7 @@ describe('produceCollectedUrlsStep', () => {
],
])
)
- const step = createProduceCollectedUrlsStep(outputs, topHog, { crawlHistory: { read } })
+ const step = createStep({ crawlHistory: { read } })
await run(step, {
message: { timestamp: CAPTURED_AT },
@@ -291,7 +309,7 @@ describe('produceCollectedUrlsStep', () => {
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 step = createStep({ crawlHistory: { read } })
const result = await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [entry] })
@@ -304,7 +322,7 @@ describe('produceCollectedUrlsStep', () => {
['inline image', `image:${TEAM_ID}:h1xxxxxxxxxxxxxxxxxxxx`],
['legacy team-scoped URL', `imageurl:${'a'.repeat(32)}:h1xxxxxxxxxxxxxxxxxxxx`],
])('refuses to produce a %s ref', async (_name, ref) => {
- const step = createProduceCollectedUrlsStep(outputs, topHog, { producedRefCacheMax: 100 })
+ const step = createStep({ producedRefCacheMax: 100 })
await run(step, {
message: { timestamp: CAPTURED_AT },
@@ -324,7 +342,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, { producedRefCacheMax: 100 })
+ const step = createStep({ producedRefCacheMax: 100 })
await run(step, {
message: { timestamp: CAPTURED_AT },
@@ -352,7 +370,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, { producedRefCacheMax: 100_000 })
+ const step = createStep({ 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`)
)
@@ -365,7 +383,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, { producedRefCacheMax: 100_000 })
+ const step = createStep({ 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`)
)
@@ -380,7 +398,7 @@ describe('produceCollectedUrlsStep', () => {
})
it('splits when the urls are long enough to fill a record', async () => {
- const step = createProduceCollectedUrlsStep(outputs, topHog, { producedRefCacheMax: 100_000 })
+ const step = createStep({ 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`)
@@ -397,7 +415,7 @@ describe('produceCollectedUrlsStep', () => {
})
it('drops an entry whose ref names another team', async () => {
- const step = createProduceCollectedUrlsStep(outputs, topHog, { producedRefCacheMax: 100 })
+ const step = createStep({ producedRefCacheMax: 100 })
const otherTeam = 'b'.repeat(32)
await run(step, {
@@ -423,7 +441,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, { producedRefCacheMax: 100 })
+ const step = createStep({ 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 fac1817c66ab..af6227b5a982 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
@@ -1,5 +1,3 @@
-import { createHash } from 'node:crypto'
-
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { logger } from '~/common/utils/logger'
import { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'
@@ -9,24 +7,14 @@ import type { CrawlHistoryStore } from '~/ingestion/pipelines/sessionreplay/ml-m
import { parseImageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'
import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'
import { ML_IMAGE_FETCH_OUTPUT, MlImageFetchOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
-import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'
import { MlSessionKeys } from './keys/key-store'
import { mlKafkaRecord, mlWireVersion, validateImageOwner } from './keys/transport'
import { MlMirrorMetrics } from './metrics'
import { CollectedUrl } from './parse-and-anonymize-step'
+import { ProducedTransportUrls } from './produced-refs'
import { usesRawSessionIdentifiers } from './session-identifier-format'
-/**
- * The same trade as the image lane's cache, at a much lower cost per entry: a record here holds a
- * digest of the ref and transport URL, with no image bytes or original URL. An entry that this
- * cache drops before its next arrival produces a second time, which costs topic volume and one
- * more ledger read in the fetcher, but never correctness. Time-bucketed keys also make an entry
- * eligible again before crawl history expires, so a mutable URL is recrawled.
- */
-const PRODUCED_REF_CACHE_MAX = 500_000
-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
@@ -63,41 +51,24 @@ export interface CollectedUrlsMessage {
}
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)
- .update('\0')
- .update(entry.url)
- .update('\0')
- .update(String(timeBucket))
- .digest('base64url')
-}
-
async function excludeFreshCrawlHistory(
- candidates: CachedCollectedUrl[],
+ candidates: CollectedUrl[],
crawlHistory: Pick<CrawlHistoryStore, 'read'> | undefined,
nowMs: number,
onError: (error: unknown, count: number) => void
-): Promise<CachedCollectedUrl[]> {
+): Promise<CollectedUrl[]> {
if (!crawlHistory) {
return candidates
}
const startedAt = performance.now()
try {
- const refs = [...new Set(candidates.map(({ entry }) => entry.ref))]
+ const refs = [...new Set(candidates.map((entry) => entry.ref))]
const stored = await crawlHistory.read(refs)
- const publishable = candidates.filter(({ entry }) => {
+ const publishable = candidates.filter((entry) => {
const history = stored.get(entry.ref)
return history?.kind !== 'url' || history.nextFetchAtMs <= nowMs
})
@@ -150,17 +121,10 @@ export function createProduceCollectedUrlsStep<
>(
outputs: IngestionOutputs<MlImageFetchOutput>,
topHog: TopHogRegistry,
+ producedUrls: ProducedTransportUrls,
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}`)
- }
- const producedTransportUrls = new RefDedupCache('image_fetch_producer', producedRefCacheMax)
+ const { crawlHistory } = options
const producedUrlsByRegistrableDomain = topHog.registerSum('ml_image_fetch_produced_urls_by_registrable_domain', {
topN: TOP_REGISTRABLE_DOMAINS,
maxKeys: MAX_TRACKED_REGISTRABLE_DOMAINS,
@@ -176,19 +140,6 @@ export function createProduceCollectedUrlsStep<
return ok(input)
}
- 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))
- MlMirrorMetrics.incrementMlUrlsCollected('deduped', collected.length - fresh.length)
- if (fresh.length === 0) {
- return ok({ ...input, collectedUrls: undefined })
- }
-
// Each entry is checked, not just the first. A `bytes` ref names an image the page
// inlined, and its hash can never be reproduced from a URL, so a record carrying one
// reaches the fetcher under a hash nothing will ever match. Both kinds parse, so only
@@ -197,10 +148,9 @@ export function createProduceCollectedUrlsStep<
// Every entry must use the global URL-ref shape and carry the same team ID. One
// replay message belongs to one team, and a record stamped with another team's ID is
// a tenant-attribution error that nothing downstream can detect.
- const usable: typeof fresh = []
+ const usable: CollectedUrl[] = []
let teamId: string | undefined
- for (const candidate of fresh) {
- const { entry } = candidate
+ for (const entry of collected) {
validateImageOwner(entry.ref, key)
const parsed = parseImageRef(entry.ref)
if (
@@ -212,9 +162,9 @@ export function createProduceCollectedUrlsStep<
continue
}
teamId ??= entry.teamId
- usable.push(candidate)
+ usable.push(entry)
}
- const unusable = fresh.length - usable.length
+ const unusable = collected.length - usable.length
if (unusable > 0) {
MlMirrorMetrics.incrementMlUrlsCollected('ref_unusable', unusable)
// Warn, not error: this is per replay message, so an addon-side format drift would
@@ -225,10 +175,15 @@ export function createProduceCollectedUrlsStep<
return ok({ ...input, collectedUrls: undefined })
}
- for (const { cacheKey } of usable) {
- producedTransportUrls.add(cacheKey)
+ const nowMs = Date.now()
+ const claimed = producedUrls.claim(usable, nowMs)
+ const fresh = usable.filter((_entry, index) => claimed[index])
+ MlMirrorMetrics.incrementMlUrlsCollected('deduped', usable.length - fresh.length)
+ if (fresh.length === 0) {
+ return ok({ ...input, collectedUrls: undefined })
}
- const publishable = await excludeFreshCrawlHistory(usable, crawlHistory, nowMs, (error, count) => {
+
+ const publishable = await excludeFreshCrawlHistory(fresh, crawlHistory, nowMs, (error, count) => {
if (nowMs < nextCrawlHistoryWarningAtMs) {
return
}
@@ -242,7 +197,7 @@ export function createProduceCollectedUrlsStep<
const messageTimestamp = input.message.timestamp
const firstSeenAtMs = messageTimestamp !== undefined && messageTimestamp > 0 ? messageTimestamp : nowMs
const byDomain = new Map<string, FrontierJob[]>()
- for (const { entry } of publishable) {
+ for (const entry of publishable) {
const group = byDomain.get(entry.domain)
const record: FrontierJob = {
...(key ? { sessionId } : {}),
@@ -284,34 +239,32 @@ export function createProduceCollectedUrlsStep<
// The fetch consumer counts records, so the producer counts records too and the two rates compare.
const recordCount = messages.length
- // 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 = publishable.map(({ cacheKey }) => cacheKey)
+ // The ack handlers hold counts per domain rather than the jobs, so a produce that is not yet
+ // delivered keeps only the URLs its failure path must release.
+ const producedByDomain = [...byDomain].map(([domain, jobs]) => [domain, jobs.length] as const)
const produce = outputs
.queueMessages(ML_IMAGE_FETCH_OUTPUT, messages)
.then(() => {
// queueMessages resolves on the delivery acks, so `produced` counts what landed.
- MlMirrorMetrics.incrementMlUrlsCollected('produced', producedCacheKeys.length)
+ MlMirrorMetrics.incrementMlUrlsCollected('produced', publishable.length)
MlMirrorMetrics.incrementMlProducedVersion('url', mlWireVersion(key), recordCount)
- for (const [registrableDomain, jobs] of byDomain) {
- producedUrlsByRegistrableDomain.record({ registrable_domain: registrableDomain }, jobs.length)
+ for (const [registrableDomain, count] of producedByDomain) {
+ producedUrlsByRegistrableDomain.record({ registrable_domain: registrableDomain }, count)
}
- producedUrlsTotal.record({}, producedCacheKeys.length)
+ producedUrlsTotal.record({}, publishable.length)
})
.catch((error) => {
// A dangling ref renders as a placeholder, so a failed produce is logged and never
// thrown back into the pipeline. Un-mark the cache entries: the same image in a later
// snapshot then produces again, one attempt for each recurrence and no retry loop.
// A duplicate costs the fetcher one ledger read, because the ledger is keyed by ref.
- for (const cacheKey of producedCacheKeys) {
- producedTransportUrls.delete(cacheKey)
- }
+ producedUrls.release(publishable, nowMs)
logger.warn('🌐', 'ml_image_fetch_produce_failed', {
- count: producedCacheKeys.length,
- domains: byDomain.size,
+ count: publishable.length,
+ domains: producedByDomain.length,
error: String(error),
})
- MlMirrorMetrics.incrementMlUrlsCollected('produce_failed', producedCacheKeys.length)
+ MlMirrorMetrics.incrementMlUrlsCollected('produce_failed', publishable.length)
if (key) {
throw error
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produced-refs.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produced-refs.ts
new file mode 100644
index 000000000000..18fc89b57e80
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produced-refs.ts
@@ -0,0 +1,97 @@
+import type { ProducedRefDedup, RefDedupCache } from '@posthog/replay-anonymizer'
+
+import { registerNativeRefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'
+
+import { getRustAnonymizer } from './rust-anonymizer'
+
+function nativeRefDedupCache(name: string, max: number): RefDedupCache {
+ const cache = new (getRustAnonymizer().RefDedupCache)(max)
+ registerNativeRefDedupCache(name, max, () => cache.stats())
+ return cache
+}
+
+/**
+ * The image refs this process already produced to the scrub topic.
+ *
+ * The Rust collector only dedups within one message, leaving this as the sole thing between a hot
+ * sprite and one produce per recurrence, so capacity translates directly into scrub-topic volume: a
+ * ref evicted before its next sighting is re-produced and re-scrubbed. Overflowing it costs topic
+ * bytes rather than correctness, since the consumer dedupes by ref too.
+ */
+export class ProducedImageRefs {
+ readonly cache: RefDedupCache
+
+ constructor(max: number) {
+ this.cache = nativeRefDedupCache('image_scrub_producer', max)
+ }
+
+ claim(refs: string[]): boolean[] {
+ return this.cache.claimRefs(refs)
+ }
+
+ release(refs: string[]): void {
+ this.cache.releaseRefs(refs)
+ }
+}
+
+export interface TransportUrl {
+ ref: string
+ url: string
+}
+
+/**
+ * The transport URLs this process already produced to the fetch topic. An entry that this cache
+ * drops before its next arrival produces a second time, which costs topic volume and one more
+ * ledger read in the fetcher, but never correctness. Time-bucketed keys also make an entry
+ * eligible again before crawl history expires, so a mutable URL is recrawled.
+ */
+export class ProducedTransportUrls {
+ readonly cache: RefDedupCache
+
+ constructor(
+ max: number,
+ private readonly windowMs: number
+ ) {
+ if (!Number.isSafeInteger(windowMs) || windowMs <= 0) {
+ throw new Error(`produced URL cache window must be a positive safe integer, got ${windowMs}`)
+ }
+ this.cache = nativeRefDedupCache('image_fetch_producer', max)
+ }
+
+ timeBucket(nowMs: number): number {
+ return Math.floor(nowMs / this.windowMs)
+ }
+
+ claim(urls: TransportUrl[], nowMs: number): boolean[] {
+ return this.cache.claimTransportUrls(
+ urls.map(({ ref }) => ref),
+ urls.map(({ url }) => url),
+ this.timeBucket(nowMs)
+ )
+ }
+
+ /** `nowMs` must be the value the claim used, so the release finds the same time bucket. */
+ release(urls: TransportUrl[], nowMs: number): void {
+ this.cache.releaseTransportUrls(
+ urls.map(({ ref }) => ref),
+ urls.map(({ url }) => url),
+ this.timeBucket(nowMs)
+ )
+ }
+}
+
+export interface ProducedRefs {
+ images?: ProducedImageRefs
+ urls?: ProducedTransportUrls
+}
+
+export function producedRefDedup(producedRefs: ProducedRefs | undefined, nowMs: number): ProducedRefDedup | undefined {
+ if (!producedRefs?.images && !producedRefs?.urls) {
+ return undefined
+ }
+ return {
+ images: producedRefs.images?.cache,
+ urls: producedRefs.urls?.cache,
+ urlTimeBucket: producedRefs.urls?.timeBucket(nowMs),
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/rust-anonymizer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/rust-anonymizer.ts
new file mode 100644
index 000000000000..cbf6906f31ef
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/rust-anonymizer.ts
@@ -0,0 +1,12 @@
+type RustAnonymizer = typeof import('@posthog/replay-anonymizer')
+
+let rustAnonymizer: RustAnonymizer | undefined
+
+// Lazily loaded so deployments that never run the mirror don't pay the native-module load (and so a
+// missing addon only breaks the native path, not every import of this module).
+export function getRustAnonymizer(): RustAnonymizer {
+ if (!rustAnonymizer) {
+ rustAnonymizer = require('@posthog/replay-anonymizer') as RustAnonymizer
+ }
+ return rustAnonymizer
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts
index 73e3b4030c87..c3905fc06895 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts
@@ -323,7 +323,7 @@ describeAddon('native image collection', () => {
const PSEUDO_TEAM = '0123456789abcdef0123456789abcdef'
const CONTENT_KEY = 'fedcba9876543210fedcba9876543210'
- function imagePayload(): Buffer {
+ function imagePayload(remoteImageUrls: string[] = []): Buffer {
const inner = JSON.stringify({
event: '$snapshot_items',
properties: {
@@ -341,6 +341,12 @@ describeAddon('native image collection', () => {
attributes: { src: `data:image/png;base64,${PNG_B64}` },
childNodes: [],
},
+ ...remoteImageUrls.map((src) => ({
+ type: 2,
+ tagName: 'img',
+ attributes: { src },
+ childNodes: [],
+ })),
],
},
initialOffset: { top: 0, left: 0 },
@@ -384,6 +390,50 @@ describeAddon('native image collection', () => {
}
)
+ it('leaves out what an earlier message produced, and still writes those refs into the lines', async () => {
+ // The produce steps claim with refs that JS builds, and the addon drops with refs it builds
+ // itself. If the two ever disagree, nothing is dropped and every duplicate crosses into JS.
+ rustAddon!.initAnonymizer({ text: [], url: [] })
+ const namespace = 'v3:42:2026-09'
+ const producedRefDedup = {
+ images: new rustAddon!.RefDedupCache(10),
+ urls: new rustAddon!.RefDedupCache(10),
+ urlTimeBucket: 7,
+ }
+ const anonymize = () =>
+ rustAddon!.anonymizeKafkaPayload(
+ imagePayload(['https://cdn.example.com/a.png']),
+ undefined,
+ namespace,
+ CONTENT_KEY,
+ 'url-key',
+ namespace,
+ producedRefDedup
+ )
+
+ const first = await anonymize()
+ const firstMeta = parseJSON(first.meta!) as { urls?: { hash: string; url: string }[] }
+ expect(firstMeta.urls).toHaveLength(1)
+ const imageRefs = [imageRef(namespace, hashImageBytes(CONTENT_KEY, Buffer.from(PNG_B64, 'base64')))]
+ const urlRefs = firstMeta.urls!.map(({ hash }) => `imageurl:${namespace}:${hash}`)
+ const urls = firstMeta.urls!.map(({ url }) => url)
+ // The anonymize call only reads the caches, so the first message's refs are still unclaimed.
+ expect(producedRefDedup.images.claimRefs(imageRefs)).toEqual([true])
+ expect(producedRefDedup.urls.claimTransportUrls(urlRefs, urls, 7)).toEqual([true])
+
+ const second = await anonymize()
+ expect(second).toMatchObject({
+ failed: false,
+ images: null,
+ dedupedImageCount: 1,
+ dedupedUrlCount: 1,
+ collectedUrlDomainCount: 1,
+ })
+ expect((parseJSON(second.meta!) as { urls?: unknown[] }).urls).toBeUndefined()
+ expect(second.lines!.toString()).toContain(imageRefs[0])
+ expect(second.lines!.toString()).toContain(urlRefs[0])
+ })
+
it('collects nothing without the collection keys and blurs inline instead', async () => {
rustAddon!.initAnonymizer({ text: [], url: [] })
const result = await rustAddon!.anonymizeKafkaPayload(imagePayload())
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache.test.ts
index e15b3135ffcc..0943d2eb84dc 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache.test.ts
@@ -1,6 +1,6 @@
import { Counter, register } from 'prom-client'
-import { RefDedupCache } from './ref-dedup-cache'
+import { RefDedupCache, registerNativeRefDedupCache } from './ref-dedup-cache'
describe('RefDedupCache', () => {
async function probe(cache: string, verdict: 'would_hit' | 'would_miss'): Promise<number> {
@@ -58,6 +58,20 @@ describe('RefDedupCache', () => {
expect(() => new RefDedupCache('test_validation', max)).toThrow(/test_validation ref cache max/)
})
+ it('reports the running totals of a native cache once, however often it is scraped', async () => {
+ // The addon keeps running totals, and the counter is fed what grew since the last scrape. A
+ // counter fed the whole total on every scrape would grow with the scrape count instead.
+ const name = 'test_native_totals'
+ const stats = { entries: 3, evictions: 0, wouldHit: 1, wouldMiss: 2 }
+ registerNativeRefDedupCache(name, 10, () => stats)
+
+ expect(await probe(name, 'would_hit')).toBe(1)
+ expect(await probe(name, 'would_miss')).toBe(2)
+ stats.wouldMiss = 5
+ expect(await probe(name, 'would_hit')).toBe(1)
+ expect(await probe(name, 'would_miss')).toBe(5)
+ })
+
it('does not probe while the cache still has room, so an unfilled cache reads as sized correctly', async () => {
// Evictions are the only thing that can put a ref in the ghost list, so a cache that never
// fills must report no would_hit at all rather than blaming capacity for ordinary misses.
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache.ts
index 8bc7e79a4f00..f71d8d8077f3 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache.ts
@@ -8,20 +8,53 @@ import { Counter, Gauge } from 'prom-client'
*/
const GHOST_SAMPLE_RATE = 16
+export interface NativeRefDedupCacheStats {
+ entries: number
+ evictions: number
+ wouldHit: number
+ wouldMiss: number
+}
+
+interface NativeCacheSource {
+ stats: () => NativeRefDedupCacheStats
+ reported: Omit<NativeRefDedupCacheStats, 'entries'>
+}
+
+/** Native caches count on their side of the FFI. Scrapes add what they counted since the last scrape. */
+const nativeCaches = new Map<string, NativeCacheSource>()
+
+function reportNativeTotal(
+ field: keyof NativeCacheSource['reported'],
+ inc: (name: string, value: number) => void
+): void {
+ for (const [name, source] of nativeCaches) {
+ const total = source.stats()[field]
+ inc(name, total - source.reported[field])
+ source.reported[field] = total
+ }
+}
+
const evictionsTotal = new Counter({
name: 'ml_mirror_ref_cache_evictions_total',
help: 'Refs dropped from a dedup cache to make room for newer ones',
labelNames: ['cache'],
+ collect() {
+ reportNativeTotal('evictions', (name, value) => this.labels(name).inc(value))
+ },
})
const capacityProbeTotal = new Counter({
name: 'ml_mirror_ref_cache_capacity_probe_total',
help: 'Sampled cache misses split by whether the ref was evicted recently enough that twice the capacity would still hold it. would_hit / (would_hit + would_miss) is the share of misses that doubling the cache would recover, so a value near zero means the cache is big enough and a high value means it is undersized',
labelNames: ['cache', 'verdict'],
+ collect() {
+ reportNativeTotal('wouldHit', (name, value) => this.labels(name, 'would_hit').inc(value))
+ reportNativeTotal('wouldMiss', (name, value) => this.labels(name, 'would_miss').inc(value))
+ },
})
/** Read at scrape time by the entries gauge, which keeps the hot path free of a gauge write per ref. */
-const liveCaches = new Map<string, RefDedupCache>()
+const liveCaches = new Map<string, { readonly size: number }>()
// Never referenced again: constructing it registers it, and it pulls its own values at scrape time.
new Gauge({
@@ -41,6 +74,27 @@ const capacityGauge = new Gauge({
labelNames: ['cache'],
})
+function validateRefCacheMax(name: string, max: number): void {
+ // These arrive from env, where `overrideConfigWithEnv` parseFloats whatever it is given: the
+ // source default is written `1_000_000`, which parses to 1, and a typo parses to NaN. Both
+ // reach the cache as a `max` it rejects with an error naming neither the knob nor the cache.
+ if (!Number.isInteger(max) || max < 0) {
+ throw new Error(`${name} ref cache max must be 0 or a positive integer, got ${max}`)
+ }
+}
+
+/** The addon keeps the ghost list and the counters, so the metrics pull them at scrape time. */
+export function registerNativeRefDedupCache(name: string, max: number, stats: () => NativeRefDedupCacheStats): void {
+ validateRefCacheMax(name, max)
+ nativeCaches.set(name, { stats, reported: { evictions: 0, wouldHit: 0, wouldMiss: 0 } })
+ liveCaches.set(name, {
+ get size() {
+ return stats().entries
+ },
+ })
+ capacityGauge.labels(name).set(max)
+}
+
/** Independent of the ref format, so a change to how refs are built cannot skew which ones are sampled. */
function sampleBucket(ref: string): number {
let hash = 0x811c9dc5
@@ -68,12 +122,7 @@ export class RefDedupCache {
max: number,
private readonly ghostSampleRate: number = GHOST_SAMPLE_RATE
) {
- // These arrive from env, where `overrideConfigWithEnv` parseFloats whatever it is given: the
- // source default is written `1_000_000`, which parses to 1, and a typo parses to NaN. Both
- // reach lru-cache as a `max` it rejects with an error naming neither the knob nor the cache.
- if (!Number.isInteger(max) || max < 0) {
- throw new Error(`${name} ref cache max must be 0 or a positive integer, got ${max}`)
- }
+ validateRefCacheMax(name, max)
liveCaches.set(name, this)
capacityGauge.labels(name).set(max)
if (max === 0) {
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 02816655c4bd..ce8c171f36ec 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -10624,10 +10624,12 @@ checksum = "51743d3e274e2b18df81c4dc6caf8a5b8e15dbe799e0dca05c7617380094e884"
name = "replay-anonymizer-node"
version = "0.0.1"
dependencies = [
+ "lru",
"neon",
"posthog-replay-anonymizer",
"serde",
"serde_json",
+ "sha2 0.10.9",
]
[[package]]
diff --git a/rust/replay-anonymizer-node/Cargo.toml b/rust/replay-anonymizer-node/Cargo.toml
index 1ab16166ee66..854f610e5a38 100644
--- a/rust/replay-anonymizer-node/Cargo.toml
+++ b/rust/replay-anonymizer-node/Cargo.toml
@@ -15,5 +15,7 @@ crate-type = ["cdylib"]
neon = { workspace = true, features = ["external-buffers"] }
# default-features = false: the offline typed-parse module has no place in the ingestion cdylib.
posthog-replay-anonymizer = { path = "../replay-anonymizer", default-features = false }
+lru = "0.12"
serde = { workspace = true }
serde_json = { workspace = true }
+sha2 = { workspace = true }
diff --git a/rust/replay-anonymizer-node/src/dedup.rs b/rust/replay-anonymizer-node/src/dedup.rs
new file mode 100644
index 000000000000..52e408ef23d5
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/dedup.rs
@@ -0,0 +1,245 @@
+//! Cross-message dedup of the refs the ML mirror produces to the scrub and fetch topics.
+//!
+//! The cache lives outside the V8 heap, because hundreds of thousands of small entries held there
+//! add marking work to every major GC.
+
+use std::num::NonZeroUsize;
+use std::sync::{Mutex, MutexGuard};
+
+use lru::LruCache;
+use sha2::{Digest, Sha256};
+
+/// A ghost hit means a cache of twice the capacity would still have held the ref. Sampling one
+/// eviction in this many keeps the ghost list near 6% of the cache's own memory.
+const GHOST_SAMPLE_RATE: u32 = 16;
+
+/// A truncated SHA-256. At a million live entries the chance of any collision is near 2^-88.
+pub type DedupKey = [u8; 16];
+
+fn digest(parts: &[&[u8]]) -> DedupKey {
+ let mut hasher = Sha256::new();
+ for part in parts {
+ hasher.update(part);
+ }
+ let full = hasher.finalize();
+ let mut key = [0u8; 16];
+ key.copy_from_slice(&full[..16]);
+ key
+}
+
+pub fn image_ref_key(reference: &str) -> DedupKey {
+ digest(&[reference.as_bytes()])
+}
+
+/// A transport URL dedups per ref, per URL and per time bucket. A new bucket makes the URL
+/// eligible again, so a mutable image is recrawled before its crawl history expires.
+pub fn transport_url_key(reference: &str, url: &str, time_bucket: u64) -> DedupKey {
+ digest(&[
+ reference.as_bytes(),
+ b"\0",
+ url.as_bytes(),
+ b"\0",
+ &time_bucket.to_le_bytes(),
+ ])
+}
+
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
+pub struct DedupStats {
+ pub entries: u64,
+ pub evictions: u64,
+ /// Sampled misses on a ref that a cache of twice the capacity would still have held.
+ pub would_hit: u64,
+ pub would_miss: u64,
+}
+
+struct State {
+ cache: LruCache<DedupKey, ()>,
+ ghost: LruCache<DedupKey, ()>,
+ evictions: u64,
+ would_hit: u64,
+ would_miss: u64,
+}
+
+impl State {
+ fn probe_miss(&mut self, key: &DedupKey) {
+ if !is_sampled(key) {
+ return;
+ }
+ // pop, not get: a ghost entry that renewed its own recency would score would_hit forever.
+ if self.ghost.pop(key).is_some() {
+ self.would_hit += 1;
+ } else {
+ self.would_miss += 1;
+ }
+ }
+
+ fn claim(&mut self, key: DedupKey) -> bool {
+ if self.cache.get(&key).is_some() {
+ return false;
+ }
+ self.probe_miss(&key);
+ if let Some((evicted, ())) = self.cache.push(key, ()) {
+ self.evictions += 1;
+ if is_sampled(&evicted) {
+ self.ghost.put(evicted, ());
+ }
+ }
+ true
+ }
+}
+
+fn is_sampled(key: &DedupKey) -> bool {
+ u32::from_le_bytes([key[0], key[1], key[2], key[3]]).is_multiple_of(GHOST_SAMPLE_RATE)
+}
+
+/// An LRU of refs already produced. A capacity of 0 disables dedup, so every ref produces.
+pub struct RefDedupCache {
+ state: Option<Mutex<State>>,
+}
+
+impl RefDedupCache {
+ pub fn new(capacity: usize) -> Self {
+ let state = NonZeroUsize::new(capacity).map(|capacity| {
+ let ghost_capacity = NonZeroUsize::new(capacity.get() / GHOST_SAMPLE_RATE as usize)
+ .unwrap_or(NonZeroUsize::MIN);
+ Mutex::new(State {
+ cache: LruCache::new(capacity),
+ ghost: LruCache::new(ghost_capacity),
+ evictions: 0,
+ would_hit: 0,
+ would_miss: 0,
+ })
+ });
+ Self { state }
+ }
+
+ fn lock(&self) -> Option<MutexGuard<'_, State>> {
+ // A poisoned lock only means another thread panicked mid-update, and the LRU is still valid.
+ self.state.as_ref().map(|state| {
+ state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ })
+ }
+
+ /// Keeps the items whose key is not cached, without marking them, and returns how many it
+ /// dropped. A cached key gets renewed recency, so a ref that keeps recurring stays cached.
+ pub fn retain_absent<T>(&self, items: &mut Vec<T>, key_of: impl Fn(&T) -> DedupKey) -> usize {
+ if self.state.is_none() {
+ return 0;
+ }
+ // The event loop's claims wait on this lock, so the hashing happens before it is taken.
+ let keys: Vec<DedupKey> = items.iter().map(key_of).collect();
+ let absent: Vec<bool> = match self.lock() {
+ Some(mut state) => keys
+ .iter()
+ .map(|key| state.cache.get(key).is_none())
+ .collect(),
+ None => return 0,
+ };
+ let before = items.len();
+ let mut absent = absent.into_iter();
+ items.retain(|_| absent.next().unwrap_or(true));
+ before - items.len()
+ }
+
+ pub fn claim(&self, keys: &[DedupKey]) -> Vec<bool> {
+ match self.lock() {
+ Some(mut state) => keys.iter().map(|key| state.claim(*key)).collect(),
+ None => vec![true; keys.len()],
+ }
+ }
+
+ pub fn release(&self, keys: &[DedupKey]) {
+ if let Some(mut state) = self.lock() {
+ for key in keys {
+ state.cache.pop(key);
+ }
+ }
+ }
+
+ pub fn stats(&self) -> DedupStats {
+ self.lock()
+ .map_or_else(DedupStats::default, |state| DedupStats {
+ entries: state.cache.len() as u64,
+ evictions: state.evictions,
+ would_hit: state.would_hit,
+ would_miss: state.would_miss,
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn key(n: u32) -> DedupKey {
+ image_ref_key(&format!("image:1:{n}"))
+ }
+
+ #[test]
+ fn claims_a_key_once_until_released() {
+ let cache = RefDedupCache::new(10);
+ assert_eq!(cache.claim(&[key(1), key(1)]), vec![true, false]);
+ assert_eq!(cache.claim(&[key(1)]), vec![false]);
+ cache.release(&[key(1)]);
+ assert_eq!(cache.claim(&[key(1)]), vec![true]);
+ }
+
+ #[test]
+ fn retain_absent_filters_without_marking() {
+ let cache = RefDedupCache::new(10);
+ cache.claim(&[key(1)]);
+ let mut items = vec![1, 2, 3];
+ assert_eq!(cache.retain_absent(&mut items, |n| key(*n)), 1);
+ assert_eq!(items, vec![2, 3]);
+ assert_eq!(cache.claim(&[key(2)]), vec![true]);
+ }
+
+ #[test]
+ fn evicts_the_least_recently_used_key() {
+ let cache = RefDedupCache::new(2);
+ cache.claim(&[key(1), key(2)]);
+ let mut renewed = vec![1];
+ cache.retain_absent(&mut renewed, |n| key(*n));
+ cache.claim(&[key(3)]);
+ assert_eq!(cache.claim(&[key(1), key(2)]), vec![false, true]);
+ assert_eq!(cache.stats().evictions, 2);
+ }
+
+ #[test]
+ fn zero_capacity_produces_every_ref() {
+ let cache = RefDedupCache::new(0);
+ assert_eq!(cache.claim(&[key(1), key(1)]), vec![true, true]);
+ let mut items = vec![1];
+ assert_eq!(cache.retain_absent(&mut items, |n| key(*n)), 0);
+ assert_eq!(cache.stats(), DedupStats::default());
+ }
+
+ #[test]
+ fn a_sampled_miss_on_a_recent_eviction_scores_would_hit_once() {
+ let sampled = (0..).map(key).find(is_sampled).unwrap();
+ let fillers: Vec<DedupKey> = (100_000..)
+ .map(key)
+ .filter(|k| !is_sampled(k))
+ .take(16)
+ .collect();
+ let cache = RefDedupCache::new(16);
+ cache.claim(&[sampled]);
+ cache.claim(&fillers);
+ cache.claim(&[sampled]);
+ cache.release(&[sampled]);
+ cache.claim(&[sampled]);
+ let stats = cache.stats();
+ assert_eq!(stats.would_hit, 1);
+ assert_eq!(stats.would_miss, 2);
+ }
+
+ #[test]
+ fn transport_url_keys_differ_by_time_bucket() {
+ assert_ne!(
+ transport_url_key("imageurl:a", "https://example.com/a.png", 1),
+ transport_url_key("imageurl:a", "https://example.com/a.png", 2)
+ );
+ }
+}
diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.ts
index a28cf457e170..cba2ffbfbba8 100644
--- a/rust/replay-anonymizer-node/src/index.ts
+++ b/rust/replay-anonymizer-node/src/index.ts
@@ -127,6 +127,59 @@ export interface AnonymizeKafkaPayloadResult {
timings: AnonymizeTimings | null
/** Original bytes of the collected images, concatenated in `meta.images` order; null when none. */
images: Buffer | null
+ dedupedImageCount?: number
+ dedupedUrlCount?: number
+ /** Distinct registrable domains among the collected URLs, counted before the dedup drop. */
+ collectedUrlDomainCount?: number
+}
+
+export interface RefDedupCacheStats {
+ entries: number
+ evictions: number
+ /** Sampled misses on a ref that a cache of twice the capacity would still have held. */
+ wouldHit: number
+ wouldMiss: number
+}
+
+/** The entries live outside the V8 heap, so a full cache adds nothing for a major GC to mark. A capacity of 0 turns dedup off. */
+export class RefDedupCache {
+ /** The addon's handle. Only this package reads it. */
+ readonly nativeHandle: unknown
+
+ constructor(capacity: number) {
+ this.nativeHandle = native.refDedupCacheNew(capacity)
+ }
+
+ claimRefs(refs: string[]): boolean[] {
+ return native.refDedupCacheClaimRefs(this.nativeHandle, refs)
+ }
+
+ releaseRefs(refs: string[]): void {
+ native.refDedupCacheReleaseRefs(this.nativeHandle, refs)
+ }
+
+ claimTransportUrls(refs: string[], urls: string[], timeBucket: number): boolean[] {
+ return native.refDedupCacheClaimTransportUrls(this.nativeHandle, refs, urls, timeBucket)
+ }
+
+ releaseTransportUrls(refs: string[], urls: string[], timeBucket: number): void {
+ native.refDedupCacheReleaseTransportUrls(this.nativeHandle, refs, urls, timeBucket)
+ }
+
+ stats(): RefDedupCacheStats {
+ return native.refDedupCacheStats(this.nativeHandle)
+ }
+}
+
+/**
+ * The produce lanes' caches, consulted inside the anonymize call without marking. An image or URL
+ * whose ref the cache holds is left out of the result, so it never reaches the JS heap. The caller
+ * still claims what comes back before it produces.
+ */
+export interface ProducedRefDedup {
+ images?: RefDedupCache
+ urls?: RefDedupCache
+ urlTimeBucket?: number
}
/** Initialize the process-wide allow lists. Call once at startup before {@link anonymizeKafkaPayload}. */
@@ -155,6 +208,8 @@ export function initAnonymizer(allow: AllowListsInput): void {
* `imageurl:<hash>`. For v2, pass `v2:<raw team id>:<YYYY-MM>` as both `teamId` and `referenceNamespace`.
*
* The two lanes are independent: either, both, or neither. Only `contentKey` needs `teamId`.
+ *
+ * `producedRefDedup` leaves out the collected images and URLs that an earlier message already produced.
*/
export async function anonymizeKafkaPayload(
payload: Buffer,
@@ -162,7 +217,8 @@ export async function anonymizeKafkaPayload(
teamId?: string | null,
contentKey?: string | null,
urlKey?: string | null,
- referenceNamespace?: string | null
+ referenceNamespace?: string | null,
+ producedRefDedup?: ProducedRefDedup
): Promise<AnonymizeKafkaPayloadResult> {
const result = await native.anonymizeKafkaPayload(
payload,
@@ -170,7 +226,10 @@ export async function anonymizeKafkaPayload(
teamId ?? undefined,
contentKey ?? undefined,
urlKey ?? undefined,
- referenceNamespace ?? undefined
+ referenceNamespace ?? undefined,
+ producedRefDedup?.images?.nativeHandle,
+ producedRefDedup?.urls?.nativeHandle,
+ producedRefDedup?.urlTimeBucket
)
// Timings are best-effort telemetry: a malformed timings blob must never fail the message.
let timings: AnonymizeTimings | null = null
@@ -243,7 +302,11 @@ export type UrlPolicyVerdict =
export function tryCanonicalizeUrl(url: string): UrlPolicyVerdict {
const result = native.tryCanonicalizeUrl(url)
if (typeof result.decline === 'string') {
- return { ok: false, decline: result.decline, unwanted: result.unwanted === true }
+ return {
+ ok: false,
+ decline: result.decline,
+ unwanted: result.unwanted === true,
+ }
}
return { ok: true, url: result }
}
diff --git a/rust/replay-anonymizer-node/src/lib.rs b/rust/replay-anonymizer-node/src/lib.rs
index 15253c968fee..ea5e33a70847 100644
--- a/rust/replay-anonymizer-node/src/lib.rs
+++ b/rust/replay-anonymizer-node/src/lib.rs
@@ -8,16 +8,22 @@
//! `tests/fixtures/`, which the Jest suite runs against through this addon.
//!
//! It also carries the image-scrub sidecar's pixel layout conversions (`pixels`), which fill model
-//! inputs in place in typed arrays that the sidecar allocates.
+//! inputs in place in typed arrays that the sidecar allocates, and the produce lanes' ref dedup
+//! caches (`dedup`), which hold their entries outside the V8 heap.
+mod dedup;
mod pixels;
-use std::sync::RwLock;
+use std::collections::HashSet;
+use std::sync::{Arc, RwLock};
+use dedup::{image_ref_key, transport_url_key, DedupKey, RefDedupCache};
use neon::context::Lock;
use neon::prelude::*;
use neon::types::buffer::TypedArray;
use pixels::{LayoutError, PlaneOrder};
+use posthog_replay_anonymizer::collect::{image_ref, url_ref};
+use posthog_replay_anonymizer::snapshot::{AnonymizedMessage, ImageEntry};
use posthog_replay_anonymizer::{
is_public_host, politeness_key, snapshot, try_canonicalize, AllowLists, FailKind,
ImageCollection, ImagePolicy, PhaseTimings, UrlCollection,
@@ -74,11 +80,122 @@ fn init_anonymizer(mut cx: FunctionContext) -> JsResult<JsNull> {
Ok(cx.null())
}
-/// The off-thread outcome: anonymized output (lines, meta JSON, route, packed image bytes), a
-/// classified failure (dlq/drop reason + detail), or an unclassified error (panic, missing init)
-/// that the caller must treat as `anonymize_failed`.
-type TaskOutcome =
- Result<Result<(Vec<u8>, String, &'static str, Vec<u8>), (&'static str, String)>, String>;
+/// The collected refs a produce lane's cache dropped before the meta was serialized. The caller
+/// still counts them as collected, so the domain count is taken before the drop.
+#[derive(Debug, Default, Clone, Copy)]
+struct ProducedRefDrops {
+ images: usize,
+ urls: usize,
+ collected_url_domains: usize,
+}
+
+struct Anonymized {
+ lines: Vec<u8>,
+ meta: String,
+ route: &'static str,
+ image_bytes: Vec<u8>,
+ drops: ProducedRefDrops,
+}
+
+/// The off-thread outcome: anonymized output, a classified failure (dlq/drop reason + detail), or
+/// an unclassified error (panic, missing init) that the caller must treat as `anonymize_failed`.
+type TaskOutcome = Result<Result<Anonymized, (&'static str, String)>, String>;
+
+struct DedupCacheHandle(Arc<RefDedupCache>);
+
+impl Finalize for DedupCacheHandle {}
+
+/// The produce lanes' caches, consulted without marking. A ref the cache already holds was
+/// produced by an earlier message, so it never crosses into JS. A ref it does not hold is claimed
+/// at produce time, after the checks that can still stop the produce.
+struct ProducedRefFilter {
+ images: Option<(Arc<RefDedupCache>, String)>,
+ urls: Option<(Arc<RefDedupCache>, Option<String>, u64)>,
+}
+
+impl ProducedRefFilter {
+ fn apply(&self, out: &mut AnonymizedMessage) -> ProducedRefDrops {
+ let mut drops = ProducedRefDrops {
+ collected_url_domains: out
+ .meta
+ .urls
+ .iter()
+ .map(|entry| entry.domain.as_str())
+ .collect::<HashSet<_>>()
+ .len(),
+ ..Default::default()
+ };
+ if let Some((cache, team_id)) = &self.images {
+ drops.images =
+ drop_produced_images(cache, team_id, &mut out.meta.images, &mut out.image_bytes);
+ }
+ if let Some((cache, namespace, time_bucket)) = &self.urls {
+ drops.urls = cache.retain_absent(&mut out.meta.urls, |entry| {
+ transport_url_key(
+ &url_reference(namespace.as_deref(), &entry.hash),
+ &entry.url,
+ *time_bucket,
+ )
+ });
+ }
+ drops
+ }
+}
+
+fn url_reference(namespace: Option<&str>, hash: &str) -> String {
+ match namespace {
+ Some(namespace) => format!("imageurl:{namespace}:{hash}"),
+ None => url_ref(hash),
+ }
+}
+
+/// Drops the entries the cache holds and repacks the bytes of the rest, so the bytes of an image
+/// already produced never reach the JS heap's external memory.
+fn drop_produced_images(
+ cache: &RefDedupCache,
+ team_id: &str,
+ entries: &mut Vec<ImageEntry>,
+ bytes: &mut Vec<u8>,
+) -> usize {
+ let dropped = cache.retain_absent(entries, |entry| {
+ image_ref_key(&image_ref(team_id, &entry.hash))
+ });
+ if dropped > 0 {
+ let mut packed = Vec::with_capacity(entries.iter().map(|entry| entry.len).sum());
+ for entry in entries.iter_mut() {
+ let start = packed.len();
+ packed.extend_from_slice(&bytes[entry.offset..entry.offset + entry.len]);
+ entry.offset = start;
+ }
+ *bytes = packed;
+ }
+ dropped
+}
+
+fn opt_dedup_cache_arg(
+ cx: &mut FunctionContext,
+ index: usize,
+) -> NeonResult<Option<Arc<RefDedupCache>>> {
+ match cx.argument_opt(index) {
+ Some(v) if v.is_a::<JsUndefined, _>(cx) || v.is_a::<JsNull, _>(cx) => Ok(None),
+ Some(v) => Ok(Some(
+ v.downcast_or_throw::<JsBox<DedupCacheHandle>, _>(cx)?
+ .0
+ .clone(),
+ )),
+ None => Ok(None),
+ }
+}
+
+fn time_bucket_arg(cx: &mut FunctionContext, index: usize) -> NeonResult<u64> {
+ let bucket = cx.argument::<JsNumber>(index)?.value(cx);
+ if !(bucket.is_finite() && bucket >= 0.0 && bucket.fract() == 0.0) {
+ return cx.throw_range_error(format!(
+ "time bucket must be a non-negative integer, got {bucket}"
+ ));
+ }
+ Ok(bucket as u64)
+}
/// The outcome plus the JSON phase timings, reported on every arm including panics.
type TaskResult = (TaskOutcome, Option<String>);
@@ -109,6 +226,11 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {
let content_key = opt_string_arg(&mut cx, 3)?;
let url_key = opt_string_arg(&mut cx, 4)?;
let reference_namespace = opt_string_arg(&mut cx, 5)?;
+ let image_dedup = opt_dedup_cache_arg(&mut cx, 6)?;
+ let url_dedup = match opt_dedup_cache_arg(&mut cx, 7)? {
+ Some(cache) => Some((cache, time_bucket_arg(&mut cx, 8)?)),
+ None => None,
+ };
if team_id.is_none() && content_key.is_some() {
return cx.throw_error("contentKey requires teamId");
}
@@ -119,6 +241,16 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {
}),
_ => None,
};
+ let produced_ref_filter = ProducedRefFilter {
+ images: image_collection
+ .as_ref()
+ .zip(image_dedup)
+ .map(|(collection, cache)| (cache, collection.team_id.clone())),
+ urls: url_key
+ .as_ref()
+ .zip(url_dedup)
+ .map(|(_, (cache, time_bucket))| (cache, reference_namespace.clone(), time_bucket)),
+ };
let url_collection = url_key.map(|url_key| UrlCollection {
url_key,
reference_namespace,
@@ -160,12 +292,19 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {
);
timings.scrub_finished();
match scrubbed {
- Ok(out) => {
+ Ok(mut out) => {
+ let drops = produced_ref_filter.apply(&mut out);
timings.mark("serialize_meta");
let meta = serde_json::to_string(&out.meta)
.map_err(|e| format!("serialize meta: {e}"))?;
timings.mark("done");
- Ok(Ok((out.lines, meta, out.route.as_str(), out.image_bytes)))
+ Ok(Ok(Anonymized {
+ lines: out.lines,
+ meta,
+ route: out.route.as_str(),
+ image_bytes: out.image_bytes,
+ drops,
+ }))
}
Err(f) => Ok(Err((f.kind.reason(), f.detail))),
}
@@ -207,7 +346,19 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {
Ok(())
};
match result {
- Ok(Ok((lines, meta, route, image_bytes))) => {
+ Ok(Ok(Anonymized {
+ lines,
+ meta,
+ route,
+ image_bytes,
+ drops,
+ })) => {
+ let deduped_images = cx.number(drops.images as f64);
+ obj.set(&mut cx, "dedupedImageCount", deduped_images)?;
+ let deduped_urls = cx.number(drops.urls as f64);
+ obj.set(&mut cx, "dedupedUrlCount", deduped_urls)?;
+ let url_domains = cx.number(drops.collected_url_domains as f64);
+ obj.set(&mut cx, "collectedUrlDomainCount", url_domains)?;
let failed = cx.boolean(false);
obj.set(&mut cx, "failed", failed)?;
let null = cx.null();
@@ -366,6 +517,95 @@ fn rgb_to_rgba_ffi(mut cx: FunctionContext) -> JsResult<JsUndefined> {
convert_in_place(&mut cx, rgb, rgba, pixels::rgb_to_rgba)
}
+fn ref_dedup_cache_new(mut cx: FunctionContext) -> JsResult<JsBox<DedupCacheHandle>> {
+ let capacity = cx.argument::<JsNumber>(0)?.value(&mut cx);
+ if !(capacity.is_finite() && capacity >= 0.0 && capacity.fract() == 0.0) {
+ return cx.throw_range_error(format!(
+ "ref cache capacity must be 0 or a positive integer, got {capacity}"
+ ));
+ }
+ Ok(cx.boxed(DedupCacheHandle(Arc::new(RefDedupCache::new(
+ capacity as usize,
+ )))))
+}
+
+fn string_array_arg(cx: &mut FunctionContext, index: usize) -> NeonResult<Vec<String>> {
+ let values = cx.argument::<JsArray>(index)?.to_vec(cx)?;
+ values
+ .into_iter()
+ .map(|value| Ok(value.downcast_or_throw::<JsString, _>(cx)?.value(cx)))
+ .collect()
+}
+
+fn image_ref_keys_arg(cx: &mut FunctionContext) -> NeonResult<Vec<DedupKey>> {
+ Ok(string_array_arg(cx, 1)?
+ .iter()
+ .map(|reference| image_ref_key(reference))
+ .collect())
+}
+
+fn transport_url_keys_arg(cx: &mut FunctionContext) -> NeonResult<Vec<DedupKey>> {
+ let references = string_array_arg(cx, 1)?;
+ let urls = string_array_arg(cx, 2)?;
+ if references.len() != urls.len() {
+ return cx.throw_range_error("expected one URL per ref");
+ }
+ let time_bucket = time_bucket_arg(cx, 3)?;
+ Ok(references
+ .iter()
+ .zip(&urls)
+ .map(|(reference, url)| transport_url_key(reference, url, time_bucket))
+ .collect())
+}
+
+fn claimed_array<'cx>(cx: &mut FunctionContext<'cx>, claimed: Vec<bool>) -> JsResult<'cx, JsArray> {
+ let array = cx.empty_array();
+ for (index, claimed) in (0u32..).zip(claimed) {
+ let claimed = cx.boolean(claimed);
+ array.set(cx, index, claimed)?;
+ }
+ Ok(array)
+}
+
+fn ref_dedup_cache_claim_refs(mut cx: FunctionContext) -> JsResult<JsArray> {
+ let cache = cx.argument::<JsBox<DedupCacheHandle>>(0)?.0.clone();
+ let keys = image_ref_keys_arg(&mut cx)?;
+ claimed_array(&mut cx, cache.claim(&keys))
+}
+
+fn ref_dedup_cache_release_refs(mut cx: FunctionContext) -> JsResult<JsUndefined> {
+ let cache = cx.argument::<JsBox<DedupCacheHandle>>(0)?.0.clone();
+ cache.release(&image_ref_keys_arg(&mut cx)?);
+ Ok(cx.undefined())
+}
+
+fn ref_dedup_cache_claim_transport_urls(mut cx: FunctionContext) -> JsResult<JsArray> {
+ let cache = cx.argument::<JsBox<DedupCacheHandle>>(0)?.0.clone();
+ let keys = transport_url_keys_arg(&mut cx)?;
+ claimed_array(&mut cx, cache.claim(&keys))
+}
+
+fn ref_dedup_cache_release_transport_urls(mut cx: FunctionContext) -> JsResult<JsUndefined> {
+ let cache = cx.argument::<JsBox<DedupCacheHandle>>(0)?.0.clone();
+ cache.release(&transport_url_keys_arg(&mut cx)?);
+ Ok(cx.undefined())
+}
+
+fn ref_dedup_cache_stats(mut cx: FunctionContext) -> JsResult<JsObject> {
+ let stats = cx.argument::<JsBox<DedupCacheHandle>>(0)?.0.stats();
+ let result = cx.empty_object();
+ for (name, value) in [
+ ("entries", stats.entries),
+ ("evictions", stats.evictions),
+ ("wouldHit", stats.would_hit),
+ ("wouldMiss", stats.would_miss),
+ ] {
+ let value = cx.number(value as f64);
+ result.set(&mut cx, name, value)?;
+ }
+ Ok(result)
+}
+
#[neon::main]
fn main(mut cx: ModuleContext) -> NeonResult<()> {
cx.export_function("initAnonymizer", init_anonymizer)?;
@@ -376,5 +616,46 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
cx.export_function("rgbToChw", rgb_to_chw_ffi)?;
cx.export_function("rgbToNormalizedChw", rgb_to_normalized_chw_ffi)?;
cx.export_function("rgbToRgba", rgb_to_rgba_ffi)?;
+ cx.export_function("refDedupCacheNew", ref_dedup_cache_new)?;
+ cx.export_function("refDedupCacheClaimRefs", ref_dedup_cache_claim_refs)?;
+ cx.export_function("refDedupCacheReleaseRefs", ref_dedup_cache_release_refs)?;
+ cx.export_function(
+ "refDedupCacheClaimTransportUrls",
+ ref_dedup_cache_claim_transport_urls,
+ )?;
+ cx.export_function(
+ "refDedupCacheReleaseTransportUrls",
+ ref_dedup_cache_release_transport_urls,
+ )?;
+ cx.export_function("refDedupCacheStats", ref_dedup_cache_stats)?;
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn entry(hash: &str, offset: usize, len: usize) -> ImageEntry {
+ ImageEntry {
+ hash: hash.to_string(),
+ offset,
+ len,
+ }
+ }
+
+ #[test]
+ fn dropping_a_produced_image_repacks_the_rest_under_their_own_hashes() {
+ let cache = RefDedupCache::new(10);
+ cache.claim(&[image_ref_key(&image_ref("7", "first"))]);
+ let mut entries = vec![entry("first", 0, 3), entry("second", 3, 2)];
+ let mut bytes = b"aaabb".to_vec();
+
+ assert_eq!(
+ drop_produced_images(&cache, "7", &mut entries, &mut bytes),
+ 1
+ );
+
+ assert_eq!(entries, vec![entry("second", 0, 2)]);
+ assert_eq!(bytes, b"bb");
+ }
+}