:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay): add concerrency per batch to ml-mirror sessions scrubbing (#72887)
Robbiea346012e27d9
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.test.tsnew file mode 100644index 000000000000..57878ebe5cfc--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.test.ts@@ -0,0 +1,12 @@+import { resolveMlAnonymizeMaxConcurrency } from './config'++describe('resolveMlAnonymizeMaxConcurrency', () => {+ it.each([+ ['explicit value passes through verbatim, even above the pool', 8, 3, 4, 8],+ ['sentinel resolves to available CPUs when below the pool', 0, 3, 4, 3],+ ['sentinel is capped by the threadpool size', 0, 16, 4, 4],+ ['sentinel never resolves below 1', -1, 0, 0, 1],+ ])('%s', (_name, configured, cpus, poolSize, expected) => {+ expect(resolveMlAnonymizeMaxConcurrency(configured, cpus, poolSize)).toBe(expected)+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.tsindex 3d7bcc833856..b95256b9a28a 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts@@ -1,3 +1,5 @@+import os from 'node:os'+export type MlMirrorConfig = {/** S3 key prefix under the bucket for the block-metadata Parquet dataset (used by the sink). */SESSION_RECORDING_ML_METADATA_PREFIX: string@@ -36,6 +38,14 @@ export type MlMirrorConfig = {// Scrub-phase budget. Sized so scrub + 2x the S3 write timeout stays under Kafka's max.poll.interval.ms// (300s), or a hung sidecar/S3 evicts us mid-batch and livelocks.SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_BATCH_SCRUB_MS: number++ /**+ * Cap on messages scrubbed concurrently per pod. Each in-flight scrub occupies one libuv+ * threadpool thread (UV_THREADPOOL_SIZE, default 4, shared with the recorder's snappy+ * compression). <= 0 (the default) resolves to min(available CPUs, threadpool size); an+ * explicit positive value is used verbatim; 1 restores fully sequential scrubbing.+ */+ SESSION_RECORDING_ML_ANONYMIZE_MAX_CONCURRENCY: number}export function getDefaultMlMirrorConfig(): MlMirrorConfig {@@ -61,5 +71,23 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_RETRIES: 3,SESSION_RECORDING_ML_IMAGE_SCRUB_S3_WRITE_TIMEOUT_MS: 30 * 1000,SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_BATCH_SCRUB_MS: 120 * 1000,+ SESSION_RECORDING_ML_ANONYMIZE_MAX_CONCURRENCY: 0,+ }+}++const DEFAULT_UV_THREADPOOL_SIZE = 4++/**+ * `os.availableParallelism()` respects cgroup CPU limits, so in-container this sees the pod's+ * cores, not the node's.+ */+export function resolveMlAnonymizeMaxConcurrency(+ configured: number,+ availableParallelism: number = os.availableParallelism(),+ uvThreadpoolSize: number = parseInt(process.env.UV_THREADPOOL_SIZE ?? '', 10) || DEFAULT_UV_THREADPOOL_SIZE+): number {+ if (configured > 0) {+ return configured}+ return Math.max(1, Math.min(availableParallelism, uvThreadpoolSize))}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.tsnew file mode 100644index 000000000000..93419589440f--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-anonymize-concurrency.test.ts@@ -0,0 +1,219 @@+import { DateTime } from 'luxon'+import { Message } from 'node-rdkafka'++import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'+import { PromiseScheduler } from '~/common/utils/promise-scheduler'+import { createApplyEventRestrictionsStep, createParseHeadersStep } from '~/ingestion/common/steps/event-preprocessing'+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'+import {+ RetentionResolution,+ RetentionService,+} from '~/ingestion/pipelines/sessionreplay/shared/retention/retention-service'+import { SessionMap, SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'+import { TeamService } from '~/ingestion/pipelines/sessionreplay/shared/teams/team-service'+import { createMockKeyStore } from '~/ingestion/pipelines/sessionreplay/shared/test-helpers'+import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'+import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'++import { createMlMirrorReplayPipeline } from './ml-mirror-pipeline'++jest.mock('~/ingestion/common/steps/event-preprocessing', () => ({+ createParseHeadersStep: jest.fn(),+ createApplyEventRestrictionsStep: jest.fn(),+}))+jest.mock('~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step', () => ({+ createParseAndAnonymizeMessageStep: jest.fn(),+}))++const mockCreateParseHeadersStep = createParseHeadersStep as jest.Mock+const mockCreateApplyEventRestrictionsStep = createApplyEventRestrictionsStep as jest.Mock+const mockCreateParseAndAnonymizeMessageStep = createParseAndAnonymizeMessageStep as jest.Mock++describe('ml-mirror anonymize concurrency', () => {+ const now = DateTime.now()++ const retentionService = {+ resolveSessionRetentions: jest.fn().mockImplementation((sessions: SessionSet) => {+ const resolutions = new SessionMap<RetentionResolution>()+ for (const s of sessions) {+ resolutions.set(s.teamId, s.sessionId, { resolved: true, retentionPeriod: '30d' })+ }+ return Promise.resolve(resolutions)+ }),+ } as unknown as RetentionService+ const sessionTracker = {+ hasSeen: jest.fn().mockImplementation((sessions: SessionSet) => {+ const map = new SessionMap<boolean>()+ for (const { teamId, sessionId } of sessions) {+ map.set(teamId, sessionId, true)+ }+ return Promise.resolve(map)+ }),+ markSeen: jest.fn().mockResolvedValue(undefined),+ } as unknown as SessionTracker+ const sessionFilter = {+ handleNewSessions: jest.fn().mockResolvedValue(new SessionSet()),+ isBlocked: jest.fn().mockResolvedValue(new SessionSet()),+ } as unknown as SessionFilter+ const keyStore = createMockKeyStore()+ const teamService = {+ getTeamByToken: jest.fn().mockResolvedValue({+ teamId: 1,+ consoleLogIngestionEnabled: false,+ aiTrainingOptedIn: true,+ } satisfies TeamForReplay),+ getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),+ } as unknown as TeamService++ let recordMock: jest.Mock+ let promiseScheduler: PromiseScheduler+ // Per `${sessionId}:${offset}`: a promise the mocked scrub awaits before completing.+ let scrubGates: Map<string, Promise<void>>+ let scrubStarts: Set<string>++ beforeEach(() => {+ jest.clearAllMocks()+ recordMock = jest.fn().mockResolvedValue(undefined)+ promiseScheduler = new PromiseScheduler()+ scrubGates = new Map()+ scrubStarts = new Set()++ mockCreateParseHeadersStep.mockReturnValue((input: { message: Message }) => {+ const headers: Record<string, string> = {}+ for (const header of input.message.headers || []) {+ for (const [key, value] of Object.entries(header)) {+ headers[key] = Buffer.isBuffer(value) ? value.toString() : (value as string)+ }+ }+ return Promise.resolve(ok({ ...input, headers }))+ })+ mockCreateApplyEventRestrictionsStep.mockReturnValue((input: unknown) => Promise.resolve(ok(input)))+ mockCreateParseAndAnonymizeMessageStep.mockReturnValue(+ async (input: { message: Message; headers: Record<string, string> }) => {+ const scrubKey = `${input.headers.session_id}:${input.message.offset}`+ scrubStarts.add(scrubKey)+ await (scrubGates.get(scrubKey) ?? Promise.resolve())+ const parsedMessage: ParsedMessageData = {+ metadata: {+ partition: input.message.partition,+ topic: input.message.topic,+ rawSize: input.message.size,+ offset: input.message.offset,+ timestamp: input.message.timestamp!,+ },+ distinct_id: 'user-123',+ session_id: input.headers.session_id,+ token: input.headers.token,+ eventsByWindowId: {},+ preSerialized: {+ lines: Buffer.from('["window-1",{}]\n'),+ events: [],+ consoleLogCount: 0,+ consoleWarnCount: 0,+ consoleErrorCount: 0,+ },+ eventsRange: { start: now, end: now },+ snapshot_source: null,+ snapshot_library: null,+ }+ return ok({ ...input, parsedMessage })+ }+ )+ })++ function buildPipeline(): ReturnType<typeof createMlMirrorReplayPipeline> {+ return createMlMirrorReplayPipeline(+ {+ outputs: createMockIngestionOutputs(),+ eventIngestionRestrictionManager: {} as unknown as EventIngestionRestrictionManager,+ overflowMode: 'disabled',+ promiseScheduler,+ teamService,+ retentionService,+ sessionTracker,+ sessionFilter,+ keyStore,+ sessionKeyResolutionMaxConcurrency: 20,+ topHog: {+ registerSum: jest.fn().mockReturnValue({ record: jest.fn() }),+ registerMax: jest.fn().mockReturnValue({ record: jest.fn() }),+ registerAverage: jest.fn().mockReturnValue({ record: jest.fn() }),+ } as unknown as TopHogRegistry,+ isDebugLoggingEnabled: () => false,+ },+ { anonymizeMaxConcurrency: 2 }+ )+ }++ function message(sessionId: string, offset: number): Message {+ return {+ partition: 0,+ offset,+ topic: 'test-topic',+ value: Buffer.from('irrelevant, the scrub step is mocked'),+ key: Buffer.from('k'),+ timestamp: Date.now(),+ headers: [+ { token: Buffer.from('test-token') },+ { session_id: Buffer.from(sessionId) },+ { distinct_id: Buffer.from('user-123') },+ ],+ size: 10,+ } as unknown as Message+ }++ function recordedOffsets(sessionId: string): number[] {+ return recordMock.mock.calls+ .filter((call) => call[0].message.session_id === sessionId)+ .map((call) => call[0].message.metadata.offset)+ }++ async function until(condition: () => boolean): Promise<void> {+ for (let i = 0; i < 5000 && !condition(); i++) {+ await new Promise(setImmediate)+ }+ if (!condition()) {+ throw new Error('condition not reached while a scrub gate was held')+ }+ }++ it('scrubs messages concurrently, including messages of the same session', async () => {+ let releaseFirstScrub!: () => void+ let releaseSecondScrub!: () => void+ scrubGates.set('sess-a:1', new Promise<void>((resolve) => (releaseFirstScrub = resolve)))+ scrubGates.set('sess-a:2', new Promise<void>((resolve) => (releaseSecondScrub = resolve)))++ const recorder = {+ record: recordMock,+ getRetention: jest.fn().mockReturnValue(undefined),+ } as unknown as SessionBatchRecorder+ const run = runSessionReplayPipeline(+ buildPipeline(),+ [message('sess-a', 1), message('sess-a', 2), message('sess-b', 3)],+ recorder,+ promiseScheduler+ )++ try {+ // Both of sess-a's scrubs are in flight at once — sequential processing never starts+ // the second scrub while the first is gated, and per-session grouping never starts a+ // session's second message while its first is gated.+ await until(() => scrubStarts.has('sess-a:1') && scrubStarts.has('sess-a:2'))+ } finally {+ releaseFirstScrub()+ releaseSecondScrub()+ }+ await run++ // No ordering guarantees, so only membership is asserted.+ expect(recordedOffsets('sess-a').sort()).toEqual([1, 2])+ expect(recordedOffsets('sess-b')).toEqual([3])+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.tsindex 39ce9a456583..d5d5d40214a2 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts@@ -128,20 +128,23 @@ describe('ml-mirror-pipeline', () => {})function buildPipeline(): ReturnType<typeof createMlMirrorReplayPipeline> {- return createMlMirrorReplayPipeline({- outputs,- eventIngestionRestrictionManager: {} as unknown as EventIngestionRestrictionManager,- overflowMode: 'disabled',- promiseScheduler,- teamService: mockTeamService,- retentionService,- sessionTracker,- sessionFilter,- keyStore,- sessionKeyResolutionMaxConcurrency: 20,- topHog,- isDebugLoggingEnabled: () => false,- })+ return createMlMirrorReplayPipeline(+ {+ outputs,+ eventIngestionRestrictionManager: {} as unknown as EventIngestionRestrictionManager,+ overflowMode: 'disabled',+ promiseScheduler,+ teamService: mockTeamService,+ retentionService,+ sessionTracker,+ sessionFilter,+ keyStore,+ sessionKeyResolutionMaxConcurrency: 20,+ topHog,+ isDebugLoggingEnabled: () => false,+ },+ { anonymizeMaxConcurrency: 4 }+ )}function message(sessionId: string): Message {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.tsindex 19efc89944c9..a02193d2dadf 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@@ -22,7 +22,15 @@ import { createResolveKeyStep } from '~/ingestion/pipelines/sessionreplay/sessioimport { createTeamFilterStep } from '~/ingestion/pipelines/sessionreplay/team-filter-step'import { createValidateSessionReplayHeadersStep } from '~/ingestion/pipelines/sessionreplay/validate-headers-step'-export function createMlMirrorReplayPipeline(config: SessionReplayPipelineConfig): SessionReplayPipeline {+export interface MlMirrorPipelineOptions {+ /** Cap on sessions scrubbed concurrently; each in-flight scrub occupies a libuv threadpool thread. */+ anonymizeMaxConcurrency: number+}++export function createMlMirrorReplayPipeline(+ config: SessionReplayPipelineConfig,+ mlOptions: MlMirrorPipelineOptions+): SessionReplayPipeline {const {outputs,eventIngestionRestrictionManager,@@ -112,38 +120,43 @@ export function createMlMirrorReplayPipeline(config: SessionReplayPipelineConfigb.teamAware((b) =>b- .sequentially((b) => {- // The native Rust addon fuses parse+anonymize in one step.- const parsed = b.pipe(- topHogWrapper(createParseAndAnonymizeMessageStep(), [- timer('parse_time_ms_by_session_id', (input) => ({- token: input.headers.token ?? 'unknown',- session_id: input.headers.session_id ?? 'unknown',- })),- ])- )- return parsed.pipe(- topHogWrapper(- createRecordSessionEventStep({- isDebugLoggingEnabled,- }),- [- sum(- 'message_size_by_session_id',- (input) => ({+ // Downstream consumers don't require event order within a+ // session's block, so scrubbing is free to complete out of order.+ .concurrently(+ (b) => {+ // The native Rust addon fuses parse+anonymize in one step.+ const parsed = b.pipe(+ topHogWrapper(createParseAndAnonymizeMessageStep(), [+ timer('parse_time_ms_by_session_id', (input) => ({+ token: input.headers.token ?? 'unknown',+ session_id: input.headers.session_id ?? 'unknown',+ })),+ ])+ )+ return parsed.pipe(+ topHogWrapper(+ createRecordSessionEventStep({+ isDebugLoggingEnabled,+ }),+ [+ sum(+ 'message_size_by_session_id',+ (input) => ({+ token: input.parsedMessage.token ?? 'unknown',+ session_id: input.parsedMessage.session_id,+ }),+ (input) => input.parsedMessage.metadata.rawSize+ ),+ timer('consume_time_ms_by_session_id', (input) => ({token: input.parsedMessage.token ?? 'unknown',session_id: input.parsedMessage.session_id,- }),- (input) => input.parsedMessage.metadata.rawSize- ),- timer('consume_time_ms_by_session_id', (input) => ({- token: input.parsedMessage.token ?? 'unknown',- session_id: input.parsedMessage.session_id,- })),- ]+ })),+ ]+ ))- )- })+ },+ { maxConcurrency: mlOptions.anonymizeMaxConcurrency }+ ).gather()).handleIngestionWarnings(outputs)diff --git a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.tsindex 1e32dbc74870..52053b3162b9 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts@@ -19,7 +19,11 @@ import {SessionRecordingIngester,SessionRecordingIngesterCollaborators,} from '~/ingestion/pipelines/sessionreplay/consumer'-import { MlMirrorConfig, getDefaultMlMirrorConfig } from '~/ingestion/pipelines/sessionreplay/ml-mirror/config'+import {+ MlMirrorConfig,+ getDefaultMlMirrorConfig,+ resolveMlAnonymizeMaxConcurrency,+} from '~/ingestion/pipelines/sessionreplay/ml-mirror/config'import { MlBlockMetadataSink } from '~/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink'import { createMlMirrorReplayPipeline } from '~/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline'import { resolvePseudonymKey } from '~/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key'@@ -153,7 +157,12 @@ export class IngestionSessionReplayMlMirrorServer implements NodeServer {featureStore: new SessionFeatureStore(outputs, false),keyStore,encryptor: new CleartextRecordingEncryptor(keyStore),- createPipeline: (pipelineConfig) => createMlMirrorReplayPipeline(pipelineConfig),+ createPipeline: (pipelineConfig) =>+ createMlMirrorReplayPipeline(pipelineConfig, {+ anonymizeMaxConcurrency: resolveMlAnonymizeMaxConcurrency(+ this.config.SESSION_RECORDING_ML_ANONYMIZE_MAX_CONCURRENCY+ ),+ }),// Isolate the mirror's session tracker/filter keys from the main lane. Sharing them would let// the cleartext mirror mark a session seen without the main lane's KMS key, so the main lane// would then fetch a missing key and record cleartext.