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.

fix(ai-research): publish ML mirror records without waiting on each delivery ack (#101415)

Robbie775e79b8eb4d
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
index ac1d5be04225..fa96851b4600 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
@@ -17,6 +17,15 @@ export type MlImageLaneStage = 'collected' | 'deduped' | 'queued' | 'produced' |
export type MlUrlLaneStage = 'collected' | 'deduped' | 'queued' | 'produced' | 'produce_failed' | 'ref_unusable'
export type MlUrlCrawlHistoryOutcome = 'fresh' | 'miss' | 'error'
export type MlImageSource = 'css' | 'html'
+/** Phases of the ML key work around one Kafka batch: the key bulk read before processing, the key writes and re-read after it, and the deferred publications. */
+export type MlPrivacyPhase = 'prepare' | 'commit' | 'publish'
+export type MlPrivacyRequest =
+ | 'kms_generate'
+ | 'kms_decrypt'
+ | 'kms_wait'
+ | 'dynamodb_read'
+ | 'dynamodb_put'
+ | 'dynamodb_put_if_absent'
export type MlImageSourceKind = 'inline' | 'url'
const URL_BYTES_SAMPLE_RATE = 16
@@ -117,6 +126,18 @@ export class MlMirrorMetrics {
* observing each one puts the size of the payload on the mirror's hot path.
*/
private static urlBytesSeen = 0
+ private static readonly mlPrivacyPhaseDuration = new Histogram({
+ name: 'recording_blob_ingestion_v2_ml_privacy_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',
+ labelNames: ['phase'],
+ buckets: [1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000, Infinity],
+ })
+ private static readonly mlPrivacyRequestDuration = new Histogram({
+ name: 'recording_blob_ingestion_v2_ml_privacy_request_duration_ms',
+ help: 'Duration of one KMS or DynamoDB request from the ML key store, and for kms_wait the time a KMS request spent queued behind the per-pod rate limit before it was sent',
+ labelNames: ['request'],
+ buckets: [1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, Infinity],
+ })
private static readonly mlUrlsPerRecord = new Histogram({
name: 'recording_blob_ingestion_v2_ml_urls_per_record',
help: 'URLs packed into one record on the fetch topic. Bounded in practice by the collector cap per message, since a record holds one domain from one message',
@@ -128,6 +149,14 @@ export class MlMirrorMetrics {
buckets: [1024, 8192, 65536, 262144, 524288, 1_000_000],
})
+ public static observeMlPrivacyPhase(phase: MlPrivacyPhase, ms: number): void {
+ this.mlPrivacyPhaseDuration.labels(phase).observe(ms)
+ }
+
+ public static observeMlPrivacyRequest(request: MlPrivacyRequest, ms: number): void {
+ this.mlPrivacyRequestDuration.labels(request).observe(ms)
+ }
+
public static observeMlAnonymizeDuration(impl: MlAnonymizeImpl, ms: number, route: MlAnonymizeRoute = ''): void {
this.mlAnonymizeDuration.labels(impl, route).observe(ms)
}
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 2d5ba5d5c71b..66f34dd3c654 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
@@ -218,7 +218,7 @@ export function createMlMirrorReplayPipeline(
.gather(),
(afterBatch) =>
afterBatch.pipe(async function passThroughAfterBatch(input) {
- await mlOptions.privacy?.commit()
+ await mlOptions.privacy?.commit(promiseScheduler)
return ok(input)
}),
// One batch in flight at a time (also the framework default): each feed tags the manager's
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/batch-controller.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/batch-controller.ts
index b1a6a6cf97e2..0db6ab5b543b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/batch-controller.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/batch-controller.ts
@@ -1,6 +1,8 @@
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 {
DeleteKeyResult,
@@ -21,7 +23,7 @@ export interface MlRecordingKey extends SessionKey {
export class MlPrivacyBatchController implements KeyStore, RecordingEncryptor {
private readonly publish = pLimit(8)
private batch?: MlKeyBatch
- private deferred: Array<() => Promise<void>> = []
+ private deferred: Array<(sideEffects: (promises: Promise<unknown>[]) => Promise<void>) => Promise<void>> = []
constructor(
private readonly store: MlSessionKeyStore,
@@ -43,9 +45,11 @@ export class MlPrivacyBatchController implements KeyStore, RecordingEncryptor {
public async prepare(identities: MlSessionIdentity[]): Promise<void> {
this.deferred = []
+ const startedAt = performance.now()
this.batch = await this.store.prepare(
identities.filter((identity) => usesRawSessionIdentifiers(identity.sessionId))
)
+ MlMirrorMetrics.observeMlPrivacyPhase('prepare', performance.now() - startedAt)
}
public keys(teamId: number, sessionId: string): MlSessionKeys | undefined {
@@ -56,25 +60,42 @@ export class MlPrivacyBatchController implements KeyStore, RecordingEncryptor {
input: T,
action: (input: T) => Promise<PipelineResult<T>>
): Promise<PipelineResult<T>> {
- this.deferred.push(async () => {
+ 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 Promise.all(result.sideEffects ?? [])
+ await sideEffects(result.sideEffects ?? [])
}
}
})
return Promise.resolve(ok(input))
}
- public async commit(): Promise<void> {
+ // 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
}
+ const startedAt = performance.now()
await this.batch.commit()
- await Promise.all(this.deferred.map((action) => this.publish(action)))
+ const committedAt = performance.now()
+ MlMirrorMetrics.observeMlPrivacyPhase('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.observeMlPrivacyPhase('publish', performance.now() - committedAt)
}
public getKey(sessionId: string, teamId: number): Promise<SessionKey> {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/crypto.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/crypto.ts
index 311e8f788cf5..12d56f09323e 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/crypto.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/crypto.ts
@@ -5,6 +5,7 @@ import { isDeepStrictEqual } from 'node:util'
import pLimit from 'p-limit'
import { parseJSON } from '~/common/utils/json-parse'
+import { MlMirrorMetrics, MlPrivacyRequest } from '~/ingestion/pipelines/sessionreplay/ml-mirror/metrics'
import { MlKeyIdentity, wrappingContext } from './schema'
@@ -51,20 +52,27 @@ export class MlKeyEncryption {
await sodium.ready
}
- private async request<T>(operation: () => Promise<T>): Promise<T> {
+ private async request<T>(kind: MlPrivacyRequest, operation: () => Promise<T>): Promise<T> {
return this.concurrency(async () => {
+ const queuedAt = performance.now()
const now = Date.now()
const scheduledAt = Math.max(now, this.nextRequestAt)
this.nextRequestAt = scheduledAt + 1000 / this.requestsPerSecond
if (scheduledAt > now) {
await new Promise((resolve) => setTimeout(resolve, scheduledAt - now))
}
- return operation()
+ const sentAt = performance.now()
+ MlMirrorMetrics.observeMlPrivacyRequest('kms_wait', sentAt - queuedAt)
+ try {
+ return await operation()
+ } finally {
+ MlMirrorMetrics.observeMlPrivacyRequest(kind, performance.now() - sentAt)
+ }
})
}
public async generate(identity: MlKeyIdentity): Promise<MlDataKey> {
- const result = await this.request(() =>
+ const result = await this.request('kms_generate', () =>
this.kms.send(
new GenerateDataKeyCommand({
KeyId: this.masterKeyArn,
@@ -96,7 +104,7 @@ export class MlKeyEncryption {
}
let pending = this.pending.get(id)
if (!pending) {
- pending = this.request(async () => {
+ pending = this.request('kms_decrypt', async () => {
const result = await this.kms.send(
new DecryptCommand({
KeyId: this.masterKeyArn,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/dynamodb.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/dynamodb.ts
index 900e97ec3f3f..61403f40d6ec 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/dynamodb.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/dynamodb.ts
@@ -7,6 +7,8 @@ import {
} from '@aws-sdk/client-dynamodb'
import pLimit from 'p-limit'
+import { MlMirrorMetrics, MlPrivacyRequest } from '~/ingestion/pipelines/sessionreplay/ml-mirror/metrics'
+
import { TableKey, tableKeyString } from './schema'
export type DynamoItem = Record<string, AttributeValue>
@@ -45,11 +47,13 @@ export class MlPrivacyDynamoDB {
this.concurrency(async () => {
let pending = chunk.map(encodeKey)
for (let attempt = 0; pending.length && attempt < this.attempts; attempt++) {
- const response = await this.client.send(
- new BatchGetItemCommand({
- RequestItems: { [this.tableName]: { Keys: pending, ConsistentRead: true } },
- }),
- { abortSignal: this.requestSignal(deadline) }
+ const response = await this.timed('dynamodb_read', () =>
+ this.client.send(
+ new BatchGetItemCommand({
+ RequestItems: { [this.tableName]: { Keys: pending, ConsistentRead: true } },
+ }),
+ { abortSignal: this.requestSignal(deadline) }
+ )
)
for (const item of response.Responses?.[this.tableName] ?? []) {
result.set(tableKeyString(decodeKey(item)), item)
@@ -69,37 +73,48 @@ export class MlPrivacyDynamoDB {
}
public async putIfAbsent(key: TableKey, attributes: DynamoItem, deadline?: AbortSignal): Promise<boolean> {
- return this.writeConcurrency(async () => {
- try {
- await this.client.send(
- new PutItemCommand({
- TableName: this.tableName,
- Item: { ...encodeKey(key), ...attributes },
- ConditionExpression: 'attribute_not_exists(pk)',
- }),
- { abortSignal: this.requestSignal(deadline) }
- )
- return true
- } catch (error) {
- if (error instanceof ConditionalCheckFailedException) {
- return false
+ return this.writeConcurrency(() =>
+ this.timed('dynamodb_put_if_absent', async () => {
+ try {
+ await this.client.send(
+ new PutItemCommand({
+ TableName: this.tableName,
+ Item: { ...encodeKey(key), ...attributes },
+ ConditionExpression: 'attribute_not_exists(pk)',
+ }),
+ { abortSignal: this.requestSignal(deadline) }
+ )
+ return true
+ } catch (error) {
+ if (error instanceof ConditionalCheckFailedException) {
+ return false
+ }
+ throw error
}
- throw error
- }
- })
+ })
+ )
}
public async put(key: TableKey, attributes: DynamoItem, deadline?: AbortSignal): Promise<void> {
await this.writeConcurrency(() =>
- this.client.send(
- new PutItemCommand({ TableName: this.tableName, Item: { ...encodeKey(key), ...attributes } }),
- {
- abortSignal: this.requestSignal(deadline),
- }
+ this.timed('dynamodb_put', () =>
+ this.client.send(
+ new PutItemCommand({ TableName: this.tableName, Item: { ...encodeKey(key), ...attributes } }),
+ { abortSignal: this.requestSignal(deadline) }
+ )
)
)
}
+ private async timed<T>(request: MlPrivacyRequest, operation: () => Promise<T>): Promise<T> {
+ const startedAt = performance.now()
+ try {
+ return await operation()
+ } finally {
+ MlMirrorMetrics.observeMlPrivacyRequest(request, performance.now() - startedAt)
+ }
+ }
+
private requestSignal(deadline?: AbortSignal): AbortSignal {
const timeout = AbortSignal.timeout(this.requestTimeoutMs)
return deadline ? AbortSignal.any([deadline, timeout]) : timeout
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.test.ts
index 2004f9eb8ca8..0b313bf97dfc 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.test.ts
@@ -10,6 +10,7 @@ import { Message } from 'node-rdkafka'
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 { BlockMetadataBatcher } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher'
import { BlockMetadataParquetStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store'
@@ -333,7 +334,7 @@ describe('ML session key batches', () => {
expect(generated).toBe(2)
})
- it('publishes a bounded concurrent batch only after privacy writes commit', async () => {
+ it('publishes only after privacy writes commit and hands delivery acks to the scheduler', async () => {
const identity = { ...session, sessionId: '01a0a4f0-3200-7000-8000-000000000001' }
const controller = new MlPrivacyBatchController(store, encryption)
await controller.prepare([identity])
@@ -342,10 +343,6 @@ describe('ML session key batches', () => {
release = resolve
})
let started = 0
- let firstWaveStarted!: () => void
- const firstWave = new Promise<void>((resolve) => {
- firstWaveStarted = resolve
- })
const input = {
team: { teamId: identity.teamId },
headers: { session_id: identity.sessionId },
@@ -355,19 +352,43 @@ describe('ML session key batches', () => {
await controller.defer(input, (value) => {
expect(
boundary.items.get(tableKeyString(sessionKeyId(identity.teamId, identity.sessionId)))?.wrapped_key
- ).toBeDefined()
- if (++started === 8) {
- firstWaveStarted()
- }
+ ).not.toBeUndefined()
+ started += 1
return Promise.resolve(ok(value, [delivery]))
})
}
- const committed = controller.commit()
- await firstWave
- expect(started).toBe(8)
- release()
- await committed
+ const scheduler = new PromiseScheduler()
+ await controller.commit(scheduler)
expect(started).toBe(20)
+ expect(scheduler.promises.size).toBe(1)
+ release()
+ await scheduler.waitForAll()
+ expect(scheduler.promises.size).toBe(0)
+ })
+
+ it('waits for delivery acks itself when no scheduler owns them', async () => {
+ const identity = { ...session, sessionId: '01a0a4f0-3200-7000-8000-000000000002' }
+ const controller = new MlPrivacyBatchController(store, encryption)
+ await controller.prepare([identity])
+ let release!: () => void
+ const delivery = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ const input = {
+ team: { teamId: identity.teamId },
+ headers: { session_id: identity.sessionId },
+ sessionKey: await controller.getKey(identity.sessionId, identity.teamId),
+ }
+ await controller.defer(input, (value) => Promise.resolve(ok(value, [delivery])))
+ let committed = false
+ const committing = controller.commit().then(() => {
+ committed = true
+ })
+ await new Promise((resolve) => setImmediate(resolve))
+ expect(committed).toBe(false)
+ release()
+ await committing
+ expect(committed).toBe(true)
})
it.each(['invalid-json', 'oversized-session', 'invalid-session', 'invalid-month'])(
'reports accepted, malformed (%s) and deleted encrypted metadata separately',