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.

chore(ai-research): colocate ML mirror anonymizer (#90283)

Robbiefa2dc29f3220
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
index c46dd4473bce..fff37547f54b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
@@ -4,23 +4,6 @@ import { recordMessagesDroppedByRestrictions } from './otel-metrics'
const BUCKETS_KB_WRITTEN = [0, 128, 512, 1024, 5120, 10240, 20480, 51200, 102400, 204800, Infinity]
-/** Which anonymizer produced the output; the label makes the flag rollout a direct A/B. */
-export type MlAnonymizeImpl = 'rust' | 'ts'
-/** Rust engine that produced the output (tree = the parse fallback fired). `''` when not applicable. */
-export type MlAnonymizeRoute = 'stream' | 'tree' | ''
-
-export type MlImageLaneStage = 'collected' | 'deduped' | 'queued' | 'produced' | 'produce_failed'
-
-/** Stages of the URL lane. Deliberately the same vocabulary as {@link MlImageLaneStage}, so the two
- * lanes read the same way on a dashboard even though only `collected` exists until the fetch lane
- * ships. */
-export type MlUrlLaneStage = 'collected' | 'deduped' | 'queued' | 'produced' | 'produce_failed' | 'ref_unusable'
-export type MlUrlCrawlHistoryOutcome = 'fresh' | 'miss' | 'error'
-export type MlImageSource = 'css' | 'html'
-export type MlImageSourceKind = 'inline' | 'url'
-
-const URL_BYTES_SAMPLE_RATE = 16
-
export class SessionRecordingIngesterMetrics {
private static readonly sessionsHandled = new Gauge({
name: 'recording_blob_ingestion_v2_session_manager_count',
@@ -72,80 +55,6 @@ export class SessionRecordingIngesterMetrics {
labelNames: ['content_encoding'],
})
- private static readonly mlAnonymizeDuration = new Histogram({
- name: 'recording_blob_ingestion_v2_ml_anonymize_duration_ms',
- help: 'Per-message ML mirror anonymize time in ms, by implementation and route',
- labelNames: ['impl', 'route'],
- // The measured interval includes libuv threadpool queue wait, which under backpressure
- // reaches tens of seconds — the tail buckets exist so quantiles don't clamp at 10s.
- buckets: [0, 1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000, 60000, 120000, Infinity],
- })
-
- private static readonly mlAnonymizeFailed = new Counter({
- name: 'recording_blob_ingestion_v2_ml_anonymize_failed',
- help: 'Messages dropped because ML mirror anonymization failed (fail-closed), by implementation',
- labelNames: ['impl'],
- })
-
- private static readonly mlImagesCollected = new Counter({
- name: 'recording_blob_ingestion_v2_ml_images_collected',
- help: 'Images through the out-of-band scrub lane, by stage: collected (returned by the addon), deduped (suppressed by the cross-message cache), queued (handed to the producer), produced (delivery acked), produce_failed (delivery failed; refs un-marked for natural retry)',
- labelNames: ['outcome'],
- })
-
- private static readonly mlUrlsCollected = new Counter({
- name: 'recording_blob_ingestion_v2_ml_urls_collected',
- help: 'Remote image URLs through the fetch lane, by stage: collected (returned by the addon), deduped (suppressed by the cross-message cache), queued (handed to the producer), produced (delivery acked), produce_failed (delivery failed)',
- labelNames: ['outcome'],
- })
-
- private static readonly mlImageReferencesByProperty = new Counter({
- name: 'recording_blob_ingestion_v2_ml_image_references_by_property',
- help: 'Collected CSS and HTML image ref occurrences by bounded source, property, and lane. Counts references before per-message content or URL deduplication',
- labelNames: ['source', 'property', 'kind'],
- })
-
- private static readonly mlUrlCrawlHistory = new Counter({
- name: 'recording_blob_ingestion_v2_ml_url_crawl_history_total',
- help: 'URL jobs checked by the mirror before Kafka: fresh jobs are suppressed, misses are produced, and errors fail open',
- labelNames: ['outcome'],
- })
-
- private static readonly mlUrlCrawlHistoryDuration = new Histogram({
- name: 'recording_blob_ingestion_v2_ml_url_crawl_history_duration_seconds',
- help: 'Wall time for one mirror crawl-history read by outcome',
- labelNames: ['outcome'],
- buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],
- })
-
- private static readonly mlUrlsDeclined = new Counter({
- name: 'recording_blob_ingestion_v2_ml_urls_declined',
- help: 'Remote image URLs the anonymizer refused to collect, by reason. A decline is invisible in the collected count, so without this the lane looks like traffic carries fewer images than it does',
- labelNames: ['reason'],
- })
-
- private static readonly mlUrlDomainsPerMessage = new Histogram({
- name: 'recording_blob_ingestion_v2_ml_url_domains_per_message',
- help: 'Distinct registrable domains among the URLs collected from one message, observed for every message including those with none. The fetch topic is keyed by that domain, so this is how many Kafka messages one replay message becomes, and how concentrated a page is on one operator',
- buckets: [0, 1, 2, 3, 5, 8, 13, 21, 34, 55],
- })
-
- private static readonly mlUrlsPerMessage = new Histogram({
- name: 'recording_blob_ingestion_v2_ml_urls_per_message',
- help: 'URLs collected from one message that carried at least one. The counter alone gives a mean; sizing the fetch lane needs the tail',
- buckets: [1, 2, 5, 10, 25, 50, 100, 256, 512],
- })
-
- private static readonly mlImageBytesProduced = new Counter({
- name: 'recording_blob_ingestion_v2_ml_image_bytes_produced',
- help: 'Bytes of collected images delivered to the scrub topic (acked)',
- })
-
- private static readonly mlImagePseudoTeamInvalid = new Counter({
- name: 'recording_blob_ingestion_v2_ml_image_pseudo_team_invalid',
- help: 'Messages whose derived team pseudonym failed the consumer ref-shape check; collection disabled for them (inline blur instead)',
- })
-
public static incrementMessageReceived(partition: number): void {
this.messageReceived.labels(partition.toString()).inc()
}
@@ -182,91 +91,4 @@ export class SessionRecordingIngesterMetrics {
public static observeKafkaBatchSizeKb(sizeKb: number): void {
this.kafkaBatchSizeKb.observe(sizeKb)
}
-
- public static observeMlAnonymizeDuration(impl: MlAnonymizeImpl, ms: number, route: MlAnonymizeRoute = ''): void {
- this.mlAnonymizeDuration.labels(impl, route).observe(ms)
- }
-
- public static incrementMlAnonymizeFailed(impl: MlAnonymizeImpl): void {
- this.mlAnonymizeFailed.labels(impl).inc()
- }
-
- public static incrementMlImagesCollected(outcome: MlImageLaneStage, count: number): void {
- this.mlImagesCollected.labels(outcome).inc(count)
- }
-
- public static incrementMlImageReferencesByProperty(
- source: MlImageSource,
- property: string,
- kind: MlImageSourceKind,
- count: number
- ): void {
- if (count > 0) {
- this.mlImageReferencesByProperty.labels(source, property, kind).inc(count)
- }
- }
-
- private static readonly mlUrlBytes = new Histogram({
- name: 'recording_blob_ingestion_v2_ml_url_bytes',
- help: 'Bytes in one collected remote image URL, sampled. The tail sizes the per-record packing budget, because a record is filled by bytes rather than by a fixed number of URLs. Read the shape, not the count: one URL in URL_BYTES_SAMPLE_RATE is observed',
- buckets: [64, 128, 256, 512, 1024, 2048],
- })
- /**
- * A message can carry hundreds of URLs, and an observation costs several allocations, so
- * observing each one puts the size of the payload on the mirror's hot path.
- */
- private static urlBytesSeen = 0
- private static readonly mlUrlsPerRecord = new Histogram({
- name: 'recording_blob_ingestion_v2_ml_urls_per_record',
- help: 'URLs packed into one record on the fetch topic. Bounded in practice by the collector cap per message, since a record holds one domain from one message',
- buckets: [1, 8, 32, 64, 128, 256, 512],
- })
- private static readonly mlUrlRecordBytes = new Histogram({
- name: 'recording_blob_ingestion_v2_ml_url_record_bytes',
- help: 'Serialized bytes of one record on the fetch topic. Read against librdkafka message.max.bytes, which this producer leaves at its 1,000,000 byte default: the packing budget is what keeps a record under it',
- buckets: [1024, 8192, 65536, 262144, 524288, 1_000_000],
- })
-
- public static observeMlUrlBytes(bytes: number): void {
- if (this.urlBytesSeen++ % URL_BYTES_SAMPLE_RATE === 0) {
- this.mlUrlBytes.observe(bytes)
- }
- }
- public static observeMlUrlRecord(urls: number, bytes: number): void {
- this.mlUrlsPerRecord.observe(urls)
- this.mlUrlRecordBytes.observe(bytes)
- }
- public static incrementMlUrlsCollected(outcome: MlUrlLaneStage, count: number): void {
- this.mlUrlsCollected.labels(outcome).inc(count)
- }
-
- public static incrementMlUrlCrawlHistory(outcome: MlUrlCrawlHistoryOutcome, count: number): void {
- this.mlUrlCrawlHistory.labels(outcome).inc(count)
- }
-
- public static observeMlUrlCrawlHistoryDuration(outcome: 'success' | 'error', durationSeconds: number): void {
- this.mlUrlCrawlHistoryDuration.labels(outcome).observe(durationSeconds)
- }
-
- public static incrementMlUrlsDeclined(reason: string, count: number): void {
- if (count > 0) {
- this.mlUrlsDeclined.inc({ reason }, count)
- }
- }
-
- public static observeMlUrlDomainsPerMessage(domains: number): void {
- this.mlUrlDomainsPerMessage.observe(domains)
- }
-
- public static observeMlUrlsPerMessage(urls: number): void {
- this.mlUrlsPerMessage.observe(urls)
- }
-
- public static incrementMlImageBytesProduced(bytes: number): void {
- this.mlImageBytesProduced.inc(bytes)
- }
-
- public static incrementMlImagePseudoTeamInvalid(): void {
- this.mlImagePseudoTeamInvalid.inc()
- }
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
index 43a0d18bb2f3..b20ccadfec29 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
@@ -1,5 +1,187 @@
import { Counter, Histogram } from 'prom-client'
+/** Which anonymizer produced the output; the label makes the flag rollout a direct A/B. */
+export type MlAnonymizeImpl = 'rust' | 'ts'
+/** Rust engine that produced the output (tree = the parse fallback fired). `''` when not applicable. */
+export type MlAnonymizeRoute = 'stream' | 'tree' | ''
+
+export type MlImageLaneStage = 'collected' | 'deduped' | 'queued' | 'produced' | 'produce_failed'
+
+/** Stages of the URL lane. Deliberately the same vocabulary as {@link MlImageLaneStage}, so the two
+ * lanes read the same way on a dashboard even though only `collected` exists until the fetch lane
+ * ships. */
+export type MlUrlLaneStage = 'collected' | 'deduped' | 'queued' | 'produced' | 'produce_failed' | 'ref_unusable'
+export type MlUrlCrawlHistoryOutcome = 'fresh' | 'miss' | 'error'
+export type MlImageSource = 'css' | 'html'
+export type MlImageSourceKind = 'inline' | 'url'
+
+const URL_BYTES_SAMPLE_RATE = 16
+
+export class MlMirrorMetrics {
+ private static readonly mlAnonymizeDuration = new Histogram({
+ name: 'recording_blob_ingestion_v2_ml_anonymize_duration_ms',
+ help: 'Per-message ML mirror anonymize time in ms, by implementation and route',
+ labelNames: ['impl', 'route'],
+ // The measured interval includes libuv threadpool queue wait, which under backpressure
+ // reaches tens of seconds — the tail buckets exist so quantiles don't clamp at 10s.
+ buckets: [0, 1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000, 60000, 120000, Infinity],
+ })
+
+ private static readonly mlAnonymizeFailed = new Counter({
+ name: 'recording_blob_ingestion_v2_ml_anonymize_failed',
+ help: 'Messages dropped because ML mirror anonymization failed (fail-closed), by implementation',
+ labelNames: ['impl'],
+ })
+
+ private static readonly mlImagesCollected = new Counter({
+ name: 'recording_blob_ingestion_v2_ml_images_collected',
+ help: 'Images through the out-of-band scrub lane, by stage: collected (returned by the addon), deduped (suppressed by the cross-message cache), queued (handed to the producer), produced (delivery acked), produce_failed (delivery failed; refs un-marked for natural retry)',
+ labelNames: ['outcome'],
+ })
+
+ private static readonly mlUrlsCollected = new Counter({
+ name: 'recording_blob_ingestion_v2_ml_urls_collected',
+ help: 'Remote image URLs through the fetch lane, by stage: collected (returned by the addon), deduped (suppressed by the cross-message cache), queued (handed to the producer), produced (delivery acked), produce_failed (delivery failed)',
+ labelNames: ['outcome'],
+ })
+
+ private static readonly mlImageReferencesByProperty = new Counter({
+ name: 'recording_blob_ingestion_v2_ml_image_references_by_property',
+ help: 'Collected CSS and HTML image ref occurrences by bounded source, property, and lane. Counts references before per-message content or URL deduplication',
+ labelNames: ['source', 'property', 'kind'],
+ })
+
+ private static readonly mlUrlCrawlHistory = new Counter({
+ name: 'recording_blob_ingestion_v2_ml_url_crawl_history_total',
+ help: 'URL jobs checked by the mirror before Kafka: fresh jobs are suppressed, misses are produced, and errors fail open',
+ labelNames: ['outcome'],
+ })
+
+ private static readonly mlUrlCrawlHistoryDuration = new Histogram({
+ name: 'recording_blob_ingestion_v2_ml_url_crawl_history_duration_seconds',
+ help: 'Wall time for one mirror crawl-history read by outcome',
+ labelNames: ['outcome'],
+ buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],
+ })
+
+ private static readonly mlUrlsDeclined = new Counter({
+ name: 'recording_blob_ingestion_v2_ml_urls_declined',
+ help: 'Remote image URLs the anonymizer refused to collect, by reason. A decline is invisible in the collected count, so without this the lane looks like traffic carries fewer images than it does',
+ labelNames: ['reason'],
+ })
+
+ private static readonly mlUrlDomainsPerMessage = new Histogram({
+ name: 'recording_blob_ingestion_v2_ml_url_domains_per_message',
+ help: 'Distinct registrable domains among the URLs collected from one message, observed for every message including those with none. The fetch topic is keyed by that domain, so this is how many Kafka messages one replay message becomes, and how concentrated a page is on one operator',
+ buckets: [0, 1, 2, 3, 5, 8, 13, 21, 34, 55],
+ })
+
+ private static readonly mlUrlsPerMessage = new Histogram({
+ name: 'recording_blob_ingestion_v2_ml_urls_per_message',
+ help: 'URLs collected from one message that carried at least one. The counter alone gives a mean; sizing the fetch lane needs the tail',
+ buckets: [1, 2, 5, 10, 25, 50, 100, 256, 512],
+ })
+
+ private static readonly mlImageBytesProduced = new Counter({
+ name: 'recording_blob_ingestion_v2_ml_image_bytes_produced',
+ help: 'Bytes of collected images delivered to the scrub topic (acked)',
+ })
+
+ private static readonly mlImagePseudoTeamInvalid = new Counter({
+ name: 'recording_blob_ingestion_v2_ml_image_pseudo_team_invalid',
+ help: 'Messages whose derived team pseudonym failed the consumer ref-shape check; collection disabled for them (inline blur instead)',
+ })
+
+ private static readonly mlUrlBytes = new Histogram({
+ name: 'recording_blob_ingestion_v2_ml_url_bytes',
+ help: 'Bytes in one collected remote image URL, sampled. The tail sizes the per-record packing budget, because a record is filled by bytes rather than by a fixed number of URLs. Read the shape, not the count: one URL in URL_BYTES_SAMPLE_RATE is observed',
+ buckets: [64, 128, 256, 512, 1024, 2048],
+ })
+ /**
+ * A message can carry hundreds of URLs, and an observation costs several allocations, so
+ * observing each one puts the size of the payload on the mirror's hot path.
+ */
+ private static urlBytesSeen = 0
+ private static readonly mlUrlsPerRecord = new Histogram({
+ name: 'recording_blob_ingestion_v2_ml_urls_per_record',
+ help: 'URLs packed into one record on the fetch topic. Bounded in practice by the collector cap per message, since a record holds one domain from one message',
+ buckets: [1, 8, 32, 64, 128, 256, 512],
+ })
+ private static readonly mlUrlRecordBytes = new Histogram({
+ name: 'recording_blob_ingestion_v2_ml_url_record_bytes',
+ help: 'Serialized bytes of one record on the fetch topic. Read against librdkafka message.max.bytes, which this producer leaves at its 1,000,000 byte default: the packing budget is what keeps a record under it',
+ buckets: [1024, 8192, 65536, 262144, 524288, 1_000_000],
+ })
+
+ public static observeMlAnonymizeDuration(impl: MlAnonymizeImpl, ms: number, route: MlAnonymizeRoute = ''): void {
+ this.mlAnonymizeDuration.labels(impl, route).observe(ms)
+ }
+
+ public static incrementMlAnonymizeFailed(impl: MlAnonymizeImpl): void {
+ this.mlAnonymizeFailed.labels(impl).inc()
+ }
+
+ public static incrementMlImagesCollected(outcome: MlImageLaneStage, count: number): void {
+ this.mlImagesCollected.labels(outcome).inc(count)
+ }
+
+ public static incrementMlImageReferencesByProperty(
+ source: MlImageSource,
+ property: string,
+ kind: MlImageSourceKind,
+ count: number
+ ): void {
+ if (count > 0) {
+ this.mlImageReferencesByProperty.labels(source, property, kind).inc(count)
+ }
+ }
+
+ public static observeMlUrlBytes(bytes: number): void {
+ if (this.urlBytesSeen++ % URL_BYTES_SAMPLE_RATE === 0) {
+ this.mlUrlBytes.observe(bytes)
+ }
+ }
+
+ public static observeMlUrlRecord(urls: number, bytes: number): void {
+ this.mlUrlsPerRecord.observe(urls)
+ this.mlUrlRecordBytes.observe(bytes)
+ }
+
+ public static incrementMlUrlsCollected(outcome: MlUrlLaneStage, count: number): void {
+ this.mlUrlsCollected.labels(outcome).inc(count)
+ }
+
+ public static incrementMlUrlCrawlHistory(outcome: MlUrlCrawlHistoryOutcome, count: number): void {
+ this.mlUrlCrawlHistory.labels(outcome).inc(count)
+ }
+
+ public static observeMlUrlCrawlHistoryDuration(outcome: 'success' | 'error', durationSeconds: number): void {
+ this.mlUrlCrawlHistoryDuration.labels(outcome).observe(durationSeconds)
+ }
+
+ public static incrementMlUrlsDeclined(reason: string, count: number): void {
+ if (count > 0) {
+ this.mlUrlsDeclined.inc({ reason }, count)
+ }
+ }
+
+ public static observeMlUrlDomainsPerMessage(domains: number): void {
+ this.mlUrlDomainsPerMessage.observe(domains)
+ }
+
+ public static observeMlUrlsPerMessage(urls: number): void {
+ this.mlUrlsPerMessage.observe(urls)
+ }
+
+ public static incrementMlImageBytesProduced(bytes: number): void {
+ this.mlImageBytesProduced.inc(bytes)
+ }
+
+ public static incrementMlImagePseudoTeamInvalid(): void {
+ this.mlImagePseudoTeamInvalid.inc()
+ }
+}
+
// Days. A batch that spans dates files the whole object under its oldest event date (see objectKey), so
// these buckets are chosen to separate a same-day batch (span 0) from one dragged back by a straggler.
const PARTITION_DAY_BUCKETS = [0, 1, 2, 3, 7, 14, 30, 90, 365]
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-anonymize-concurrency.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-anonymize-concurrency.test.ts
index 93419589440f..c5c3c169997b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-anonymize-concurrency.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-anonymize-concurrency.test.ts
@@ -8,7 +8,6 @@ import { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'
import { ok } from '~/ingestion/framework/results'
import { runSessionReplayPipeline } from '~/ingestion/pipelines/sessionreplay'
import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'
-import { createParseAndAnonymizeMessageStep } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'
import { SessionBatchRecorder } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder'
import { SessionFilter } from '~/ingestion/pipelines/sessionreplay/sessions/session-filter'
import { SessionTracker } from '~/ingestion/pipelines/sessionreplay/sessions/session-tracker'
@@ -23,12 +22,13 @@ import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'
import { createMlMirrorReplayPipeline } from './ml-mirror-pipeline'
+import { createParseAndAnonymizeMessageStep } from './parse-and-anonymize-step'
jest.mock('~/ingestion/common/steps/event-preprocessing', () => ({
createParseHeadersStep: jest.fn(),
createApplyEventRestrictionsStep: jest.fn(),
}))
-jest.mock('~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step', () => ({
+jest.mock('./parse-and-anonymize-step', () => ({
createParseAndAnonymizeMessageStep: jest.fn(),
}))
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 024ce34e708f..408770d54446 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
@@ -17,7 +17,6 @@ import { createAiTrainingOptInFilterStep } from '~/ingestion/pipelines/sessionre
import type { CrawlHistoryStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history'
import { createProduceCollectedImagesStep } from '~/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step'
import { createProduceCollectedUrlsStep } from '~/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step'
-import { createParseAndAnonymizeMessageStep } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'
import { MessageContext } from '~/ingestion/pipelines/sessionreplay/pipeline-types'
import { createRecordSessionEventStep } from '~/ingestion/pipelines/sessionreplay/record-session-event-step'
import { createMarkSeenStep } from '~/ingestion/pipelines/sessionreplay/session-batch-mark-seen-step'
@@ -28,6 +27,8 @@ import { MlImageFetchOutput, MlImageScrubOutput } from '~/ingestion/pipelines/se
import { createTeamFilterStep } from '~/ingestion/pipelines/sessionreplay/team-filter-step'
import { createValidateSessionReplayHeadersStep } from '~/ingestion/pipelines/sessionreplay/validate-headers-step'
+import { createParseAndAnonymizeMessageStep } from './parse-and-anonymize-step'
+
export interface MlMirrorPipelineOptions {
/** Cap on sessions scrubbed concurrently; each in-flight scrub occupies a libuv threadpool thread. */
anonymizeMaxConcurrency: number
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.ts
similarity index 98%
rename from nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts
rename to nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.ts
index 6d60013b58f3..bec57e9b2d19 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.ts
@@ -4,17 +4,17 @@ import { register } from 'prom-client'
import { gzip } from 'zlib'
import { PipelineResultType } from '~/ingestion/framework/results'
+import { imageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'
+import { SessionReplayHeaders } from '~/ingestion/pipelines/sessionreplay/pipeline-types'
-import { imageRef } from './ml-mirror-image-scrub/content-ref'
+import { createParseAndAnonymizeMessageStep } from './parse-and-anonymize-step'
import {
PSEUDONYM_IMAGE_CONTENT_KEY,
PSEUDONYM_IMAGE_URL_GLOBAL_VALUE,
PSEUDONYM_IMAGE_URL_KEY,
PSEUDONYM_TEAM,
pseudonymize,
-} from './ml-mirror/pseudonymize'
-import { createParseAndAnonymizeMessageStep } from './parse-and-anonymize-step'
-import { SessionReplayHeaders } from './pipeline-types'
+} from './pseudonymize'
const compressWithGzip = promisify(gzip)
const IMAGE_SOURCE_METRIC = 'recording_blob_ingestion_v2_ml_image_references_by_property'
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts
similarity index 92%
rename from nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts
rename to nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts
index 911de63e7c2f..76c038709fa4 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts
@@ -10,17 +10,28 @@ import { ProcessingStep } from '~/ingestion/framework/steps'
import { recordAnonymizeTimingSpans } from '~/ingestion/pipelines/sessionreplay/anonymize-timing-spans'
import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'
import { SessionRecordingIngesterMetrics } from '~/ingestion/pipelines/sessionreplay/metrics'
+import {
+ hashImageBytes,
+ imageRef,
+ isImageRef,
+ urlRef,
+} from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'
+import {
+ ParseMessageStepInput,
+ ParseMessageStepOutput,
+ getContentEncoding,
+ isGzipped,
+} from '~/ingestion/pipelines/sessionreplay/parse-message-step'
import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
-import { hashImageBytes, imageRef, isImageRef, urlRef } from './ml-mirror-image-scrub/content-ref'
+import { MlMirrorMetrics } from './metrics'
import {
PSEUDONYM_IMAGE_CONTENT_KEY,
PSEUDONYM_IMAGE_URL_GLOBAL_VALUE,
PSEUDONYM_IMAGE_URL_KEY,
PSEUDONYM_TEAM,
pseudonymize,
-} from './ml-mirror/pseudonymize'
-import { ParseMessageStepInput, ParseMessageStepOutput, getContentEncoding, isGzipped } from './parse-message-step'
+} from './pseudonymize'
const MESSAGE_TIMESTAMP_DIFF_THRESHOLD_DAYS = 7
@@ -131,7 +142,7 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInp
// would drop — those messages fall back to the inline blur, loudly.
if (!isImageRef(imageRef(pseudoTeam, hashImageBytes(contentKey, Buffer.alloc(0))))) {
logger.error('🖼️', 'ml_image_scrub_pseudo_team_shape_invalid', { teamId })
- SessionRecordingIngesterMetrics.incrementMlImagePseudoTeamInvalid()
+ MlMirrorMetrics.incrementMlImagePseudoTeamInvalid()
return undefined
}
keys = {
@@ -172,10 +183,10 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInp
} catch (error) {
// A rejected promise (native panic, addon load failure) must fail closed.
logger.warn('🙈', 'anonymize_event_failed', { error: String(error) })
- SessionRecordingIngesterMetrics.incrementMlAnonymizeFailed('rust')
+ MlMirrorMetrics.incrementMlAnonymizeFailed('rust')
return drop('anonymize_failed')
}
- SessionRecordingIngesterMetrics.observeMlAnonymizeDuration('rust', performance.now() - t0, result.route ?? '')
+ MlMirrorMetrics.observeMlAnonymizeDuration('rust', performance.now() - t0, result.route ?? '')
recordAnonymizeTimingSpans(callStartEpochMs, result.timings, {
route: result.route,
failureReason: result.failed ? (result.reason ?? 'anonymize_failed') : null,
@@ -199,7 +210,7 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInp
}
// anonymize_failed (or anything unclassified): fail closed.
logger.warn('🙈', 'anonymize_event_failed', { error: result.error ?? 'rust anonymizer failed' })
- SessionRecordingIngesterMetrics.incrementMlAnonymizeFailed('rust')
+ MlMirrorMetrics.incrementMlAnonymizeFailed('rust')
return drop('anonymize_failed')
}
@@ -209,7 +220,7 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInp
} catch (error) {
// Fail closed: an uncaught throw here poisons the pipeline instead of dropping one message.
logger.warn('🙈', 'anonymize_event_failed', { error: String(error) })
- SessionRecordingIngesterMetrics.incrementMlAnonymizeFailed('rust')
+ MlMirrorMetrics.incrementMlAnonymizeFailed('rust')
return drop('anonymize_failed')
}
@@ -284,7 +295,7 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInp
function recordImageSources(meta: AnonymizeMeta): void {
for (const imageSource of meta.imageSources ?? []) {
- SessionRecordingIngesterMetrics.incrementMlImageReferencesByProperty(
+ MlMirrorMetrics.incrementMlImageReferencesByProperty(
imageSource.source,
imageSource.property,
imageSource.kind,
@@ -317,7 +328,7 @@ function unpackCollectedImages(
bytes: packed.subarray(entry.offset, entry.offset + entry.len),
})
}
- SessionRecordingIngesterMetrics.incrementMlImagesCollected('collected', images.length)
+ MlMirrorMetrics.incrementMlImagesCollected('collected', images.length)
return images.length > 0 ? images : undefined
}
@@ -342,13 +353,13 @@ function unpackCollectedUrls(pseudoTeam: string, meta: AnonymizeMeta): Collected
domains.add(entry.domain)
}
for (const decline of meta.urlDeclines ?? []) {
- SessionRecordingIngesterMetrics.incrementMlUrlsDeclined(decline.reason, decline.count)
+ MlMirrorMetrics.incrementMlUrlsDeclined(decline.reason, decline.count)
}
- SessionRecordingIngesterMetrics.observeMlUrlDomainsPerMessage(domains.size)
+ MlMirrorMetrics.observeMlUrlDomainsPerMessage(domains.size)
if (urls.length === 0) {
return undefined
}
- SessionRecordingIngesterMetrics.incrementMlUrlsCollected('collected', urls.length)
- SessionRecordingIngesterMetrics.observeMlUrlsPerMessage(urls.length)
+ MlMirrorMetrics.incrementMlUrlsCollected('collected', urls.length)
+ MlMirrorMetrics.observeMlUrlsPerMessage(urls.length)
return urls
}
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 2bda2c9b7293..362c7f57f83b 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
@@ -1,9 +1,9 @@
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { PipelineResultType } from '~/ingestion/framework/results'
import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport'
-import { CollectedImage } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'
import { MlImageScrubOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
+import { CollectedImage } from './parse-and-anonymize-step'
import { createProduceCollectedImagesStep } from './produce-collected-images-step'
describe('produceCollectedImagesStep', () => {
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 f76db2d8c5d3..f72f42364b0e 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
@@ -2,12 +2,13 @@ import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { logger } from '~/common/utils/logger'
import { ok } from '~/ingestion/framework/results'
import { ProcessingStep } from '~/ingestion/framework/steps'
-import { SessionRecordingIngesterMetrics } from '~/ingestion/pipelines/sessionreplay/metrics'
import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport'
-import { CollectedImage } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'
import { ML_IMAGE_SCRUB_OUTPUT, MlImageScrubOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'
+import { MlMirrorMetrics } from './metrics'
+import { CollectedImage } from './parse-and-anonymize-step'
+
/**
* 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
@@ -40,7 +41,7 @@ export function createProduceCollectedImagesStep<
}
const fresh = images.filter((image) => !producedRefs.has(image.ref))
- SessionRecordingIngesterMetrics.incrementMlImagesCollected('deduped', images.length - fresh.length)
+ MlMirrorMetrics.incrementMlImagesCollected('deduped', images.length - fresh.length)
if (fresh.length === 0) {
return Promise.resolve(ok({ ...input, collectedImages: undefined }))
}
@@ -50,7 +51,7 @@ export function createProduceCollectedImagesStep<
producedRefs.add(image.ref)
bytes += image.bytes.length
}
- SessionRecordingIngesterMetrics.incrementMlImagesCollected('queued', fresh.length)
+ MlMirrorMetrics.incrementMlImagesCollected('queued', fresh.length)
const captureTimestampMs = input.message.timestamp
const headers =
captureTimestampMs !== undefined && Number.isSafeInteger(captureTimestampMs) && captureTimestampMs > 0
@@ -69,8 +70,8 @@ export function createProduceCollectedImagesStep<
)
.then(() => {
// queueMessages resolves on delivery acks, so `produced` counts what actually landed.
- SessionRecordingIngesterMetrics.incrementMlImagesCollected('produced', refs.length)
- SessionRecordingIngesterMetrics.incrementMlImageBytesProduced(bytes)
+ MlMirrorMetrics.incrementMlImagesCollected('produced', refs.length)
+ MlMirrorMetrics.incrementMlImageBytesProduced(bytes)
})
.catch((error) => {
// A dangling ref reads as a placeholder downstream, so a failed produce is logged,
@@ -81,7 +82,7 @@ export function createProduceCollectedImagesStep<
producedRefs.delete(ref)
}
logger.warn('🖼️', 'ml_image_scrub_produce_failed', { count: refs.length, error: String(error) })
- SessionRecordingIngesterMetrics.incrementMlImagesCollected('produce_failed', refs.length)
+ MlMirrorMetrics.incrementMlImagesCollected('produce_failed', refs.length)
})
return Promise.resolve(ok({ ...input, collectedImages: undefined }, [produce]))
}
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 0e04a255d417..58df08cf9cac 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
@@ -3,10 +3,10 @@ import { parseJSON } from '~/common/utils/json-parse'
import { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'
import { PipelineResultType } from '~/ingestion/framework/results'
import type { CrawlHistoryStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history'
-import { CollectedUrl } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'
import { MlImageFetchOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
import { RecordedTopHogMetric, createRecordingTopHog } from '~/tests/helpers/tophog'
+import { CollectedUrl } from './parse-and-anonymize-step'
import { CollectedUrlsMessage, createProduceCollectedUrlsStep } from './produce-collected-urls-step'
describe('produceCollectedUrlsStep', () => {
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 e60406e8ec34..d1553c4dbdcb 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
@@ -5,13 +5,14 @@ import { logger } from '~/common/utils/logger'
import { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'
import { ok } from '~/ingestion/framework/results'
import { ProcessingStep } from '~/ingestion/framework/steps'
-import { SessionRecordingIngesterMetrics } from '~/ingestion/pipelines/sessionreplay/metrics'
import type { CrawlHistoryStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history'
import { parseImageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'
-import { CollectedUrl } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'
import { ML_IMAGE_FETCH_OUTPUT, MlImageFetchOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'
+import { MlMirrorMetrics } from './metrics'
+import { CollectedUrl } from './parse-and-anonymize-step'
+
/**
* 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
@@ -96,19 +97,13 @@ async function excludeFreshCrawlHistory(
const history = stored.get(entry.ref)
return history?.kind !== 'url' || history.nextFetchAtMs <= nowMs
})
- SessionRecordingIngesterMetrics.incrementMlUrlCrawlHistory('fresh', candidates.length - publishable.length)
- SessionRecordingIngesterMetrics.incrementMlUrlCrawlHistory('miss', publishable.length)
- SessionRecordingIngesterMetrics.observeMlUrlCrawlHistoryDuration(
- 'success',
- (performance.now() - startedAt) / 1000
- )
+ MlMirrorMetrics.incrementMlUrlCrawlHistory('fresh', candidates.length - publishable.length)
+ MlMirrorMetrics.incrementMlUrlCrawlHistory('miss', publishable.length)
+ MlMirrorMetrics.observeMlUrlCrawlHistoryDuration('success', (performance.now() - startedAt) / 1000)
return publishable
} catch (error) {
- SessionRecordingIngesterMetrics.incrementMlUrlCrawlHistory('error', candidates.length)
- SessionRecordingIngesterMetrics.observeMlUrlCrawlHistoryDuration(
- 'error',
- (performance.now() - startedAt) / 1000
- )
+ MlMirrorMetrics.incrementMlUrlCrawlHistory('error', candidates.length)
+ MlMirrorMetrics.observeMlUrlCrawlHistoryDuration('error', (performance.now() - startedAt) / 1000)
onError(error, candidates.length)
return candidates
}
@@ -174,7 +169,7 @@ export function createProduceCollectedUrlsStep<
const fresh = collected
.map((entry) => ({ entry, cacheKey: producedUrlCacheKey(entry, timeBucket) }))
.filter(({ cacheKey }) => !producedTransportUrls.has(cacheKey))
- SessionRecordingIngesterMetrics.incrementMlUrlsCollected('deduped', collected.length - fresh.length)
+ MlMirrorMetrics.incrementMlUrlsCollected('deduped', collected.length - fresh.length)
if (fresh.length === 0) {
return ok({ ...input, collectedUrls: undefined })
}
@@ -205,7 +200,7 @@ export function createProduceCollectedUrlsStep<
}
const unusable = fresh.length - usable.length
if (unusable > 0) {
- SessionRecordingIngesterMetrics.incrementMlUrlsCollected('ref_unusable', unusable)
+ MlMirrorMetrics.incrementMlUrlsCollected('ref_unusable', unusable)
// Warn, not error: this is per replay message, so an addon-side format drift would
// otherwise write an error line at full ingest rate for as long as it lasted.
logger.warn('🌐', 'ml_image_fetch_ref_unusable', { count: unusable })
@@ -243,14 +238,14 @@ export function createProduceCollectedUrlsStep<
republishCount: 0,
lastRepublishReason: null,
}
- SessionRecordingIngesterMetrics.observeMlUrlBytes(Buffer.byteLength(entry.url))
+ MlMirrorMetrics.observeMlUrlBytes(Buffer.byteLength(entry.url))
if (group) {
group.push(record)
} else {
byDomain.set(entry.domain, [record])
}
}
- SessionRecordingIngesterMetrics.incrementMlUrlsCollected('queued', publishable.length)
+ MlMirrorMetrics.incrementMlUrlsCollected('queued', publishable.length)
const messages = [...byDomain].flatMap(([domain, jobs]) =>
packByBytes(jobs, MAX_RECORD_BYTES).map((slice) => {
@@ -260,7 +255,7 @@ export function createProduceCollectedUrlsStep<
jobs: slice,
} satisfies CollectedUrlsMessage)
)
- SessionRecordingIngesterMetrics.observeMlUrlRecord(slice.length, value.length)
+ MlMirrorMetrics.observeMlUrlRecord(slice.length, value.length)
return { key: domain, value }
})
)
@@ -272,7 +267,7 @@ export function createProduceCollectedUrlsStep<
.queueMessages(ML_IMAGE_FETCH_OUTPUT, messages)
.then(() => {
// queueMessages resolves on the delivery acks, so `produced` counts what landed.
- SessionRecordingIngesterMetrics.incrementMlUrlsCollected('produced', producedCacheKeys.length)
+ MlMirrorMetrics.incrementMlUrlsCollected('produced', producedCacheKeys.length)
for (const [registrableDomain, jobs] of byDomain) {
producedUrlsByRegistrableDomain.record({ registrable_domain: registrableDomain }, jobs.length)
}
@@ -291,7 +286,7 @@ export function createProduceCollectedUrlsStep<
domains: byDomain.size,
error: String(error),
})
- SessionRecordingIngesterMetrics.incrementMlUrlsCollected('produce_failed', producedCacheKeys.length)
+ MlMirrorMetrics.incrementMlUrlsCollected('produce_failed', producedCacheKeys.length)
})
return ok({ ...input, collectedUrls: undefined }, [produce])
}