:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ai-research): keep rows that arrive while the metadata sink flushes (#105977)
Robbie4954fbe49594
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.test.tsindex b30ce5358565..4c91d475c1dd 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.test.ts@@ -5,14 +5,14 @@ import { Message } from 'node-rdkafka'import { parseJSON } from '~/common/utils/json-parse'-import { BlockMetadataBatcher, OffsetStore } from './block-metadata-batcher'+import { BlockMetadataBatcher, KeyedRecordReader, OffsetStore } from './block-metadata-batcher'import { BlockMetadataParquetStore } from './block-metadata-parquet-store'import { MlBlockMetadataRow } from './block-metadata-row'import { MlDataKey } from './keys/crypto'import { decryptEnvelope } from './keys/envelope-testing'import { MlKeyReader } from './keys/reader'import { sessionKeyId, tableKeyString } from './keys/schema'-import { MlKafkaTransport, mlKafkaRecord } from './keys/transport'+import { MlDecodedMessage, MlKafkaTransport, mlKafkaRecord } from './keys/transport'const row = (sessionId: string): MlBlockMetadataRow => ({session_id: sessionId,@@ -133,6 +133,125 @@ describe('BlockMetadataBatcher', () => {})+ it('keeps the offsets for the next flush when storing them fails, without writing or counting the rows again', async () => {+ offsets.offsetsStore.mockImplementationOnce(() => {+ throw new Error('Local: Erroneous state')+ })+ const batcher = new BlockMetadataBatcher(+ store,+ offsets,+ { flushIntervalMs: 60_000, maxRows: 1_000, maxBytes: msg(0).value!.length * 2 },+ 0+ )+ await expect(batcher.handleBatch([msg(0), msg(1)], 0)).rejects.toThrow('Local: Erroneous state')++ await batcher.handleBatch([msg(2, 1)], 0)+ expect(store.write).toHaveBeenCalledTimes(1)+ await batcher.flush(1)+ expect(store.write.mock.calls.map(([rows]) => rows.map((stored) => stored.session_id))).toEqual([+ ['s0', 's1'],+ ['s2'],+ ])+ expect(offsets.offsetsStore.mock.calls).toEqual([+ [[{ topic: 'ml_block_metadata', partition: 0, offset: 2 }]],+ [+ [+ { topic: 'ml_block_metadata', partition: 0, offset: 2 },+ { topic: 'ml_block_metadata', partition: 1, offset: 3 },+ ],+ ],+ ])+ })++ it('counts the bytes of a batch whose key read overlaps a flush toward the flush that takes its rows', async () => {+ const asLegacyRows = (messages: Message[]): MlDecodedMessage[] =>+ messages.map((message) => ({ message, original: message }))+ const firstKeyRead = Promise.withResolvers<MlDecodedMessage[]>()+ const keyManager: KeyedRecordReader = {+ read: jest+ .fn()+ .mockReturnValueOnce(firstKeyRead.promise)+ .mockImplementation((messages: Message[]) => Promise.resolve(asLegacyRows(messages))),+ }+ const batcher = new BlockMetadataBatcher(+ store,+ offsets,+ { flushIntervalMs: 60_000, maxRows: 1_000, maxBytes: msg(0).value!.length * 2 },+ 0,+ keyManager+ )++ const batchInKeyRead = batcher.handleBatch([msg(0)], 0)+ await batcher.flush(0)+ firstKeyRead.resolve(asLegacyRows([msg(0)]))+ await batchInKeyRead+ await batcher.handleBatch([msg(1)], 0)+ expect(store.write).toHaveBeenCalledTimes(1)+ expect(store.write.mock.calls[0][0].map((stored) => stored.session_id)).toEqual(['s0', 's1'])+ })++ describe.each([+ { storage: 'legacy', write: 'write' as const, message: (offset: number) => msg(offset) },+ { storage: 'plain v3', write: 'writePlainV3' as const, message: (offset: number) => v3Msg(offset) },+ ])('while a $storage flush is writing', ({ write, message }) => {+ let firstWriteStarted: PromiseWithResolvers<void>+ let firstWrite: PromiseWithResolvers<void>+ let writtenRowCounts: number[]++ beforeEach(() => {+ firstWriteStarted = Promise.withResolvers<void>()+ firstWrite = Promise.withResolvers<void>()+ writtenRowCounts = []+ store[write].mockImplementation((rows) => {+ writtenRowCounts.push(rows.length)+ if (writtenRowCounts.length > 1) {+ return Promise.resolve()+ }+ firstWriteStarted.resolve()+ return firstWrite.promise+ })+ })++ it('keeps a batch that arrives, and stores only the offsets of the rows it wrote', async () => {+ const batcher = makeBatcher(60_000, 1_000)+ await batcher.handleBatch([message(0)], 0)++ const shutdownFlush = batcher.flush(0)+ await firstWriteStarted.promise+ await batcher.handleBatch([message(1)], 0)+ firstWrite.resolve()+ await shutdownFlush+ expect(offsets.offsetsStore.mock.calls).toEqual([+ [[{ topic: 'ml_block_metadata', partition: 0, offset: 1 }]],+ ])++ await batcher.flush(1)+ expect(writtenRowCounts).toEqual([1, 1])+ expect(offsets.offsetsStore).toHaveBeenLastCalledWith([+ { topic: 'ml_block_metadata', partition: 0, offset: 2 },+ ])+ })++ it('holds a second flush until the first fails, then writes both batches and stores their offsets', async () => {+ const batcher = makeBatcher(60_000, 2)+ await batcher.handleBatch([message(0)], 0)++ const shutdownFlush = batcher.flush(0)+ await firstWriteStarted.promise+ const batchAtRowLimit = batcher.handleBatch([message(1), message(2)], 0)+ await new Promise((resolve) => setImmediate(resolve))+ expect(offsets.offsetsStore).not.toHaveBeenCalled()++ firstWrite.reject(new Error('s3 down'))+ await expect(shutdownFlush).rejects.toThrow('s3 down')+ await batchAtRowLimit+ expect(writtenRowCounts).toEqual([1, 3])+ expect(offsets.offsetsStore.mock.calls).toEqual([+ [[{ topic: 'ml_block_metadata', partition: 0, offset: 3 }]],+ ])+ })+ })+it('keeps v2 offsets pending until the encrypted eval index upload succeeds', async () => {await sodium.readyconst sessionId = '01a0a4f0-3200-7000-8000-000000000001'diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.tsindex 4a82fbd964be..f40221c53d69 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.ts@@ -19,37 +19,50 @@ export interface OffsetStore {offsetsStore(offsets: TopicPartitionOffset[]): void}+/** The subset of the ML Kafka transport the batcher needs: reading each record with its session key. */+export type KeyedRecordReader = Pick<MlKafkaTransport, 'read'>+export interface BlockMetadataBatcherOptions {flushIntervalMs: numbermaxRows: numbermaxBytes?: number}+/** Bytes toward the byte limit for each buffer, so a failed flush puts back only the bytes of the buffers it puts back. */+interface BufferedBytes {+ plainV3: number+ encryptedIndex: number+ encrypted: number+ rows: number+}++const noBufferedBytes = (): BufferedBytes => ({ plainV3: 0, encryptedIndex: 0, encrypted: 0, rows: 0 })++const totalBytes = (bytes: BufferedBytes): number => bytes.plainV3 + bytes.encryptedIndex + bytes.encrypted + bytes.rows+export class BlockMetadataBatcher {private encrypted: MlEncryptedEnvelope[] = []private encryptedIndex: EncryptedReplayIndex[] = []private buffer: MlBlockMetadataRow[] = []private plainV3: MlBlockMetadataRow[] = []- private bufferedBytes = 0+ private bufferedBytes = noBufferedBytes()private pendingOffsets = new Map<string, TopicPartitionOffset>()private lastFlushMs: number+ private flushQueue: Promise<void> = Promise.resolve()constructor(private readonly store: BlockMetadataParquetStore,private readonly offsetStore: OffsetStore,private readonly options: BlockMetadataBatcherOptions,nowMs: number,- private readonly keyManager?: MlKafkaTransport+ private readonly keyManager?: KeyedRecordReader) {this.lastFlushMs = nowMs}/** Buffers a batch and flushes once the buffer is old enough or large enough. */public async handleBatch(messages: Message[], nowMs: number): Promise<void> {- for (const message of messages) {- this.bufferedBytes += message.value?.length ?? 0- }- const { plainV3Rows, otherMessages } = splitPlainV3Rows(messages)+ const { plainV3Rows, plainV3Bytes, otherMessages } = splitPlainV3Rows(messages)const decoded: MlDecodedMessage[] = this.keyManager? await this.keyManager.read(otherMessages, { sessionIdentity: rowSessionIdentity }): otherMessages.map((message) => {@@ -58,6 +71,15 @@ export class BlockMetadataBatcher {}return { message, original: message, key: undefined, invalid: undefined }})+ // Counted after the key read, so a flush that starts during the read cannot take these bytes without their rows.+ this.bufferedBytes.plainV3 += plainV3Bytes+ for (const { original, key } of decoded) {+ if (key) {+ this.bufferedBytes.encrypted += original.value?.length ?? 0+ } else {+ this.bufferedBytes.rows += original.value?.length ?? 0+ }+ }MlParquetSinkMetrics.incRowsRejected('key_missing', otherMessages.length - decoded.length)let encryptedRows = 0for (const { message, key, invalid, legacy } of decoded) {@@ -81,7 +103,10 @@ export class BlockMetadataBatcher {encryptedRows++const index = encryptReplayIndex(selected, key)this.encryptedIndex.push(...index)- this.bufferedBytes += index.reduce((size, item) => size + JSON.stringify(item.envelope).length, 0)+ this.bufferedBytes.encryptedIndex += index.reduce(+ (size, item) => size + JSON.stringify(item.envelope).length,+ 0+ )} else {MlParquetSinkMetrics.incRowsRejected('invalid')}@@ -109,7 +134,7 @@ export class BlockMetadataBatcher {private shouldFlush(nowMs: number): boolean {if (this.buffer.length + this.encrypted.length + this.plainV3.length >= this.options.maxRows ||- this.bufferedBytes >= (this.options.maxBytes ?? 32 * 1024 * 1024)+ totalBytes(this.bufferedBytes) >= (this.options.maxBytes ?? 32 * 1024 * 1024)) {return true}@@ -123,40 +148,89 @@ export class BlockMetadataBatcher {* Writes the buffered rows (if any) as one Parquet object, then stores the consumed offsets.* Throws (without storing offsets) if the write fails, so the consumer replays the window (at-least-once).*/- public async flush(nowMs: number): Promise<void> {+ public flush(nowMs: number): Promise<void> {+ // A later flush's offsets also cover rows that an earlier flush is still writing, so flushes run one at a time and in order.+ const flushed = this.flushQueue.then(() => this.flushNow(nowMs))+ this.flushQueue = flushed.catch(() => undefined)+ return flushed+ }++ private async flushNow(nowMs: number): Promise<void> {this.lastFlushMs = nowMs- const wroteObject = this.buffer.length > 0 || this.encrypted.length > 0 || this.plainV3.length > 0- if (this.plainV3.length > 0) {- await this.store.writePlainV3(this.plainV3)- this.plainV3 = []- }- if (this.encryptedIndex.length > 0) {- await this.store.writeEncryptedReplayIndex(this.encryptedIndex)- this.encryptedIndex = []- }- if (this.encrypted.length > 0) {- await this.store.writeEncrypted(this.encrypted)- this.encrypted = []- }- if (this.buffer.length > 0) {- await this.store.write(this.buffer)- this.buffer = []- }- this.bufferedBytes = 0- if (this.pendingOffsets.size > 0) {- // Commit after the write lands so a failed write replays; skipped-only batches still advance here.- this.offsetStore.offsetsStore([...this.pendingOffsets.values()])- this.pendingOffsets.clear()- // 'empty' means we advanced past messages that produced no rows (all skipped/malformed): healthy- // offset progress with zero Parquet output, the one state Kafka lag can't distinguish.- MlParquetSinkMetrics.incFlush(wroteObject ? 'written' : 'empty')+ // The shutdown flush runs while the consumer loop still delivers batches, so a flush writes only the rows it takes here and stores only their offsets.+ let plainV3 = this.plainV3+ let encryptedIndex = this.encryptedIndex+ let encrypted = this.encrypted+ let rows = this.buffer+ const offsets = this.pendingOffsets+ const bytes = this.bufferedBytes+ this.plainV3 = []+ this.encryptedIndex = []+ this.encrypted = []+ this.buffer = []+ this.pendingOffsets = new Map()+ this.bufferedBytes = noBufferedBytes()+ const wroteObject = rows.length > 0 || encrypted.length > 0 || plainV3.length > 0+ try {+ if (plainV3.length > 0) {+ await this.store.writePlainV3(plainV3)+ plainV3 = []+ }+ if (encryptedIndex.length > 0) {+ await this.store.writeEncryptedReplayIndex(encryptedIndex)+ encryptedIndex = []+ }+ if (encrypted.length > 0) {+ await this.store.writeEncrypted(encrypted)+ encrypted = []+ }+ if (rows.length > 0) {+ await this.store.write(rows)+ rows = []+ }+ if (offsets.size > 0) {+ // Commit after the write lands so a failed write replays; skipped-only batches still advance here.+ this.offsetStore.offsetsStore([...offsets.values()])+ // 'empty' means we advanced past messages that produced no rows (all skipped/malformed): healthy+ // offset progress with zero Parquet output, the one state Kafka lag can't distinguish.+ MlParquetSinkMetrics.incFlush(wroteObject ? 'written' : 'empty')+ }+ } catch (error) {+ if (plainV3.length > 0) {+ this.plainV3 = plainV3.concat(this.plainV3)+ this.bufferedBytes.plainV3 += bytes.plainV3+ }+ if (encryptedIndex.length > 0) {+ this.encryptedIndex = encryptedIndex.concat(this.encryptedIndex)+ this.bufferedBytes.encryptedIndex += bytes.encryptedIndex+ }+ if (encrypted.length > 0) {+ this.encrypted = encrypted.concat(this.encrypted)+ this.bufferedBytes.encrypted += bytes.encrypted+ }+ if (rows.length > 0) {+ this.buffer = rows.concat(this.buffer)+ this.bufferedBytes.rows += bytes.rows+ }+ for (const [partition, offset] of offsets) {+ // A newer offset for the partition stays, because the next flush stores it only after writing every row it covers.+ if (!this.pendingOffsets.has(partition)) {+ this.pendingOffsets.set(partition, offset)+ }+ }+ throw error}}}/** A v3 session needs no session key, because the sink stores its metadata and replay index as plain Parquet. */-function splitPlainV3Rows(messages: Message[]): { plainV3Rows: MlBlockMetadataRow[]; otherMessages: Message[] } {+function splitPlainV3Rows(messages: Message[]): {+ plainV3Rows: MlBlockMetadataRow[]+ plainV3Bytes: number+ otherMessages: Message[]+} {const plainV3Rows: MlBlockMetadataRow[] = []+ let plainV3Bytes = 0const otherMessages: Message[] = []for (const message of messages) {const row = parsedV3Row(message)@@ -164,11 +238,12 @@ function splitPlainV3Rows(messages: Message[]): { plainV3Rows: MlBlockMetadataRootherMessages.push(message)} else if (isWellFormedRow(row) && row.format_version === 2) {plainV3Rows.push(selectBlockMetadataFields(row))+ plainV3Bytes += message.value?.length ?? 0} else {MlParquetSinkMetrics.incRowsRejected('invalid')}}- return { plainV3Rows, otherMessages }+ return { plainV3Rows, plainV3Bytes, otherMessages }}function parsedV3Row(message: Message): object | null {