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.

refactor(replay): track Kafka offsets in one place (#67799)

Paweł Ledwońc6194da00618
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts
index a47b0fb3855a..f48b02ea52c0 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts
@@ -14,7 +14,7 @@ import { logger } from '~/common/utils/logger'
import { captureException } from '~/common/utils/posthog'
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
import { IngestionConsumerConfig } from '~/ingestion/config'
-import { BatchPipelineUnwrapper } from '~/ingestion/framework/batch-pipeline-unwrapper'
+import { BatchPipeline } from '~/ingestion/framework/batch-pipeline.interface'
import { TopHog } from '~/ingestion/framework/tophog/tophog'
import {
SessionReplayPipelineConfig,
@@ -66,10 +66,11 @@ export type SessionRecordingIngesterConfig = SessionRecordingConfig &
/** Builds the session replay pipeline for a deployment (default or ML mirror). */
export type SessionReplayPipelineFactory = (
config: SessionReplayPipelineConfig
-) => BatchPipelineUnwrapper<
+) => BatchPipeline<
SessionReplayPipelineInput,
SessionReplayPipelineOutput,
{ message: Message },
+ { message: Message },
OverflowOutput
>
@@ -101,10 +102,11 @@ export class SessionRecordingIngester {
private readonly eventIngestionRestrictionManagerComponent: EventIngestionRestrictionManagerComponent
private eventIngestionRestrictionManager!: EventIngestionRestrictionManager
private stopEventIngestionRestrictionManager?: () => Promise<void>
- private sessionReplayPipeline!: BatchPipelineUnwrapper<
+ private sessionReplayPipeline!: BatchPipeline<
SessionReplayPipelineInput,
SessionReplayPipelineOutput,
{ message: Message },
+ { message: Message },
OverflowOutput
>
private readonly outputs: IngestionOutputs<
@@ -276,13 +278,21 @@ export class SessionRecordingIngester {
SessionRecordingIngesterMetrics.observeKafkaBatchSizeKb(batchSizeKb)
// Run messages through the pipeline (handles restrictions, parsing, team filtering, and recording)
- await instrumentFn(`recordingingesterv2.handleEachBatch.runPipeline`, async () =>
+ // and track the highest offset reached per partition — the single place Kafka progress is tracked.
+ const offsets = await instrumentFn(`recordingingesterv2.handleEachBatch.runPipeline`, async () =>
runSessionReplayPipeline(this.sessionReplayPipeline, messages)
)
+ this.sessionBatchManager.trackProcessedOffsets(offsets)
this.kafkaConsumer.heartbeat()
if (this.sessionBatchManager.shouldFlush()) {
+ // The pipeline schedules its side effects (DLQ and overflow produces) fire-and-forget on
+ // the promise scheduler. Drain them before flushing so we never commit a message's offset
+ // before its produce is durable — otherwise a crash in that window would lose it.
+ await instrumentFn(`recordingingesterv2.handleEachBatch.flush.awaitSideEffects`, async () => {
+ await this.promiseScheduler.waitForAllSettled()
+ })
await instrumentFn(`recordingingesterv2.handleEachBatch.flush`, async () =>
this.sessionBatchManager.flush()
)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/kafka/offset-manager.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/kafka/offset-manager.test.ts
index 76b8f376df06..ef4a83725f83 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/kafka/offset-manager.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/kafka/offset-manager.test.ts
@@ -120,5 +120,22 @@ describe('KafkaOffsetManager', () => {
},
])
})
+
+ it('should not move a partition backwards when a lower offset is tracked last', async () => {
+ // A drop for a lower offset can be tracked after a higher recorded offset; committing the
+ // lower one would replay everything in between.
+ offsetManager.trackOffset({ partition: 1, offset: 101 })
+ offsetManager.trackOffset({ partition: 1, offset: 99 })
+
+ await offsetManager.commit()
+
+ expect(mockCommitOffsets).toHaveBeenCalledWith([
+ {
+ topic: 'test_topic',
+ partition: 1,
+ offset: 102,
+ },
+ ])
+ })
})
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/kafka/offset-manager.ts b/nodejs/src/ingestion/pipelines/sessionreplay/kafka/offset-manager.ts
index 2a3a0dfa15e3..ced11ec4a97a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/kafka/offset-manager.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/kafka/offset-manager.ts
@@ -14,8 +14,14 @@ export class KafkaOffsetManager {
) {}
public trackOffset({ partition, offset }: PartitionOffset): void {
- // We track the next offset to process
- this.partitionOffsets.set(partition, offset + 1)
+ // We track the next offset to process. Never move a partition backwards: callers can arrive
+ // out of order (a drop tracked before a lower recorded offset), and committing the lower one
+ // would replay everything in between.
+ const nextOffset = offset + 1
+ const current = this.partitionOffsets.get(partition)
+ if (current === undefined || nextOffset > current) {
+ this.partitionOffsets.set(partition, nextOffset)
+ }
}
public discardPartition(partition: number): void {
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 e21b15460d67..630e77c0c36b 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
@@ -3,10 +3,9 @@ import { Message } from 'node-rdkafka'
import { OverflowOutput } from '~/common/outputs'
import { createApplyEventRestrictionsStep, createParseHeadersStep } from '~/ingestion/common/steps/event-preprocessing'
-import { BatchPipelineUnwrapper } from '~/ingestion/framework/batch-pipeline-unwrapper'
+import { BatchPipeline } from '~/ingestion/framework/batch-pipeline.interface'
import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'
import { createTopHogWrapper, sum, timer } from '~/ingestion/framework/extensions/tophog'
-import { createUnwrapper } from '~/ingestion/framework/helpers'
import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'
import {
SessionReplayPipelineConfig,
@@ -27,10 +26,11 @@ export type MlMirrorReplayPipelineConfig = SessionReplayPipelineConfig & {
export function createMlMirrorReplayPipeline(
config: MlMirrorReplayPipelineConfig
-): BatchPipelineUnwrapper<
+): BatchPipeline<
SessionReplayPipelineInput,
SessionReplayPipelineOutput,
{ message: Message },
+ { message: Message },
OverflowOutput
> {
const {
@@ -121,5 +121,5 @@ export function createMlMirrorReplayPipeline(
.gather()
.build()
- return createUnwrapper(pipeline)
+ return pipeline
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts
index 5d8dab06466a..d8ee1fa6dd6a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts
@@ -236,6 +236,13 @@ describe('session-replay-pipeline', () => {
}
describe('runSessionReplayPipeline', () => {
+ // The runner now returns the max offset per partition; which messages actually reached
+ // recording is observed through the batch recorder mock.
+ const recordedSessionIds = (): string[] =>
+ (mockSessionBatchManager.getCurrentBatch().record as jest.Mock).mock.calls.map(
+ (call) => call[0].message.session_id
+ )
+
it('passes through messages when no restrictions apply', async () => {
const pipeline = createSessionReplayPipeline({
outputs,
@@ -250,13 +257,10 @@ describe('session-replay-pipeline', () => {
const messages = [createMessage(0, 1, 'session-1'), createMessage(0, 2, 'session-2')]
- const result = await runSessionReplayPipeline(pipeline, messages)
+ const offsets = await runSessionReplayPipeline(pipeline, messages)
- expect(result).toHaveLength(2)
- expect(result[0].parsedMessage.session_id).toBe('session-1')
- expect(result[0].team.teamId).toBe(1)
- expect(result[1].parsedMessage.session_id).toBe('session-2')
- expect(result[1].team.teamId).toBe(1)
+ expect(recordedSessionIds()).toEqual(['session-1', 'session-2'])
+ expect(offsets).toEqual(new Map([[0, 2]]))
})
it('filters out dropped messages from restrictions', async () => {
@@ -286,11 +290,47 @@ describe('session-replay-pipeline', () => {
createMessage(0, 3, 'session-3'),
]
- const result = await runSessionReplayPipeline(pipeline, messages)
+ const offsets = await runSessionReplayPipeline(pipeline, messages)
+
+ expect(recordedSessionIds()).toEqual(['session-1', 'session-3'])
+ // The dropped message (offset 2) is not recorded, but its offset is still accounted for —
+ // the partition's committed offset advances past it rather than replaying it forever.
+ expect(offsets).toEqual(new Map([[0, 3]]))
+ })
+
+ it('tracks the offset of a dropped message even when it is the highest in the partition', async () => {
+ mockCreateApplyEventRestrictionsStep.mockReturnValue(
+ (input: { message: Message; headers: Record<string, string> }) => {
+ if (input.message.offset === 3) {
+ return Promise.resolve(drop('blocked'))
+ }
+ return Promise.resolve(ok(input))
+ }
+ )
+
+ const pipeline = createSessionReplayPipeline({
+ outputs,
+ eventIngestionRestrictionManager: mockRestrictionManager,
+ overflowEnabled: true,
+ promiseScheduler,
+ teamService: mockTeamService,
+ topHog,
+ sessionBatchManager: mockSessionBatchManager,
+ isDebugLoggingEnabled,
+ })
+
+ const messages = [
+ createMessage(0, 1, 'session-1'),
+ createMessage(0, 2, 'session-2'),
+ createMessage(0, 3, 'session-3'),
+ ]
+
+ const offsets = await runSessionReplayPipeline(pipeline, messages)
- expect(result).toHaveLength(2)
- expect(result[0].parsedMessage.session_id).toBe('session-1')
- expect(result[1].parsedMessage.session_id).toBe('session-3')
+ expect(recordedSessionIds()).toEqual(['session-1', 'session-2'])
+ // The highest offset on the partition belongs to the dropped message; it must still be
+ // tracked or that partition would never commit past offset 2.
+ expect(offsets).toEqual(new Map([[0, 3]]))
})
it('filters out messages that fail to parse', async () => {
@@ -319,11 +359,11 @@ describe('session-replay-pipeline', () => {
const messages = [createMessage(0, 1, 'session-1'), invalidMessage, createMessage(0, 3, 'session-3')]
- const result = await runSessionReplayPipeline(pipeline, messages)
+ const offsets = await runSessionReplayPipeline(pipeline, messages)
- expect(result).toHaveLength(2)
- expect(result[0].parsedMessage.session_id).toBe('session-1')
- expect(result[1].parsedMessage.session_id).toBe('session-3')
+ expect(recordedSessionIds()).toEqual(['session-1', 'session-3'])
+ // The unparseable message (offset 2) is DLQ'd, but its offset is still accounted for.
+ expect(offsets).toEqual(new Map([[0, 3]]))
})
it('sends messages that fail to parse to the DLQ topic', async () => {
@@ -393,20 +433,20 @@ describe('session-replay-pipeline', () => {
createMessage(0, 3, 'session-3'),
]
- const result = await runSessionReplayPipeline(pipeline, messages)
+ const offsets = await runSessionReplayPipeline(pipeline, messages)
// Wait for side effects to complete
await promiseScheduler.waitForAll()
- expect(result).toHaveLength(2)
- expect(result[0].parsedMessage.session_id).toBe('session-1')
- expect(result[1].parsedMessage.session_id).toBe('session-3')
+ expect(recordedSessionIds()).toEqual(['session-1', 'session-3'])
+ // The redirected message (offset 2) is not recorded, but its offset is still accounted for.
+ expect(offsets).toEqual(new Map([[0, 3]]))
// Verify the overflow message was produced
expect(outputs.produce).toHaveBeenCalledWith(OVERFLOW_OUTPUT, expect.anything())
})
- it('returns empty array for empty input', async () => {
+ it('returns empty offsets for empty input', async () => {
const pipeline = createSessionReplayPipeline({
outputs,
eventIngestionRestrictionManager: mockRestrictionManager,
@@ -418,9 +458,9 @@ describe('session-replay-pipeline', () => {
isDebugLoggingEnabled,
})
- const result = await runSessionReplayPipeline(pipeline, [])
+ const offsets = await runSessionReplayPipeline(pipeline, [])
- expect(result).toHaveLength(0)
+ expect(offsets.size).toBe(0)
})
it('processes large batch with mixed dropped and passed messages correctly', async () => {
@@ -451,21 +491,20 @@ describe('session-replay-pipeline', () => {
messages.push(createMessage(0, i))
}
- const result = await runSessionReplayPipeline(pipeline, messages)
+ const offsets = await runSessionReplayPipeline(pipeline, messages)
- // 100 messages should be dropped (10, 20, 30, ..., 1000)
- // 900 messages should pass through
- expect(result).toHaveLength(900)
-
- // Verify the session_ids are correct (all non-multiples of 10)
- const resultSessionIds = result.map((m) => m.parsedMessage.session_id)
+ // 100 messages dropped (10, 20, ..., 1000), 900 recorded
+ const recorded = recordedSessionIds()
+ expect(recorded).toHaveLength(900)
for (let i = 1; i <= 1000; i++) {
if (i % 10 === 0) {
- expect(resultSessionIds).not.toContain(`session-${i}`)
+ expect(recorded).not.toContain(`session-${i}`)
} else {
- expect(resultSessionIds).toContain(`session-${i}`)
+ expect(recorded).toContain(`session-${i}`)
}
}
+ // Every message's offset is accounted for regardless of disposition.
+ expect(offsets).toEqual(new Map([[0, 1000]]))
})
it('correctly parses and passes headers to the restrictions step', async () => {
@@ -494,9 +533,9 @@ describe('session-replay-pipeline', () => {
createMessage(0, 2, 'session-2', { token: 'team-token-789' }),
]
- const result = await runSessionReplayPipeline(pipeline, messages)
+ await runSessionReplayPipeline(pipeline, messages)
- expect(result).toHaveLength(2)
+ expect(recordedSessionIds()).toEqual(['session-1', 'session-2'])
// Verify headers were correctly parsed and passed through
expect(capturedHeaders).toHaveLength(2)
expect(capturedHeaders[0]).toEqual({
@@ -525,14 +564,14 @@ describe('session-replay-pipeline', () => {
messages.push(createMessage(0, i))
}
- const result = await runSessionReplayPipeline(pipeline, messages)
+ const offsets = await runSessionReplayPipeline(pipeline, messages)
- expect(result).toHaveLength(500)
-
- // Verify all session_ids are present and in order
+ const recorded = recordedSessionIds()
+ expect(recorded).toHaveLength(500)
for (let i = 0; i < 500; i++) {
- expect(result[i].parsedMessage.session_id).toBe(`session-${i + 1}`)
+ expect(recorded[i]).toBe(`session-${i + 1}`)
}
+ expect(offsets).toEqual(new Map([[0, 500]]))
})
it('filters out messages with invalid team', async () => {
@@ -563,11 +602,11 @@ describe('session-replay-pipeline', () => {
createMessage(0, 3, 'session-3', { token: 'valid-token' }),
]
- const result = await runSessionReplayPipeline(pipeline, messages)
+ const offsets = await runSessionReplayPipeline(pipeline, messages)
- expect(result).toHaveLength(2)
- expect(result[0].parsedMessage.session_id).toBe('session-1')
- expect(result[1].parsedMessage.session_id).toBe('session-3')
+ expect(recordedSessionIds()).toEqual(['session-1', 'session-3'])
+ // The invalid-team message (offset 2) isn't recorded, but its offset is still tracked.
+ expect(offsets).toEqual(new Map([[0, 3]]))
})
it('sends messages with no token header to DLQ', async () => {
@@ -585,10 +624,11 @@ describe('session-replay-pipeline', () => {
// Explicitly pass empty headers (no token)
const messages = [createMessage(0, 1, 'session-1', {})]
- const result = await runSessionReplayPipeline(pipeline, messages)
+ const offsets = await runSessionReplayPipeline(pipeline, messages)
- // Message should be dropped by team filter due to missing token
- expect(result).toHaveLength(0)
+ // Message is dropped by team filter due to missing token — not recorded, offset still tracked.
+ expect(recordedSessionIds()).toEqual([])
+ expect(offsets).toEqual(new Map([[0, 1]]))
})
it('sends ingestion warning for old lib version', async () => {
@@ -605,9 +645,9 @@ describe('session-replay-pipeline', () => {
const messages = [createMessage(0, 1, 'session-1', { token: 'test-token', lib_version: '1.74.0' })]
- const result = await runSessionReplayPipeline(pipeline, messages)
+ await runSessionReplayPipeline(pipeline, messages)
- expect(result).toHaveLength(1)
+ expect(recordedSessionIds()).toEqual(['session-1'])
expect(outputs.queueMessages).toHaveBeenCalledTimes(1)
expect(outputs.queueMessages).toHaveBeenCalledWith(
@@ -642,9 +682,9 @@ describe('session-replay-pipeline', () => {
const messages = [createMessage(0, 1, 'session-1', { token: 'test-token', lib_version: '1.75.0' })]
- const result = await runSessionReplayPipeline(pipeline, messages)
+ await runSessionReplayPipeline(pipeline, messages)
- expect(result).toHaveLength(1)
+ expect(recordedSessionIds()).toEqual(['session-1'])
expect(outputs.queueMessages).not.toHaveBeenCalled()
})
@@ -662,9 +702,9 @@ describe('session-replay-pipeline', () => {
const messages = [createMessage(0, 1, 'session-1', { token: 'test-token' })]
- const result = await runSessionReplayPipeline(pipeline, messages)
+ await runSessionReplayPipeline(pipeline, messages)
- expect(result).toHaveLength(1)
+ expect(recordedSessionIds()).toEqual(['session-1'])
expect(outputs.queueMessages).not.toHaveBeenCalled()
})
@@ -683,10 +723,11 @@ describe('session-replay-pipeline', () => {
// Create a message with timestamps 10 days old (threshold is 7 days)
const messages = [createMessageWithOldTimestamps(0, 1, 'session-1', 10, { token: 'test-token' })]
- const result = await runSessionReplayPipeline(pipeline, messages)
+ const offsets = await runSessionReplayPipeline(pipeline, messages)
- // Message should be dropped but warning should be sent
- expect(result).toHaveLength(0)
+ // Message is dropped (not recorded) but its offset is tracked and a warning is sent.
+ expect(recordedSessionIds()).toEqual([])
+ expect(offsets).toEqual(new Map([[0, 1]]))
expect(outputs.queueMessages).toHaveBeenCalledTimes(1)
expect(outputs.queueMessages).toHaveBeenCalledWith(
@@ -773,11 +814,12 @@ describe('session-replay-pipeline', () => {
const messages = [createMessage(0, 1, 'session-1')]
- const result = await runSessionReplayPipeline(pipeline, messages)
+ const offsets = await runSessionReplayPipeline(pipeline, messages)
- expect(result).toHaveLength(0)
const mockBatch = mockSessionBatchManager.getCurrentBatch()
expect(mockBatch.record).not.toHaveBeenCalled()
+ // Dropped, but its offset is still tracked so the partition commits past it.
+ expect(offsets).toEqual(new Map([[0, 1]]))
})
it('does not record messages with invalid team to session batch', async () => {
@@ -798,11 +840,12 @@ describe('session-replay-pipeline', () => {
const messages = [createMessage(0, 1, 'session-1', { token: 'invalid-token' })]
- const result = await runSessionReplayPipeline(pipeline, messages)
+ const offsets = await runSessionReplayPipeline(pipeline, messages)
- expect(result).toHaveLength(0)
const mockBatch = mockSessionBatchManager.getCurrentBatch()
expect(mockBatch.record).not.toHaveBeenCalled()
+ // Dropped, but its offset is still tracked so the partition commits past it.
+ expect(offsets).toEqual(new Map([[0, 1]]))
})
it('records parse time metric via TopHog', async () => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts
index 53821090d4ab..0cdc3d126c36 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts
@@ -5,10 +5,10 @@ import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
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 { BatchPipelineUnwrapper } from '~/ingestion/framework/batch-pipeline-unwrapper'
+import { BatchPipeline } from '~/ingestion/framework/batch-pipeline.interface'
import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'
import { TopHogRegistry, createTopHogWrapper, sum, timer } from '~/ingestion/framework/extensions/tophog'
-import { createBatch, createUnwrapper } from '~/ingestion/framework/helpers'
+import { createBatch } from '~/ingestion/framework/helpers'
import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'
import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'
import { SessionBatchManager } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-manager'
@@ -56,10 +56,11 @@ export interface SessionReplayPipelineConfig {
*/
export function createSessionReplayPipeline(
config: SessionReplayPipelineConfig
-): BatchPipelineUnwrapper<
+): BatchPipeline<
SessionReplayPipelineInput,
SessionReplayPipelineOutput,
{ message: Message },
+ { message: Message },
OverflowOutput
> {
const {
@@ -156,37 +157,52 @@ export function createSessionReplayPipeline(
.gather()
.build()
- return createUnwrapper(pipeline)
+ return pipeline
}
/**
- * Runs a batch of messages through the session replay pipeline.
+ * Runs a batch of messages through the session replay pipeline and returns the highest Kafka offset
+ * reached per partition.
+ *
+ * Every message ends the pipeline with a terminal result — OK (recorded), DROP, DLQ, or REDIRECT —
+ * and each result still carries its source message in the context. Draining them here and taking the
+ * max offset per partition is the single place Kafka progress is tracked: the recorder no longer
+ * tracks offsets while recording, and a message dropped before it reaches the recorder (restrictions,
+ * team filter, parse failure) still has its offset accounted for. The caller feeds the returned
+ * offsets to the offset manager, which commits them on the next flush.
*
- * Returns parsed messages for the existing team filtering/processing flow to continue.
- * In future commits, the pipeline will handle all processing internally.
+ * Relies on the pipeline draining the whole fed batch before it returns null, so every fed message
+ * yields exactly one terminal result here.
*/
export async function runSessionReplayPipeline(
- pipeline: BatchPipelineUnwrapper<
+ pipeline: BatchPipeline<
SessionReplayPipelineInput,
SessionReplayPipelineOutput,
{ message: Message },
+ { message: Message },
OverflowOutput
>,
messages: Message[]
-): Promise<SessionReplayPipelineOutput[]> {
+): Promise<Map<number, number>> {
+ const maxOffsetByPartition = new Map<number, number>()
if (messages.length === 0) {
- return []
+ return maxOffsetByPartition
}
const batch = createBatch(messages.map((message) => ({ message })))
pipeline.feed(batch)
- const allResults: SessionReplayPipelineOutput[] = []
let results = await pipeline.next()
while (results !== null) {
- allResults.push(...results)
+ for (const { context } of results) {
+ const { partition, offset } = context.message
+ const current = maxOffsetByPartition.get(partition)
+ if (current === undefined || offset > current) {
+ maxOffsetByPartition.set(partition, offset)
+ }
+ }
results = await pipeline.next()
}
- return allResults
+ return maxOffsetByPartition
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.ts
index 6ea09ffe2ac5..3a90c0ee5ad0 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.ts
@@ -128,6 +128,20 @@ export class SessionBatchManager {
return this.currentBatch
}
+ /**
+ * Track the highest Kafka offset reached per partition for a processed batch, so those offsets get
+ * committed on the next flush. This is the single place offset progress is recorded — the caller
+ * derives the offsets from every message's terminal pipeline result (record / drop / dlq / redirect),
+ * so no disposition is missed and the phases can't race.
+ *
+ * @param offsets - Highest offset seen per partition (raw offset, not the next-to-process offset).
+ */
+ public trackProcessedOffsets(offsets: Map<number, number>): void {
+ for (const [partition, offset] of offsets) {
+ this.offsetManager.trackOffset({ partition, offset })
+ }
+ }
+
/**
* Flushes the current batch and replaces it with a new one
*/
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts
index f09d67dc8e91..2a2194587c20 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts
@@ -342,7 +342,7 @@ describe('SessionBatchRecorder', () => {
expect(lines).toEqual([['window1', message.message.eventsByWindowId.window1[0]]])
})
- it('should process and flush a single session and track offsets', async () => {
+ it('should process and flush a single session', async () => {
const message = createMessage('session1', [
{
type: EventType.FullSnapshot,
@@ -352,10 +352,6 @@ describe('SessionBatchRecorder', () => {
])
await recorder.record(message)
- expect(mockOffsetManager.trackOffset).toHaveBeenCalledWith({
- partition: message.message.metadata.partition,
- offset: message.message.metadata.offset,
- })
await recorder.flush()
const writtenData = captureWrittenData(mockWriter.writeSession as jest.Mock)
@@ -387,12 +383,7 @@ describe('SessionBatchRecorder', () => {
for (const message of messages) {
await recorder.record(message)
- expect(mockOffsetManager.trackOffset).toHaveBeenCalledWith({
- partition: message.message.metadata.partition,
- offset: message.message.metadata.offset,
- })
}
- expect(mockOffsetManager.trackOffset).toHaveBeenCalledTimes(2)
await recorder.flush()
@@ -1289,10 +1280,6 @@ describe('SessionBatchRecorder', () => {
])
const bytesWritten = await recorder.record(message)
- expect(mockOffsetManager.trackOffset).toHaveBeenCalledWith({
- partition: message.message.metadata.partition,
- offset: message.message.metadata.offset,
- })
expect(recorder.size).toBe(bytesWritten)
recorder.discardPartition(999)
@@ -1775,35 +1762,6 @@ describe('SessionBatchRecorder', () => {
expect(mockWriter.writeSession).not.toHaveBeenCalled()
})
- it('should track offsets for rate limited events', async () => {
- recorder = new SessionBatchRecorder(
- mockOffsetManager,
- mockStorage,
- mockMetadataStore,
- mockConsoleLogStore,
- mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
- mockEncryptor,
- 1
- )
-
- const messages = [
- createMessage('session1', [{ type: EventType.Meta, timestamp: 1000, data: {} }], { offset: 100 }),
- createMessage('session1', [{ type: EventType.Meta, timestamp: 2000, data: {} }], { offset: 101 }),
- createMessage('session1', [{ type: EventType.Meta, timestamp: 3000, data: {} }], { offset: 102 }),
- ]
-
- for (const message of messages) {
- await recorder.record(message)
- }
-
- expect(mockOffsetManager.trackOffset).toHaveBeenCalledWith({ partition: 1, offset: 100 })
- expect(mockOffsetManager.trackOffset).toHaveBeenCalledWith({ partition: 1, offset: 101 })
- expect(mockOffsetManager.trackOffset).toHaveBeenCalledWith({ partition: 1, offset: 102 })
- })
-
it('should rate limit sessions independently', async () => {
recorder = new SessionBatchRecorder(
mockOffsetManager,
@@ -2105,7 +2063,6 @@ describe('SessionBatchRecorder', () => {
const bytesWritten = await recorder.record(message)
expect(bytesWritten).toBe(0)
- expect(mockOffsetManager.trackOffset).toHaveBeenCalledWith({ partition: 1, offset: 42 })
})
it('should drop messages when session key changes between calls', async () => {
@@ -2141,7 +2098,6 @@ describe('SessionBatchRecorder', () => {
expect(bytes1).toBeGreaterThan(0)
expect(bytes2).toBe(0)
- expect(mockOffsetManager.trackOffset).toHaveBeenCalledWith({ partition: 1, offset: 1 })
})
})
@@ -2186,21 +2142,6 @@ describe('SessionBatchRecorder', () => {
expect(mockSessionFilter.isBlocked).toHaveBeenCalledWith(1, 'session1')
})
- it('should track offset when new session is blocked', async () => {
- mockSessionTracker.trackSession.mockResolvedValue(true)
- mockSessionFilter.isBlocked.mockResolvedValue(true)
-
- const message = createMessage(
- 'session1',
- [{ type: EventType.FullSnapshot, timestamp: 1000, data: { source: 1 } }],
- { partition: 1, offset: 42 }
- )
-
- await recorder.record(message)
-
- expect(mockOffsetManager.trackOffset).toHaveBeenCalledWith({ partition: 1, offset: 42 })
- })
-
it('should allow new session when not blocked', async () => {
mockSessionTracker.trackSession.mockResolvedValue(true)
mockSessionFilter.isBlocked.mockResolvedValue(false)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts
index 39f9ccc4fa36..d108ccb7cc93 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts
@@ -119,7 +119,7 @@ export class SessionBatchRecorder {
teamId,
batchId: this.batchId,
})
- return this.ignoreMessage(message)
+ return 0
}
const sessionKey = isNewSession
@@ -133,7 +133,7 @@ export class SessionBatchRecorder {
teamId,
batchId: this.batchId,
})
- return this.ignoreMessage(message)
+ return 0
}
const isEventAllowed = this.rateLimiter.handleMessage(teamSessionKey, partition, message.message)
@@ -148,7 +148,7 @@ export class SessionBatchRecorder {
})
if (!this.partitionSessions.has(partition)) {
- return this.ignoreMessage(message)
+ return 0
}
const sessions = this.partitionSessions.get(partition)!
@@ -162,7 +162,7 @@ export class SessionBatchRecorder {
})
}
- return this.ignoreMessage(message)
+ return 0
}
if (!this.partitionSessions.has(partition)) {
@@ -182,7 +182,7 @@ export class SessionBatchRecorder {
newTeamId: teamId,
batchId: this.batchId,
})
- return this.ignoreMessage(message)
+ return 0
}
if (!existingSessionKey.encryptedKey.equals(sessionKey.encryptedKey)) {
@@ -191,7 +191,7 @@ export class SessionBatchRecorder {
teamId,
batchId: this.batchId,
})
- return this.ignoreMessage(message)
+ return 0
}
} else {
sessions.set(teamSessionKey, [
@@ -222,29 +222,10 @@ export class SessionBatchRecorder {
this.partitionSizes.set(partition, currentPartitionSize + bytesWritten)
this._size += bytesWritten
- return this.ackMessage(message, bytesWritten)
- }
-
- private ignoreMessage(message: MessageWithTeam): 0 {
- this.offsetManager.trackOffset({
- partition: message.message.metadata.partition,
- offset: message.message.metadata.offset,
- })
- return 0
- }
-
- private ackMessage(message: MessageWithTeam, bytesWritten: number): number {
- const { partition } = message.message.metadata
-
- this.offsetManager.trackOffset({
- partition: message.message.metadata.partition,
- offset: message.message.metadata.offset,
- })
-
logger.debug('🔁', 'session_batch_recorder_recorded_message', {
partition,
- sessionId: message.message.session_id,
- teamId: message.team.teamId,
+ sessionId,
+ teamId,
bytesWritten,
totalSize: this._size,
})