Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(ai-research): overlap ML mirror batches across prepare, anonymize and commit stages (#101643)

Robbie7faf194f50ce
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/batch-handle.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/batch-handle.ts
new file mode 100644
index 000000000000..dc9379fe4b1f
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/batch-handle.ts
@@ -0,0 +1,111 @@
+import { Message } from 'node-rdkafka'
+import pLimit from 'p-limit'
+
+import { PromiseScheduler } from '~/common/utils/promise-scheduler'
+import { PipelineResult, PipelineResultType, ok } from '~/ingestion/framework/results'
+import { SessionBatchContext } from '~/ingestion/pipelines/sessionreplay/session-batch-context'
+import { SessionBatchRecorder } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder'
+import { SessionKey } from '~/ingestion/pipelines/sessionreplay/shared/types'
+import { PartitionOwnership } from '~/ingestion/pipelines/sessionreplay/staged-batch'
+
+import { MlKeyBatchController } from './keys/batch-controller'
+import { MlKeyBatch, MlSessionKeys } from './keys/key-store'
+import { MlMirrorMetrics } from './metrics'
+
+export interface MlDeferrableInput {
+ message: Message
+ team: { teamId: number }
+ headers: { session_id: string }
+ sessionKey: SessionKey
+ sessionBatchRecorder: Pick<SessionBatchRecorder, 'getRetention'>
+ mlKeys?: MlSessionKeys
+}
+
+type SideEffectSink = (promises: Promise<unknown>[]) => Promise<void>
+/** Runs the deferred step and answers with the message it recorded, or null when the step skipped or failed it. */
+type DeferredAction = (
+ recorder: SessionBatchRecorder,
+ sideEffects: SideEffectSink,
+ isAssigned: PartitionOwnership
+) => Promise<Message | null>
+
+/**
+ * One poll batch's publication state: the keys it prepared and the record and produce steps it put off
+ * until those keys are committed. The handle rides on every element of the batch and on the batch
+ * context, so the commit stage reaches it whether or not any message survived.
+ */
+export class MlBatchHandle {
+ public keys?: MlKeyBatch
+ private deferred: DeferredAction[] = []
+ private readonly publish = pLimit(8)
+
+ constructor(private readonly keyManager?: MlKeyBatchController) {}
+
+ public defer<T extends MlDeferrableInput>(
+ input: T,
+ action: (input: T & SessionBatchContext) => Promise<PipelineResult<unknown>>,
+ recordsMessage = false
+ ): Promise<PipelineResult<T>> {
+ this.deferred.push(async (recorder, sideEffects, isAssigned) => {
+ if (!isAssigned(input.message.partition)) {
+ return null
+ }
+ const key = this.keyManager
+ ? this.keyManager.sessionKey(this.keys, input.headers.session_id, input.team.teamId)
+ : input.sessionKey
+ if (key.sessionState === 'deleted') {
+ return null
+ }
+ // The keys are the ones the commit settled on, which differ from the prepared ones when another writer stored the session first.
+ const mlKeys = this.keys?.get(input.team.teamId, input.headers.session_id)
+ const result = await action({ ...input, sessionKey: key, sessionBatchRecorder: recorder, mlKeys })
+ if (result.type !== PipelineResultType.OK) {
+ return null
+ }
+ await sideEffects(result.sideEffects ?? [])
+ return recordsMessage ? input.message : null
+ })
+ return Promise.resolve(ok(input))
+ }
+
+ // The recorder is the one current when the commit runs, not when the batch was fed: a flush can land between the two, and a record into the flushed recorder would be lost. Delivery acks go to the consumer's scheduler, which drains before offsets commit, so publication runs at enqueue speed.
+ public async commit(
+ recorder: SessionBatchRecorder,
+ scheduler?: PromiseScheduler,
+ isAssigned: PartitionOwnership = () => true
+ ): Promise<Message[]> {
+ if (this.keys && this.keyManager) {
+ await this.keyManager.commit(this.keys)
+ }
+ const startedAt = performance.now()
+ const sideEffects: SideEffectSink = async (promises) => {
+ if (!promises.length) {
+ return
+ }
+ if (scheduler) {
+ for (const promise of promises) {
+ void scheduler.schedule(promise)
+ }
+ } else {
+ await Promise.all(promises)
+ }
+ }
+ const actions = this.deferred
+ this.deferred = []
+ if (!actions.length) {
+ return []
+ }
+ // Every action settles before this returns, because the caller holds the batch lock that stops a revoke flush replacing the recorder mid-write.
+ const settled = await Promise.allSettled(
+ actions.map((action) => this.publish(() => action(recorder, sideEffects, isAssigned)))
+ )
+ MlMirrorMetrics.observeMlKeyPhase('publish', performance.now() - startedAt)
+ const failed = settled.find((result): result is PromiseRejectedResult => result.status === 'rejected')
+ if (failed) {
+ throw failed.reason
+ }
+ return settled.flatMap((result) =>
+ result.status === 'fulfilled' && result.value !== null ? [result.value] : []
+ )
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/batch-controller.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/batch-controller.ts
index d02db7f562e0..6a72f19b0d07 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/batch-controller.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/batch-controller.ts
@@ -1,7 +1,3 @@
-import pLimit from 'p-limit'
-
-import { PromiseScheduler } from '~/common/utils/promise-scheduler'
-import { PipelineResult, PipelineResultType, ok } from '~/ingestion/framework/results'
import { MlMirrorMetrics } from '~/ingestion/pipelines/sessionreplay/ml-mirror/metrics'
import { usesRawSessionIdentifiers } from '~/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format'
import {
@@ -13,17 +9,28 @@ import {
} from '~/ingestion/pipelines/sessionreplay/shared/types'
import { MlKeyEncryption, encryptEnvelope } from './crypto'
-import { MlKeyBatch, MlSessionKeyStore, MlSessionKeys } from './key-store'
+import { MlKeyBatch, MlSessionKeyStore } from './key-store'
import { MlKeyIdentity, MlSessionIdentity } from './schema'
export interface MlRecordingKey extends SessionKey {
mlIdentity: MlKeyIdentity
}
+const CLEARTEXT_KEY: SessionKey = {
+ sessionState: 'cleartext',
+ plaintextKey: Buffer.alloc(0),
+ encryptedKey: Buffer.alloc(0),
+}
+
+const DELETED_KEY: SessionKey = {
+ sessionState: 'deleted',
+ plaintextKey: Buffer.alloc(0),
+ encryptedKey: Buffer.alloc(0),
+}
+
export class MlKeyBatchController implements KeyStore, RecordingEncryptor {
- private readonly publish = pLimit(8)
- private batch?: MlKeyBatch
- private deferred: Array<(sideEffects: (promises: Promise<unknown>[]) => Promise<void>) => Promise<void>> = []
+ // The session resolution stage resolves keys through the KeyStore interface, which names no batch, so it reads the batch prepared last. That stage runs one batch at a time, so the batch prepared last is the one it is resolving.
+ private resolving?: MlKeyBatch
constructor(
private readonly store: MlSessionKeyStore,
@@ -38,81 +45,29 @@ export class MlKeyBatchController implements KeyStore, RecordingEncryptor {
this.encryption.clear()
}
- public reset(): void {
- this.batch = undefined
- this.deferred = []
- }
-
- public async prepare(identities: MlSessionIdentity[]): Promise<void> {
- this.deferred = []
+ public async prepare(identities: MlSessionIdentity[]): Promise<MlKeyBatch> {
const startedAt = performance.now()
- this.batch = await this.store.prepare(
+ const batch = await this.store.prepare(
identities.filter((identity) => usesRawSessionIdentifiers(identity.sessionId))
)
MlMirrorMetrics.observeMlKeyPhase('prepare', performance.now() - startedAt)
+ this.resolving = batch
+ return batch
}
- public keys(teamId: number, sessionId: string): MlSessionKeys | undefined {
- return this.batch?.get(teamId, sessionId)
- }
-
- public defer<T extends { team: { teamId: number }; headers: { session_id: string }; sessionKey: SessionKey }>(
- input: T,
- action: (input: T) => Promise<PipelineResult<T>>
- ): Promise<PipelineResult<T>> {
- this.deferred.push(async (sideEffects) => {
- const key = await this.getKey(input.headers.session_id, input.team.teamId)
- if (key.sessionState !== 'deleted') {
- const result = await action({ ...input, sessionKey: key })
- if (result.type === PipelineResultType.OK) {
- await sideEffects(result.sideEffects ?? [])
- }
- }
- })
- return Promise.resolve(ok(input))
- }
-
- // Delivery acks are handed to the consumer's scheduler, which drains before offsets commit, so publication runs at enqueue speed instead of one ack round trip per message.
- public async commit(scheduler?: PromiseScheduler): Promise<void> {
- if (!this.batch) {
- return
- }
+ public async commit(batch: MlKeyBatch): Promise<void> {
const startedAt = performance.now()
- await this.batch.commit()
- const committedAt = performance.now()
- MlMirrorMetrics.observeMlKeyPhase('commit', committedAt - startedAt)
- const sideEffects = async (promises: Promise<unknown>[]): Promise<void> => {
- if (!promises.length) {
- return
- }
- if (scheduler) {
- for (const promise of promises) {
- void scheduler.schedule(promise)
- }
- } else {
- await Promise.all(promises)
- }
- }
- await Promise.all(this.deferred.map((action) => this.publish(() => action(sideEffects))))
- this.deferred = []
- MlMirrorMetrics.observeMlKeyPhase('publish', performance.now() - committedAt)
+ await batch.commit()
+ MlMirrorMetrics.observeMlKeyPhase('commit', performance.now() - startedAt)
}
- public getKey(sessionId: string, teamId: number): Promise<SessionKey> {
+ public sessionKey(batch: MlKeyBatch | undefined, sessionId: string, teamId: number): SessionKey {
if (!usesRawSessionIdentifiers(sessionId)) {
- return Promise.resolve({
- sessionState: 'cleartext',
- plaintextKey: Buffer.alloc(0),
- encryptedKey: Buffer.alloc(0),
- })
+ return CLEARTEXT_KEY
}
- const keys = this.keys(teamId, sessionId)
+ const keys = batch?.get(teamId, sessionId)
if (!keys) {
- return Promise.resolve({
- sessionState: 'deleted',
- plaintextKey: Buffer.alloc(0),
- encryptedKey: Buffer.alloc(0),
- })
+ return DELETED_KEY
}
const key: MlRecordingKey = {
sessionState: 'ciphertext',
@@ -120,7 +75,11 @@ export class MlKeyBatchController implements KeyStore, RecordingEncryptor {
encryptedKey: keys.session.wrapped,
mlIdentity: keys.session.identity,
}
- return Promise.resolve(key)
+ return key
+ }
+
+ public getKey(sessionId: string, teamId: number): Promise<SessionKey> {
+ return Promise.resolve(this.sessionKey(this.resolving, sessionId, teamId))
}
public generateKey(sessionId: string, teamId: number): Promise<SessionKey> {
@@ -131,8 +90,11 @@ export class MlKeyBatchController implements KeyStore, RecordingEncryptor {
return Promise.reject(new Error('ML deletion requires the durable deletion workflow'))
}
- public async encryptBlock(sessionId: string, teamId: number, data: Buffer): Promise<EncryptResult> {
- return this.encryptBlockWithKey(sessionId, teamId, data, await this.getKey(sessionId, teamId))
+ // Batches overlap, so the batch that prepared last owns no particular session. A block carries the key the session was recorded with.
+ public encryptBlock(_sessionId: string, _teamId: number, _data: Buffer): Promise<EncryptResult> {
+ return Promise.reject(
+ new Error('ML blocks need the key recorded on the session, so encryptBlockWithKey is required')
+ )
}
public encryptBlockWithKey(_sessionId: string, _teamId: number, data: Buffer, key: SessionKey): EncryptResult {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts
index c487f980b114..b047a78790ff 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts
@@ -13,10 +13,12 @@ import { register } from 'prom-client'
import { parseJSON } from '~/common/utils/json-parse'
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
import { ok } from '~/ingestion/framework/results'
+import { MlBatchHandle } from '~/ingestion/pipelines/sessionreplay/ml-mirror/batch-handle'
import { BlockMetadataBatcher } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher'
import { BlockMetadataParquetStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store'
import { toBlockMetadataRow } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-row'
import { MlMirrorMetrics } from '~/ingestion/pipelines/sessionreplay/ml-mirror/metrics'
+import { SessionBatchRecorder } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder'
import { createNoopBlockMetadata } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata'
import { MlKeyBatchController } from './batch-controller'
@@ -41,6 +43,13 @@ const session: MlSessionIdentity = {
}
const table = 'ml-keys-test'
+const recorder = {
+ record: jest.fn(),
+ getRetention: jest.fn(),
+ flush: jest.fn(),
+ size: 0,
+} as unknown as SessionBatchRecorder
+
function transientError(name: string): Error {
return Object.assign(new Error(name), { name })
}
@@ -855,19 +864,22 @@ describe('ML session key batches', () => {
it('publishes only after key writes commit and hands delivery acks to the scheduler', async () => {
const identity = { ...session, sessionId: '01a0a4f0-3200-7000-8000-000000000001' }
const controller = new MlKeyBatchController(store, encryption)
- await controller.prepare([identity])
+ const handle = new MlBatchHandle(controller)
+ handle.keys = await controller.prepare([identity])
let release!: () => void
const delivery = new Promise<void>((resolve) => {
release = resolve
})
let started = 0
const input = {
+ message: {} as Message,
team: { teamId: identity.teamId },
headers: { session_id: identity.sessionId },
sessionKey: await controller.getKey(identity.sessionId, identity.teamId),
+ sessionBatchRecorder: recorder,
}
for (let index = 0; index < 20; index++) {
- await controller.defer(input, (value) => {
+ await handle.defer(input, (value) => {
expect(
boundary.items.get(tableKeyString(sessionKeyId(identity.teamId, identity.sessionId)))?.sealed_key
).not.toBeUndefined()
@@ -876,7 +888,7 @@ describe('ML session key batches', () => {
})
}
const scheduler = new PromiseScheduler()
- await controller.commit(scheduler)
+ await handle.commit(recorder, scheduler)
expect(started).toBe(20)
expect(scheduler.promises.size).toBe(1)
release()
@@ -887,19 +899,22 @@ describe('ML session key batches', () => {
it('waits for delivery acks itself when no scheduler owns them', async () => {
const identity = { ...session, sessionId: '01a0a4f0-3200-7000-8000-000000000002' }
const controller = new MlKeyBatchController(store, encryption)
- await controller.prepare([identity])
+ const handle = new MlBatchHandle(controller)
+ handle.keys = await controller.prepare([identity])
let release!: () => void
const delivery = new Promise<void>((resolve) => {
release = resolve
})
const input = {
+ message: {} as Message,
team: { teamId: identity.teamId },
headers: { session_id: identity.sessionId },
sessionKey: await controller.getKey(identity.sessionId, identity.teamId),
+ sessionBatchRecorder: recorder,
}
- await controller.defer(input, (value) => Promise.resolve(ok(value, [delivery])))
+ await handle.defer(input, (value) => Promise.resolve(ok(value, [delivery])))
let committed = false
- const committing = controller.commit().then(() => {
+ const committing = handle.commit(recorder).then(() => {
committed = true
})
await new Promise((resolve) => setImmediate(resolve))
@@ -908,6 +923,93 @@ describe('ML session key batches', () => {
await committing
expect(committed).toBe(true)
})
+
+ it('hands deferred steps the keys the commit settled on, not the ones prepared', async () => {
+ const competitor = new MlSessionKeyStore(
+ new MlKeyDynamoDB(boundary as unknown as DynamoDBClient, table),
+ encryption
+ )
+ const identity = { ...session, sessionId: '01a0a4f0-3200-7000-8000-000000000004' }
+ const controller = new MlKeyBatchController(store, encryption)
+ const handle = new MlBatchHandle(controller)
+ handle.keys = await controller.prepare([identity])
+ const prepared = handle.keys.get(identity.teamId, identity.sessionId)!
+ const winner = await competitor.prepare([identity])
+ await winner.commit()
+ const seen: Buffer[] = []
+ await handle.defer(
+ {
+ message: {} as Message,
+ team: { teamId: identity.teamId },
+ headers: { session_id: identity.sessionId },
+ sessionKey: await controller.getKey(identity.sessionId, identity.teamId),
+ sessionBatchRecorder: recorder,
+ mlKeys: prepared,
+ },
+ (value) => {
+ seen.push(value.mlKeys!.session.plaintext, value.sessionKey.plaintextKey)
+ return Promise.resolve(ok(value))
+ }
+ )
+ jest.useFakeTimers()
+ const committing = handle.commit(recorder)
+ await jest.runAllTimersAsync()
+ await committing
+ // A sealed session key carries no KMS blob, so the plaintext is what tells the settled key from the prepared one.
+ const stored = winner.get(identity.teamId, identity.sessionId)!.session.plaintext
+ expect(seen).toEqual([stored, stored])
+ expect(stored).not.toEqual(prepared.session.plaintext)
+ })
+
+ it('refuses to encrypt a block without the session key, because batches overlap', async () => {
+ const controller = new MlKeyBatchController(store, encryption)
+ await controller.prepare([session])
+ await expect(controller.encryptBlock(session.sessionId, session.teamId, Buffer.alloc(4))).rejects.toThrow(
+ 'encryptBlockWithKey'
+ )
+ })
+
+ it('reports a message once however many steps the batch defers', async () => {
+ const identity = { ...session, sessionId: '01a0a4f0-3200-7000-8000-000000000005' }
+ const controller = new MlKeyBatchController(store, encryption)
+ const handle = new MlBatchHandle(controller)
+ handle.keys = await controller.prepare([identity])
+ const message = { partition: 3, offset: 9 } as unknown as Message
+ const input = {
+ message,
+ team: { teamId: identity.teamId },
+ headers: { session_id: identity.sessionId },
+ sessionKey: await controller.getKey(identity.sessionId, identity.teamId),
+ sessionBatchRecorder: recorder,
+ }
+ await handle.defer(input, (value) => Promise.resolve(ok(value)))
+ await handle.defer(input, (value) => Promise.resolve(ok(value)))
+ await handle.defer(input, (value) => Promise.resolve(ok(value)), true)
+ expect(await handle.commit(recorder)).toEqual([message])
+ })
+
+ it('records into the recorder handed to the commit, not the one the message was fed with', async () => {
+ const identity = { ...session, sessionId: '01a0a4f0-3200-7000-8000-000000000003' }
+ const controller = new MlKeyBatchController(store, encryption)
+ const handle = new MlBatchHandle(controller)
+ handle.keys = await controller.prepare([identity])
+ const flushed = { ...recorder, size: 1 } as unknown as SessionBatchRecorder
+ const current = { ...recorder, size: 2 } as unknown as SessionBatchRecorder
+ const input = {
+ message: {} as Message,
+ team: { teamId: identity.teamId },
+ headers: { session_id: identity.sessionId },
+ sessionKey: await controller.getKey(identity.sessionId, identity.teamId),
+ sessionBatchRecorder: flushed,
+ }
+ const seen: SessionBatchRecorder[] = []
+ await handle.defer(input, (value) => {
+ seen.push(value.sessionBatchRecorder)
+ return Promise.resolve(ok(value))
+ })
+ await handle.commit(current)
+ expect(seen).toEqual([current])
+ })
it.each(['invalid-json', 'oversized-session', 'invalid-session', 'invalid-month'])(
'reports accepted, malformed (%s) and deleted metadata rows separately',
async (malformed) => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts
index b84a964f56c4..c222f256ccb0 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts
@@ -260,7 +260,7 @@ export class MlKeyBatch {
this.encryption.rememberCommitted(key)
return
}
- // A session keys its own partition, so only a rebalance overlap or a team key puts two writers on one row.
+ // Batches overlap, so a later batch reads before an earlier one writes, and a new session routinely meets its own earlier candidate here.
if (stored.deleted?.BOOL === true) {
this.keys.delete(id)
dropped += 1
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
index f13e39d3ae5d..f0b52d4eb6be 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
@@ -158,7 +158,7 @@ export class MlMirrorMetrics {
})
private static readonly mlKeyPhaseDuration = new Histogram({
name: 'recording_blob_ingestion_v2_ml_key_phase_duration_ms',
- help: 'Wall time of one ML key phase per Kafka batch. The consumer handles one batch at a time, so these phases plus anonymization are the batch wall time; a phase that dominates while pod CPU stays low is the lane waiting on KMS, DynamoDB or Kafka rather than working',
+ help: 'Wall time of one ML key phase per Kafka batch. Prepare runs in the prepare stage and commit and publish in the commit stage, so a phase that dominates its stage while pod CPU stays low is the lane waiting on KMS, DynamoDB or Kafka rather than working',
labelNames: ['phase'],
buckets: [1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000, Infinity],
})
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 2af239b98fb9..939bcc6f5b1d 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
@@ -1,28 +1,22 @@
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 { 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'
+ buildMlMirrorStagedRunner,
+ mlMirrorTestMessage,
+ mlMirrorTestPipelineConfig,
+ mlMirrorTestServices,
+ parseTestHeaders,
+ runMlMirrorBatch,
+ scrubbedTestMessage,
+} from '~/tests/helpers/ml-mirror-staged-batch'
+
import { createParseAndAnonymizeMessageStep } from './parse-and-anonymize-step'
+import { MlMirrorStagedBatchRunner } from './staged-batch-runner'
jest.mock('~/ingestion/common/steps/event-preprocessing', () => ({
createParseHeadersStep: jest.fn(),
@@ -40,39 +34,7 @@ describe('ml-mirror anonymize concurrency', () => {
const SESSION_A = '01a0a4f0-3200-7000-8000-000000000001'
const SESSION_B = '01a0a4f0-3200-7000-8000-000000000002'
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
+ const services = mlMirrorTestServices()
let recordMock: jest.Mock
let promiseScheduler: PromiseScheduler
@@ -87,89 +49,25 @@ describe('ml-mirror anonymize concurrency', () => {
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 }))
- })
+ mockCreateParseHeadersStep.mockReturnValue(parseTestHeaders)
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 })
+ return ok({ ...input, parsedMessage: scrubbedTestMessage(input, now) })
}
)
})
- 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 buildRunner(): MlMirrorStagedBatchRunner {
+ return buildMlMirrorStagedRunner(mlMirrorTestPipelineConfig(promiseScheduler, services), {
+ 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
- }
+ const message = mlMirrorTestMessage
function recordedOffsets(sessionId: string): number[] {
return recordMock.mock.calls
@@ -196,11 +94,10 @@ describe('ml-mirror anonymize concurrency', () => {
record: recordMock,
getRetention: jest.fn().mockReturnValue(undefined),
} as unknown as SessionBatchRecorder
- const run = runSessionReplayPipeline(
- buildPipeline(),
+ const run = runMlMirrorBatch(
+ buildRunner(),
[message(SESSION_A, 1), message(SESSION_A, 2), message(SESSION_B, 3)],
- recorder,
- promiseScheduler
+ recorder
)
try {
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.ts
index fb73c402638e..93aeceda556c 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
@@ -10,7 +10,6 @@ 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 { defaultAllowLists } from '~/ingestion/pipelines/sessionreplay/anonymize/default-dict'
import { SessionBatchRecorder } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder'
import { SessionFilter } from '~/ingestion/pipelines/sessionreplay/sessions/session-filter'
@@ -23,9 +22,10 @@ import { SessionMap, SessionSet } from '~/ingestion/pipelines/sessionreplay/shar
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 { buildMlMirrorStagedRunner, runMlMirrorBatch } from '~/tests/helpers/ml-mirror-staged-batch'
import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'
-import { createMlMirrorReplayPipeline } from './ml-mirror-pipeline'
+import { MlMirrorStagedBatchRunner } from './staged-batch-runner'
jest.mock('~/ingestion/common/steps/event-preprocessing', () => ({
createParseHeadersStep: jest.fn(),
@@ -130,8 +130,8 @@ describe('ml-mirror-pipeline', () => {
mockCreateApplyEventRestrictionsStep.mockReturnValue((input: unknown) => Promise.resolve(ok(input)))
})
- function buildPipeline(): ReturnType<typeof createMlMirrorReplayPipeline> {
- return createMlMirrorReplayPipeline(
+ function buildRunner(): MlMirrorStagedBatchRunner {
+ return buildMlMirrorStagedRunner(
{
outputs,
eventIngestionRestrictionManager: {} as unknown as EventIngestionRestrictionManager,
@@ -269,7 +269,7 @@ describe('ml-mirror-pipeline', () => {
getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),
} as unknown as TeamService
- await runSessionReplayPipeline(buildPipeline(), [message(V2_SESSION_ID)], mockBatchRecorder, promiseScheduler)
+ await runMlMirrorBatch(buildRunner(), [message(V2_SESSION_ID)], mockBatchRecorder)
expect(recordMock).toHaveBeenCalledTimes(1)
const [windowId, event] = recordedEvents()[0]
@@ -300,7 +300,7 @@ describe('ml-mirror-pipeline', () => {
getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),
} as unknown as TeamService
- await runSessionReplayPipeline(buildPipeline(), [message(V2_SESSION_ID_2)], mockBatchRecorder, promiseScheduler)
+ await runMlMirrorBatch(buildRunner(), [message(V2_SESSION_ID_2)], mockBatchRecorder)
expect(recordMock).not.toHaveBeenCalled()
})
@@ -311,12 +311,7 @@ describe('ml-mirror-pipeline', () => {
getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),
} as unknown as TeamService
- await runSessionReplayPipeline(
- buildPipeline(),
- [message('legacy-session-id')],
- mockBatchRecorder,
- promiseScheduler
- )
+ await runMlMirrorBatch(buildRunner(), [message('legacy-session-id')], mockBatchRecorder)
expect(retentionService.resolveSessionRetentions).not.toHaveBeenCalled()
expect(recordMock).not.toHaveBeenCalled()
@@ -328,12 +323,7 @@ describe('ml-mirror-pipeline', () => {
getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),
} as unknown as TeamService
- await runSessionReplayPipeline(
- buildPipeline(),
- [fullSnapshotMessage(V2_SESSION_ID_3)],
- mockBatchRecorder,
- promiseScheduler
- )
+ await runMlMirrorBatch(buildRunner(), [fullSnapshotMessage(V2_SESSION_ID_3)], mockBatchRecorder)
expect(recordMock).toHaveBeenCalledTimes(1)
const node = recordedEvents()[0][1].data.node.childNodes[0]
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 25661d56a3fb..86474d363400 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
@@ -1,33 +1,35 @@
-/** The primary session replay pipeline plus an AI-training opt-in filter and an anonymize step. */
+/** The primary session replay pipeline plus an AI-training opt-in filter and an anonymize step, split into the stages the staged batch runner overlaps. */
import { OverflowOutput } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import { BatchingContext, BatchingPipeline } from '~/ingestion/framework/batching-pipeline'
import { newBatchingPipeline } from '~/ingestion/framework/builders'
import { createTopHogWrapper, timer } from '~/ingestion/framework/extensions/tophog'
import { aggregateKafkaDebugContexts } from '~/ingestion/framework/helpers'
import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'
import { drop, ok } from '~/ingestion/framework/results'
import { ProcessingStep } from '~/ingestion/framework/steps'
-import {
- SessionReplayPipeline,
- SessionReplayPipelineConfig,
- SessionReplayPipelineInput,
- SessionReplayPipelineOutput,
-} from '~/ingestion/pipelines/sessionreplay'
+import { SessionReplayPipelineConfig, SessionReplayPipelineOutput } from '~/ingestion/pipelines/sessionreplay'
import { createAiTrainingOptInFilterStep } from '~/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step'
import type { CrawlHistoryStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history'
import { createProduceCollectedImagesStep } from '~/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step'
import { createProduceCollectedUrlsStep } from '~/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step'
import { MessageContext, SessionReplayHeaders } from '~/ingestion/pipelines/sessionreplay/pipeline-types'
import { createRecordSessionEventStep } from '~/ingestion/pipelines/sessionreplay/record-session-event-step'
-import { RecordSessionEventStepInput } from '~/ingestion/pipelines/sessionreplay/record-session-event-step'
+import { SessionBatchContext } from '~/ingestion/pipelines/sessionreplay/session-batch-context'
import {
+ SessionReplayPreprocessingInput,
addSessionReplayPreprocessing,
addSessionReplaySessionResolution,
withSessionReplayRecordingMetrics,
} from '~/ingestion/pipelines/sessionreplay/session-replay-pipeline-stages'
+import { RetentionPeriod } from '~/ingestion/pipelines/sessionreplay/shared/constants'
import { MlImageFetchOutput, MlImageScrubOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
+import { SessionKey } from '~/ingestion/pipelines/sessionreplay/shared/types'
+import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
+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 { mlSessionIdDropReason } from './session-identifier-format'
@@ -69,6 +71,44 @@ export interface MlMirrorCollection {
collectUrls: boolean
}
+/** What the prepare stage is fed: the message and a retention lookup, never the recorder, which a flush replaces while the batch is in flight. */
+export type MlPrepareInput = SessionReplayPreprocessingInput
+
+/** What the prepare stage hands the anonymize stage: a validated, key-resolved message with its batch handle. */
+export interface MlPreparedMessage extends MlPrepareInput {
+ headers: SessionReplayHeaders
+ team: TeamForReplay
+ retentionPeriod: RetentionPeriod
+ isNewSession: boolean
+ status: 'allowed'
+ sessionKey: SessionKey
+ mlBatch: MlBatchHandle
+ mlKeys?: MlSessionKeys
+}
+
+/** The batch handle also rides on the batch context, so the commit stage reaches it when no message survived. */
+export interface MlBatchContext {
+ mlBatch: MlBatchHandle
+}
+
+export type MlPreparePipeline = BatchingPipeline<
+ MlPrepareInput,
+ MlPreparedMessage,
+ MessageContext,
+ MlBatchContext,
+ MessageContext & BatchingContext,
+ OverflowOutput
+>
+
+export type MlAnonymizePipeline = BatchingPipeline<
+ MlPreparedMessage,
+ SessionReplayPipelineOutput,
+ MessageContext,
+ Record<never, object>,
+ MessageContext & BatchingContext,
+ OverflowOutput
+>
+
function createMlSessionIdFilterStep<T extends { headers: SessionReplayHeaders }>(
nowMs: () => number
): ProcessingStep<T, T> {
@@ -78,35 +118,33 @@ function createMlSessionIdFilterStep<T extends { headers: SessionReplayHeaders }
}
}
-export function createMlMirrorReplayPipeline(
+/**
+ * The I/O-bound front of the lane: header parsing, the opt-in and session ID filters, the key bulk
+ * read, retention, session tracking and key resolution. Nothing here needs the CPU for long, so the
+ * runner lets it work on the next batch while the anonymize stage scrubs the current one.
+ */
+export function createMlMirrorPreparePipeline(
config: SessionReplayPipelineConfig,
- mlOptions: MlMirrorPipelineOptions,
- imageScrub?: MlMirrorImageScrubProducer,
- collection?: MlMirrorCollection,
- urlFetch?: MlMirrorUrlFetchProducer
-): SessionReplayPipeline {
- const { outputs, promiseScheduler, topHog, isDebugLoggingEnabled } = config
-
+ mlOptions: MlMirrorPipelineOptions
+): MlPreparePipeline {
+ const { outputs, promiseScheduler } = config
const pipelineConfig: PipelineConfig<OverflowOutput> = { outputs, promiseScheduler }
- const topHogWrapper = createTopHogWrapper(topHog)
- function deferPublication<T extends RecordSessionEventStepInput & { headers: { session_id: string } }>(
- step: ProcessingStep<T, T>
- ): ProcessingStep<T, T> {
- return mlOptions.keyManager ? (input) => mlOptions.keyManager!.defer(input, step) : step
- }
return newBatchingPipeline<
- SessionReplayPipelineInput,
- SessionReplayPipelineOutput,
+ MlPrepareInput,
+ MlPreparedMessage,
MessageContext,
- Record<never, object>,
+ MlBatchContext,
MessageContext,
OverflowOutput
>(
(beforeBatch) =>
- beforeBatch.pipe(function passThroughBeforeBatch(input) {
- mlOptions.keyManager?.reset()
- return Promise.resolve(ok(input))
+ beforeBatch.pipe(function openMlBatch(input) {
+ const batchContext: MlBatchContext & typeof input.batchContext = {
+ ...input.batchContext,
+ mlBatch: new MlBatchHandle(mlOptions.keyManager),
+ }
+ return Promise.resolve(ok({ ...input, batchContext }))
}),
(batch) =>
batch
@@ -121,18 +159,91 @@ export function createMlMirrorReplayPipeline(
)
.gather()
.pipeChunk(async function readMlKeyBatch(values) {
+ if (!values.length) {
+ return []
+ }
+ // The batching pipeline merges the batch context into every element, which the preprocessing types do not carry.
+ const { mlBatch } = values[0] as unknown as MlBatchContext
if (mlOptions.keyManager) {
- await mlOptions.keyManager.prepare(
+ mlBatch.keys = await mlOptions.keyManager.prepare(
values.map((value) => ({
teamId: value.team.teamId,
sessionId: value.headers.session_id,
}))
)
}
- return values.map((value) => ok(value))
+ return values.map((value) => ok({ ...value, mlBatch }))
}),
config
- ).filterMap(
+ ).pipeChunk(function attachMlKeys(values) {
+ return Promise.resolve(
+ values.map((value) => {
+ const prepared: MlPreparedMessage = {
+ ...value,
+ mlKeys: value.mlBatch.keys?.get(value.team.teamId, value.headers.session_id),
+ }
+ return ok(prepared)
+ })
+ )
+ })
+ )
+ .handleResults(pipelineConfig)
+ .handleSideEffects(promiseScheduler, { await: false })
+ .gather(),
+ (afterBatch) =>
+ afterBatch.pipe(function passThroughAfterBatch(input) {
+ return Promise.resolve(ok(input))
+ }),
+ { concurrentBatches: 1 },
+ { aggregateDebugContexts: aggregateKafkaDebugContexts }
+ )
+}
+
+/**
+ * The CPU-bound middle of the lane: the fused parse and scrub in the Rust addon. The record and
+ * produce steps that follow it are deferred onto the batch handle, so this stage touches neither the
+ * recorder nor Kafka and the runner can hold it to one batch at a time without holding anything else.
+ */
+export function createMlMirrorAnonymizePipeline(
+ config: SessionReplayPipelineConfig,
+ mlOptions: MlMirrorPipelineOptions,
+ imageScrub?: MlMirrorImageScrubProducer,
+ collection?: MlMirrorCollection,
+ urlFetch?: MlMirrorUrlFetchProducer
+): MlAnonymizePipeline {
+ const { outputs, promiseScheduler, topHog, isDebugLoggingEnabled } = config
+
+ const pipelineConfig: PipelineConfig<OverflowOutput> = { outputs, promiseScheduler }
+ const topHogWrapper = createTopHogWrapper(topHog)
+ // 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>
+ ): ProcessingStep<T, T> {
+ return (input) => input.mlBatch.defer(input, step)
+ }
+ // Only the recording step answers with its message, so the lane reports lag once per message and not once per deferred step.
+ function deferRecording<T extends MlDeferrableInput & { mlBatch: MlBatchHandle }>(
+ step: ProcessingStep<T & SessionBatchContext, T & SessionBatchContext>
+ ): ProcessingStep<T, T> {
+ return (input) => input.mlBatch.defer(input, step, true)
+ }
+
+ return newBatchingPipeline<
+ MlPreparedMessage,
+ SessionReplayPipelineOutput,
+ MessageContext,
+ Record<never, object>,
+ MessageContext,
+ OverflowOutput
+ >(
+ (beforeBatch) =>
+ beforeBatch.pipe(function passThroughBeforeBatch(input) {
+ return Promise.resolve(ok(input))
+ }),
+ (batch) =>
+ batch
+ .messageAware((b) =>
+ b.filterMap(
(element) => ({
result: element.result,
context: {
@@ -154,8 +265,7 @@ export function createMlMirrorReplayPipeline(
createParseAndAnonymizeMessageStep(
collection?.collectImages || collection?.collectUrls
? collection
- : undefined,
- mlOptions.keyManager
+ : undefined
),
[
timer('parse_time_ms_by_session_id', (input) => ({
@@ -170,8 +280,7 @@ export function createMlMirrorReplayPipeline(
deferPublication(
createProduceCollectedImagesStep(
imageScrub.outputs,
- imageScrub.producedRefCacheMax,
- mlOptions.keyManager
+ imageScrub.producedRefCacheMax
)
)
)
@@ -184,15 +293,14 @@ export function createMlMirrorReplayPipeline(
producedRefCacheWindowMs:
urlFetch.producedRefCacheWindowMs,
crawlHistory: urlFetch.crawlHistory,
- keyManager: mlOptions.keyManager,
})
)
)
: withImagesProduced
return withUrlsProduced.pipe(
- withSessionReplayRecordingMetrics(
- topHog,
- deferPublication(
+ deferRecording(
+ withSessionReplayRecordingMetrics(
+ topHog,
createRecordSessionEventStep({
isDebugLoggingEnabled,
})
@@ -211,12 +319,9 @@ export function createMlMirrorReplayPipeline(
.handleSideEffects(promiseScheduler, { await: false })
.gather(),
(afterBatch) =>
- afterBatch.pipe(async function passThroughAfterBatch(input) {
- await mlOptions.keyManager?.commit(promiseScheduler)
- return ok(input)
+ afterBatch.pipe(function passThroughAfterBatch(input) {
+ return Promise.resolve(ok(input))
}),
- // One batch in flight at a time (also the framework default): each feed tags the manager's
- // current recorder, so a concurrent batch could span a flush and record into a stale recorder.
{ concurrentBatches: 1 },
{ aggregateDebugContexts: aggregateKafkaDebugContexts }
)
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 8e8cbecd7b19..941c82d9af2a 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
@@ -24,7 +24,7 @@ import {
} from '~/ingestion/pipelines/sessionreplay/parse-message-step'
import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
-import { MlKeyBatchController } from './keys/batch-controller'
+import { MlSessionKeys } from './keys/key-store'
import { MlMirrorMetrics } from './metrics'
import {
PSEUDONYM_IMAGE_CONTENT_KEY,
@@ -111,10 +111,9 @@ export interface ImageCollectionConfig {
* unencrypted ML bucket. Failure classification matches the TS parse step so DLQ/drop behavior and
* ingestion warnings are unchanged.
*/
-export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInput & { team: TeamForReplay }>(
- imageCollection?: ImageCollectionConfig,
- keyManager?: MlKeyBatchController
-): ProcessingStep<T, T & ParseAndAnonymizeStepOutput> {
+export function createParseAndAnonymizeMessageStep<
+ T extends ParseMessageStepInput & { team: TeamForReplay; mlKeys?: MlSessionKeys },
+>(imageCollection?: ImageCollectionConfig): ProcessingStep<T, T & ParseAndAnonymizeStepOutput> {
const globalUrlKey =
imageCollection?.collectUrls === true
? pseudonymize(imageCollection.pseudonymSecret, PSEUDONYM_IMAGE_URL_KEY, PSEUDONYM_IMAGE_URL_GLOBAL_VALUE)
@@ -173,7 +172,7 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInp
)
const teamKeys = teamKeysFor(input.team.teamId, headers.session_id)
- const sessionKeys = keyManager?.keys(input.team.teamId, headers.session_id)
+ const sessionKeys = input.mlKeys
let referenceNamespace: string | undefined
let imageTeamId: string | undefined
const t0 = performance.now()
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 a490a1f89b5e..72cae1ea2aca 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
@@ -6,7 +6,7 @@ import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/ml
import { ML_IMAGE_SCRUB_OUTPUT, MlImageScrubOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'
-import { MlKeyBatchController } from './keys/batch-controller'
+import { MlSessionKeys } from './keys/key-store'
import { mlKafkaRecord, mlWireVersion, validateImageOwner } from './keys/transport'
import { MlMirrorMetrics } from './metrics'
import { CollectedImage } from './parse-and-anonymize-step'
@@ -35,20 +35,17 @@ export function createProduceCollectedImagesStep<
headers?: { session_id: string }
collectedImages?: CollectedImage[]
message: { timestamp?: number }
+ mlKeys?: MlSessionKeys
},
>(
outputs: IngestionOutputs<MlImageScrubOutput>,
- producedRefCacheMax: number = PRODUCED_REF_CACHE_MAX,
- keyManager?: MlKeyBatchController
+ producedRefCacheMax: number = PRODUCED_REF_CACHE_MAX
): ProcessingStep<T, T> {
const producedRefs = new RefDedupCache('image_scrub_producer', producedRefCacheMax)
return function produceCollectedImagesStep(input) {
const sessionId = input.headers?.session_id
- const key =
- sessionId && usesRawSessionIdentifiers(sessionId) && input.team
- ? keyManager?.keys(input.team.teamId, sessionId)?.session
- : undefined
+ const key = sessionId && usesRawSessionIdentifiers(sessionId) ? input.mlKeys?.session : undefined
const images = input.collectedImages
if (!images?.length) {
return Promise.resolve(ok(input))
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 e99f277271ca..6bfb466f8128 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
@@ -10,7 +10,7 @@ import { parseImageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-ima
import { ML_IMAGE_FETCH_OUTPUT, MlImageFetchOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'
-import { MlKeyBatchController } from './keys/batch-controller'
+import { MlSessionKeys } from './keys/key-store'
import { mlKafkaRecord, mlWireVersion, validateImageOwner } from './keys/transport'
import { MlMirrorMetrics } from './metrics'
import { CollectedUrl } from './parse-and-anonymize-step'
@@ -62,7 +62,6 @@ export interface CollectedUrlsMessage {
}
export interface ProduceCollectedUrlsOptions {
- keyManager?: MlKeyBatchController
producedRefCacheMax?: number
producedRefCacheWindowMs?: number
crawlHistory?: Pick<CrawlHistoryStore, 'read'>
@@ -145,6 +144,7 @@ export function createProduceCollectedUrlsStep<
headers?: { session_id: string }
collectedUrls?: CollectedUrl[]
message: { timestamp?: number }
+ mlKeys?: MlSessionKeys
},
>(
outputs: IngestionOutputs<MlImageFetchOutput>,
@@ -169,10 +169,7 @@ export function createProduceCollectedUrlsStep<
return async function produceCollectedUrlsStep(input) {
const sessionId = input.headers?.session_id
- const key =
- sessionId && usesRawSessionIdentifiers(sessionId) && input.team
- ? options.keyManager?.keys(input.team.teamId, sessionId)?.session
- : undefined
+ const key = sessionId && usesRawSessionIdentifiers(sessionId) ? input.mlKeys?.session : undefined
const collected = input.collectedUrls
if (!collected?.length) {
return ok(input)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/staged-batch-runner.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/staged-batch-runner.test.ts
new file mode 100644
index 000000000000..dc27318cae02
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/staged-batch-runner.test.ts
@@ -0,0 +1,228 @@
+import { DateTime } from 'luxon'
+import { Message } from 'node-rdkafka'
+
+import { PromiseScheduler } from '~/common/utils/promise-scheduler'
+import { createApplyEventRestrictionsStep, createParseHeadersStep } from '~/ingestion/common/steps/event-preprocessing'
+import { ok } from '~/ingestion/framework/results'
+import { SessionReplayBatchProgress } from '~/ingestion/pipelines/sessionreplay'
+import { BatchStages } from '~/ingestion/pipelines/sessionreplay/batch-stages'
+import { SessionBatchRecorder } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder'
+import { BatchCommitter } from '~/ingestion/pipelines/sessionreplay/staged-batch'
+import {
+ buildMlMirrorStagedRunner,
+ mlMirrorTestMessage,
+ mlMirrorTestPipelineConfig,
+ mlMirrorTestServices,
+ parseTestHeaders,
+ scrubbedTestMessage,
+} from '~/tests/helpers/ml-mirror-staged-batch'
+
+import { createParseAndAnonymizeMessageStep } from './parse-and-anonymize-step'
+import { ML_BATCH_STAGES, MlMirrorStagedBatchRunner } from './staged-batch-runner'
+
+jest.mock('~/ingestion/common/steps/event-preprocessing', () => ({
+ createParseHeadersStep: jest.fn(),
+ createApplyEventRestrictionsStep: jest.fn(),
+}))
+jest.mock('./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 staged batch runner', () => {
+ const SESSION_A = '01a0a4f0-3200-7000-8000-000000000001'
+ const SESSION_B = '01a0a4f0-3200-7000-8000-000000000002'
+ const OPTED_IN_TOKEN = 'opted-in'
+ const OPTED_OUT_TOKEN = 'opted-out'
+ const now = DateTime.now()
+ const services = mlMirrorTestServices((token) => token === OPTED_IN_TOKEN)
+
+ let promiseScheduler: PromiseScheduler
+ let stages: BatchStages
+ // Per `${sessionId}:${offset}`: a promise the mocked scrub awaits before completing.
+ let scrubGates: Map<string, Promise<void>>
+ let scrubStarts: Set<string>
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ promiseScheduler = new PromiseScheduler()
+ stages = new BatchStages(ML_BATCH_STAGES)
+ scrubGates = new Map()
+ scrubStarts = new Set()
+
+ mockCreateParseHeadersStep.mockReturnValue(parseTestHeaders)
+ 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())
+ return ok({ ...input, parsedMessage: scrubbedTestMessage(input, now) })
+ }
+ )
+ })
+
+ function buildRunner(): MlMirrorStagedBatchRunner {
+ return buildMlMirrorStagedRunner(mlMirrorTestPipelineConfig(promiseScheduler, services), {
+ anonymizeMaxConcurrency: 2,
+ })
+ }
+
+ function message(sessionId: string, offset: number, token = OPTED_IN_TOKEN): Message {
+ return mlMirrorTestMessage(sessionId, offset, token)
+ }
+
+ function recorder(): jest.Mocked<SessionBatchRecorder> {
+ return {
+ record: jest.fn().mockResolvedValue(undefined),
+ getRetention: jest.fn().mockReturnValue(undefined),
+ } as unknown as jest.Mocked<SessionBatchRecorder>
+ }
+
+ function gate(key: string): () => void {
+ let release!: () => void
+ scrubGates.set(key, new Promise<void>((resolve) => (release = resolve)))
+ return release
+ }
+
+ 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('prepares the next batch while the current one scrubs, and scrubs it only once the current one is done', async () => {
+ const releaseA = gate(`${SESSION_A}:1`)
+ const releaseB = gate(`${SESSION_B}:2`)
+ const runner = buildRunner()
+ const committed: number[] = []
+ const committer: BatchCommitter = {
+ knownRetention: () => undefined,
+ commit: async (write) => {
+ committed.push(...(await write(recorder(), () => true)).okMessages.map((m) => m.offset))
+ },
+ }
+
+ const first = runner.run([message(SESSION_A, 1)], stages.admit(), committer)
+ const second = runner.run([message(SESSION_B, 2)], stages.admit(), committer)
+ try {
+ await until(() => scrubStarts.has(`${SESSION_A}:1`))
+ // The second batch's prepare stage ran to its end (the seen-mark is its last step) while the first batch's scrub was still held.
+ await until(() => (services.sessionTracker.markSeen as jest.Mock).mock.calls.length === 2)
+ expect(scrubStarts.has(`${SESSION_B}:2`)).toBe(false)
+ releaseA()
+ await until(() => scrubStarts.has(`${SESSION_B}:2`))
+ } finally {
+ releaseA()
+ releaseB()
+ }
+ await Promise.all([first, second])
+
+ expect(committed).toEqual([1, 2])
+ })
+
+ it('records into the recorder current at commit time, not the one current at feed time', async () => {
+ const releaseA = gate(`${SESSION_A}:1`)
+ const runner = buildRunner()
+ const fedWith = recorder()
+ const flushedInto = recorder()
+ let current = fedWith
+ const committer: BatchCommitter = {
+ knownRetention: (teamId, sessionId) => current.getRetention(teamId, sessionId),
+ commit: async (write) => {
+ await write(current, () => true)
+ },
+ }
+
+ const run = runner.run([message(SESSION_A, 1)], stages.admit(), committer)
+ try {
+ await until(() => scrubStarts.has(`${SESSION_A}:1`))
+ current = flushedInto
+ } finally {
+ releaseA()
+ }
+ await run
+
+ expect(fedWith.record).not.toHaveBeenCalled()
+ expect(flushedInto.record).toHaveBeenCalledTimes(1)
+ })
+
+ it('advances the offset past dropped messages but reports only recorded ones as recorded', async () => {
+ const runner = buildRunner()
+ let maxOffsets: Map<number, number> | undefined
+ let recorded: number[] = []
+ const committer: BatchCommitter = {
+ knownRetention: () => undefined,
+ commit: async (write) => {
+ const progress = await write(recorder(), () => true)
+ recorded = progress.okMessages.map((m) => m.offset)
+ maxOffsets = progress.maxOffsets
+ },
+ }
+
+ await runner.run([message(SESSION_A, 5, OPTED_OUT_TOKEN), message(SESSION_B, 6)], stages.admit(), committer)
+
+ expect(maxOffsets?.get(0)).toBe(6)
+ expect(recorded).toEqual([6])
+ })
+
+ it('commits an empty poll batch so the ingester can still flush on age', async () => {
+ const runner = buildRunner()
+ let progress: SessionReplayBatchProgress | undefined
+ const commit = jest.fn().mockImplementation(async (write) => {
+ progress = await write(recorder(), () => true)
+ })
+
+ await runner.run([], stages.admit(), { knownRetention: () => undefined, commit })
+
+ expect(commit).toHaveBeenCalledTimes(1)
+ expect(progress?.maxOffsets).toEqual(new Map())
+ })
+
+ it('records nothing for partitions the pod no longer holds at commit time', async () => {
+ const runner = buildRunner()
+ const held = recorder()
+ let recorded: Message[] = []
+ let maxOffsets: Map<number, number> | undefined
+ const committer: BatchCommitter = {
+ knownRetention: () => undefined,
+ commit: async (write) => {
+ const progress = await write(held, () => false)
+ recorded = progress.okMessages
+ maxOffsets = progress.maxOffsets
+ },
+ }
+
+ await runner.run([message(SESSION_A, 1)], stages.admit(), committer)
+
+ expect(held.record).not.toHaveBeenCalled()
+ expect(recorded).toEqual([])
+ expect(maxOffsets?.size).toBe(0)
+ })
+
+ it('still tracks offsets for a batch that drops every message', async () => {
+ const runner = buildRunner()
+ let maxOffsets: Map<number, number> | undefined
+ let recorded: Message[] = []
+ const committer: BatchCommitter = {
+ knownRetention: () => undefined,
+ commit: async (write) => {
+ const progress = await write(recorder(), () => true)
+ recorded = progress.okMessages
+ maxOffsets = progress.maxOffsets
+ },
+ }
+
+ await runner.run([message(SESSION_A, 7, OPTED_OUT_TOKEN)], stages.admit(), committer)
+
+ expect(maxOffsets?.get(0)).toBe(7)
+ expect(recorded).toEqual([])
+ expect(scrubStarts.size).toBe(0)
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/staged-batch-runner.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/staged-batch-runner.ts
new file mode 100644
index 000000000000..5c14744f9c11
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/staged-batch-runner.ts
@@ -0,0 +1,145 @@
+import { Message } from 'node-rdkafka'
+
+import { PromiseScheduler } from '~/common/utils/promise-scheduler'
+import { BatchingContext, BatchingPipeline } from '~/ingestion/framework/batching-pipeline'
+import { ChunkPipelineResultWithContext } from '~/ingestion/framework/chunk-pipeline.interface'
+import { createBatch } from '~/ingestion/framework/helpers'
+import { OkResultWithContext } from '~/ingestion/framework/pipeline.interface'
+import { isOkResult } from '~/ingestion/framework/results'
+import { SessionReplayPipelineConfig } from '~/ingestion/pipelines/sessionreplay'
+import { AdmittedBatch } from '~/ingestion/pipelines/sessionreplay/batch-stages'
+import { BatchCommitter, StagedBatchRunner } from '~/ingestion/pipelines/sessionreplay/staged-batch'
+
+import {
+ MlAnonymizePipeline,
+ MlMirrorCollection,
+ MlMirrorImageScrubProducer,
+ MlMirrorPipelineOptions,
+ MlMirrorUrlFetchProducer,
+ MlPreparePipeline,
+ createMlMirrorAnonymizePipeline,
+ createMlMirrorPreparePipeline,
+} from './ml-mirror-pipeline'
+
+/** The three stages a poll batch passes through, in order. Only anonymize is CPU work; the other two wait on DynamoDB, KMS, Redis, Kafka and S3. */
+export const ML_BATCH_STAGES = ['prepare', 'anonymize', 'commit'] as const
+
+/**
+ * Runs each poll batch through the prepare, anonymize and commit stages the ingester admitted it to, so
+ * the I/O-bound prepare and commit stages of neighbouring batches overlap the CPU-bound anonymize stage
+ * of this one. Offsets and lag are tracked in the commit stage, in batch order, as before.
+ */
+export class MlMirrorStagedBatchRunner implements StagedBatchRunner {
+ public readonly stages = ML_BATCH_STAGES
+ private pipelines?: { prepare: MlPreparePipeline; anonymize: MlAnonymizePipeline; scheduler: PromiseScheduler }
+
+ constructor(
+ private readonly mlOptions: MlMirrorPipelineOptions,
+ private readonly imageScrub?: MlMirrorImageScrubProducer,
+ private readonly collection?: MlMirrorCollection,
+ private readonly urlFetch?: MlMirrorUrlFetchProducer
+ ) {}
+
+ public start(config: SessionReplayPipelineConfig): void {
+ this.pipelines = {
+ prepare: createMlMirrorPreparePipeline(config, this.mlOptions),
+ anonymize: createMlMirrorAnonymizePipeline(
+ config,
+ this.mlOptions,
+ this.imageScrub,
+ this.collection,
+ this.urlFetch
+ ),
+ scheduler: config.promiseScheduler,
+ }
+ }
+
+ public run(messages: Message[], batch: AdmittedBatch<void>, committer: BatchCommitter): Promise<void> {
+ if (!this.pipelines) {
+ return Promise.reject(new Error('ML mirror staged batch runner used before start'))
+ }
+ const { prepare, anonymize, scheduler } = this.pipelines
+ return batch
+ .stage('prepare', async () => {
+ if (!messages.length) {
+ return { survivors: [], maxOffsets: new Map<number, number>(), handle: null }
+ }
+ const retentions = {
+ getRetention: (teamId: number, sessionId: string) => committer.knownRetention(teamId, sessionId),
+ }
+ const fed = createBatch(messages.map((message) => ({ message, sessionBatchRecorder: retentions })))
+ const { elements, batchContext } = await drainBatch(prepare, fed, scheduler)
+ // The offsets are taken here so the dropped messages, which are most of them on this lane, do not keep their Kafka buffers alive through the scrub.
+ return {
+ survivors: elements.flatMap(({ result }) => (isOkResult(result) ? [result.value] : [])),
+ maxOffsets: maxOffsetsOf(elements),
+ handle: batchContext.mlBatch,
+ }
+ })
+ .stage('anonymize', async ({ survivors, maxOffsets, handle }) => {
+ if (survivors.length) {
+ await drainBatch(anonymize, createBatch(survivors), scheduler)
+ }
+ return { maxOffsets, handle }
+ })
+ .stage('commit', ({ maxOffsets, handle }) =>
+ committer.commit(async (recorder, isAssigned) => {
+ const okMessages = handle ? await handle.commit(recorder, scheduler, isAssigned) : []
+ return {
+ maxOffsets: new Map([...maxOffsets].filter(([partition]) => isAssigned(partition))),
+ okMessages,
+ }
+ })
+ )
+ .done()
+ }
+}
+
+type StageElements<TOutput, COutput extends BatchingContext, R extends string> = ChunkPipelineResultWithContext<
+ TOutput,
+ COutput,
+ R
+>
+
+// Each stage pipeline holds one batch at a time and the runner feeds each stage in batch order, so draining to null returns exactly the batch just fed.
+async function drainBatch<TInput, TOutput, CInput, CBatch, COutput extends BatchingContext, R extends string>(
+ pipeline: BatchingPipeline<TInput, TOutput, CInput, CBatch, COutput, R>,
+ batch: OkResultWithContext<TInput, CInput>[],
+ promiseScheduler: PromiseScheduler
+): Promise<{ elements: StageElements<TOutput, COutput, R>; batchContext: CBatch }> {
+ const feedResult = await pipeline.feed(batch, {})
+ if (!feedResult.ok) {
+ throw new Error(`ML mirror stage rejected feed: ${feedResult.kind} (${feedResult.reason})`)
+ }
+ let drained: { elements: StageElements<TOutput, COutput, R>; batchContext: CBatch } | undefined
+ let batchResult = await pipeline.next()
+ while (batchResult !== null) {
+ for (const sideEffect of batchResult.sideEffects ?? []) {
+ void promiseScheduler.schedule(sideEffect)
+ }
+ if (drained) {
+ throw new Error('ML mirror stage drained a second batch, so the first batch would lose its messages')
+ }
+ drained = { elements: batchResult.elements, batchContext: batchResult.batchContext }
+ batchResult = await pipeline.next()
+ }
+ if (!drained) {
+ throw new Error('ML mirror stage returned no batch, which a feed of no elements also causes')
+ }
+ return drained
+}
+
+// Every message reaches a terminal result in the prepare stage or later, and every disposition advances the offset, so the prepare elements carry every offset of the batch.
+function maxOffsetsOf<R extends string>(
+ prepared: ChunkPipelineResultWithContext<unknown, { message: Message }, R>
+): Map<number, number> {
+ const maxOffsets = new Map<number, number>()
+ for (const { context } of prepared) {
+ const { partition, offset } = context.message
+ const current = maxOffsets.get(partition)
+ if (current === undefined || offset > current) {
+ maxOffsets.set(partition, offset)
+ }
+ }
+ return maxOffsets
+}
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
index 25b9870517b4..94a48761bcd5 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
@@ -20,9 +20,9 @@ import {
} from '~/ingestion/pipelines/sessionreplay/ml-mirror/config'
import { MlKeyManager } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime'
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'
import { SessionFormatFileStorage } from '~/ingestion/pipelines/sessionreplay/ml-mirror/session-format-file-storage'
+import { MlMirrorStagedBatchRunner } from '~/ingestion/pipelines/sessionreplay/ml-mirror/staged-batch-runner'
import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'
import { createOutputsRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/registry'
import { BlackholeSessionBatchFileStorage } from '~/ingestion/pipelines/sessionreplay/sessions/blackhole-session-batch-writer'
@@ -128,41 +128,39 @@ export class IngestionSessionReplayMlMirrorServer extends MlMirrorConsumerServer
featureStore: new SessionFeatureStore(outputs, false),
keyStore: keyManager,
encryptor: keyManager,
- createPipeline: (pipelineConfig) =>
- createMlMirrorReplayPipeline(
- pipelineConfig,
- {
- keyManager,
- anonymizeMaxConcurrency: resolveMlAnonymizeMaxConcurrency(
- this.config.SESSION_RECORDING_ML_ANONYMIZE_MAX_CONCURRENCY
- ),
- },
- this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED
- ? {
- outputs,
- producedRefCacheMax: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCED_REF_CACHE_MAX,
- }
- : undefined,
- {
- pseudonymSecret,
- // Producing the images is what makes collecting them useful, so the image
- // lane follows its producer flag. The URL lane collects on its own flag,
- // because collecting alone measures without sending anything anywhere.
- collectImages: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED,
- collectUrls: this.config.SESSION_RECORDING_ML_URL_COLLECTION_ENABLED,
- },
- // Producing needs collection: without it the anonymizer returns no URLs, and
- // the step would have nothing to send.
- urlProducerEnabled
- ? {
- outputs,
- producedRefCacheMax: this.config.SESSION_RECORDING_ML_URL_PRODUCED_REF_CACHE_MAX,
- producedRefCacheWindowMs:
- (this.config.AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS * 1000) / 2,
- crawlHistory: urlCrawlHistory,
- }
- : undefined
- ),
+ runner: new MlMirrorStagedBatchRunner(
+ {
+ keyManager,
+ anonymizeMaxConcurrency: resolveMlAnonymizeMaxConcurrency(
+ this.config.SESSION_RECORDING_ML_ANONYMIZE_MAX_CONCURRENCY
+ ),
+ },
+ this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED
+ ? {
+ outputs,
+ producedRefCacheMax: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCED_REF_CACHE_MAX,
+ }
+ : undefined,
+ {
+ pseudonymSecret,
+ // Producing the images is what makes collecting them useful, so the image
+ // lane follows its producer flag. The URL lane collects on its own flag,
+ // because collecting alone measures without sending anything anywhere.
+ collectImages: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED,
+ collectUrls: this.config.SESSION_RECORDING_ML_URL_COLLECTION_ENABLED,
+ },
+ // Producing needs collection: without it the anonymizer returns no URLs, and
+ // the step would have nothing to send.
+ urlProducerEnabled
+ ? {
+ outputs,
+ producedRefCacheMax: this.config.SESSION_RECORDING_ML_URL_PRODUCED_REF_CACHE_MAX,
+ producedRefCacheWindowMs:
+ (this.config.AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS * 1000) / 2,
+ crawlHistory: urlCrawlHistory,
+ }
+ : undefined
+ ),
// 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.
diff --git a/nodejs/tests/helpers/ml-mirror-staged-batch.ts b/nodejs/tests/helpers/ml-mirror-staged-batch.ts
new file mode 100644
index 000000000000..41be5941b642
--- /dev/null
+++ b/nodejs/tests/helpers/ml-mirror-staged-batch.ts
@@ -0,0 +1,193 @@
+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 { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'
+import { ok } from '~/ingestion/framework/results'
+import { SessionReplayPipelineConfig } from '~/ingestion/pipelines/sessionreplay'
+import { BatchStages } from '~/ingestion/pipelines/sessionreplay/batch-stages'
+import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'
+import {
+ MlMirrorCollection,
+ MlMirrorImageScrubProducer,
+ MlMirrorPipelineOptions,
+ MlMirrorUrlFetchProducer,
+} from '~/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline'
+import {
+ ML_BATCH_STAGES,
+ MlMirrorStagedBatchRunner,
+} from '~/ingestion/pipelines/sessionreplay/ml-mirror/staged-batch-runner'
+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 { BatchCommitter } from '~/ingestion/pipelines/sessionreplay/staged-batch'
+import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
+import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'
+
+/** Test-only: the runner the ML mirror server builds, started on one pipeline config. */
+export function buildMlMirrorStagedRunner(
+ config: SessionReplayPipelineConfig,
+ mlOptions: MlMirrorPipelineOptions,
+ imageScrub?: MlMirrorImageScrubProducer,
+ collection?: MlMirrorCollection,
+ urlFetch?: MlMirrorUrlFetchProducer
+): MlMirrorStagedBatchRunner {
+ const runner = new MlMirrorStagedBatchRunner(mlOptions, imageScrub, collection, urlFetch)
+ runner.start(config)
+ return runner
+}
+
+/** Test-only: a committer that records into one fixed recorder and never flushes. */
+export function recordingCommitter(recorder: SessionBatchRecorder): BatchCommitter {
+ return {
+ knownRetention: (teamId, sessionId) => recorder.getRetention(teamId, sessionId),
+ commit: async (write) => {
+ await write(recorder, () => true)
+ },
+ }
+}
+
+/** Test-only: runs one poll batch to completion against one recorder, admitted to its own stages unless the test shares some. */
+export function runMlMirrorBatch(
+ runner: MlMirrorStagedBatchRunner,
+ messages: Message[],
+ recorder: SessionBatchRecorder,
+ stages: BatchStages = new BatchStages(ML_BATCH_STAGES)
+): Promise<void> {
+ return runner.run(messages, stages.admit(), recordingCommitter(recorder))
+}
+
+type MlMirrorTestServices = Pick<
+ SessionReplayPipelineConfig,
+ 'retentionService' | 'sessionTracker' | 'sessionFilter' | 'keyStore' | 'teamService'
+>
+
+/** Test-only: services that resolve every session to 30 days, already seen, unblocked, with a cleartext key, for team 1 whose consent the token decides. */
+export function mlMirrorTestServices(isOptedIn: (token: string) => boolean = () => true): MlMirrorTestServices {
+ return {
+ 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,
+ 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,
+ sessionFilter: {
+ handleNewSessions: jest.fn().mockResolvedValue(new SessionSet()),
+ isBlocked: jest.fn().mockResolvedValue(new SessionSet()),
+ } as unknown as SessionFilter,
+ keyStore: createMockKeyStore(),
+ teamService: {
+ getTeamByToken: jest.fn().mockImplementation((token: string) =>
+ Promise.resolve({
+ teamId: 1,
+ consoleLogIngestionEnabled: false,
+ aiTrainingOptedIn: isOptedIn(token),
+ } satisfies TeamForReplay)
+ ),
+ getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),
+ } as unknown as TeamService,
+ }
+}
+
+/** Test-only: a pipeline config over the test services with mock outputs and TopHog. */
+export function mlMirrorTestPipelineConfig(
+ promiseScheduler: PromiseScheduler,
+ services: MlMirrorTestServices
+): SessionReplayPipelineConfig {
+ return {
+ outputs: createMockIngestionOutputs(),
+ eventIngestionRestrictionManager: {} as unknown as EventIngestionRestrictionManager,
+ overflowMode: 'disabled',
+ promiseScheduler,
+ ...services,
+ 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,
+ }
+}
+
+/** Test-only: stands in for the parse-headers step, reading the Kafka headers into a map. */
+export function parseTestHeaders<T extends { message: Message }>(
+ input: T
+): Promise<ReturnType<typeof ok<T & { headers: Record<string, string> }>>> {
+ 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 }))
+}
+
+/** Test-only: what a mocked scrub step hands back for one message, with one empty event line. */
+export function scrubbedTestMessage(
+ input: { message: Message; headers: Record<string, string> },
+ now: DateTime
+): ParsedMessageData {
+ return {
+ 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,
+ }
+}
+
+/** Test-only: a replay message on partition 0 whose payload the mocked scrub never reads. */
+export function mlMirrorTestMessage(sessionId: string, offset: number, token = 'test-token'): 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(token) },
+ { session_id: Buffer.from(sessionId) },
+ { distinct_id: Buffer.from('user-123') },
+ ],
+ size: 10,
+ } as unknown as Message
+}
diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.md
index 659222f3dcc0..857169af7a01 100644
--- a/products/ai_training/docs/replay-data.md
+++ b/products/ai_training/docs/replay-data.md
@@ -69,9 +69,15 @@ A conditional put refuses to recreate a shredded session key.
A team blocked during a batch is refused by every reader at once and by the next batch, which reads the block row live, and the deletion worker sweeps the team once more after the reader lease, so a key stored after the block is shredded.
Kafka offsets advance only after the required writes and publication succeed.
Bulk reads use batches of at most 100 keys. Each new key is one conditional put, so no commit in the fleet waits on another, and the month index entries it needs go in together, at most 25 to a request.
+Batches overlap, so a session first seen in one batch and also present in the next costs a second conditional put, which loses and settles on the stored key.
Reads use strongly consistent `BatchGetItem` requests with bounded retries for unprocessed keys and for a throttled request.
A retry stops when the caller's deadline expires.
+The mirror runs each Kafka batch through three stages that each hold one batch at a time, in batch order: prepare (steps 1 and 2, with session tracking), anonymize (the scrub), and commit (steps 3 and 4, then offset tracking and any flush).
+Neighboring batches overlap across stages, so one batch waits on DynamoDB, KMS, Kafka or S3 while another scrubs.
+The anonymize stage does not admit a batch while an earlier batch is in it.
+The record step writes to the recorder that is current at commit time, not the one that was current when the batch was read from Kafka, so a flush between those two moments does not lose the batch.
+
Ingestion holds a usable session key row and image key row in the process, and a KMS plaintext cache reduces repeated decrypt calls.
A row with no wrapped key is never held, so a repaired row is seen at once.
A team block row is held once a read finds one, because nothing clears a block. Only a row that exists is ever held, so the cache holds "blocked" and never "not blocked": a team with no block is read from DynamoDB on every batch, and a block takes effect on the next one.