: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
refactor(replay): take the session batch recorder from the element, not the manager (#69925)
Paweł Ledwoń7c28fa85e12f
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.tsindex 3753632263b8..47715ed679e8 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts@@ -14,12 +14,10 @@ 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 { BatchPipeline } from '~/ingestion/framework/batch-pipeline.interface'import { TopHog } from '~/ingestion/framework/tophog/tophog'import {+ SessionReplayPipeline,SessionReplayPipelineConfig,- SessionReplayPipelineInput,- SessionReplayPipelineOutput,createSessionReplayPipeline,runSessionReplayPipeline,} from '~/ingestion/pipelines/sessionreplay'@@ -62,15 +60,7 @@ export type SessionRecordingIngesterConfig = SessionRecordingConfig &>/** Builds the session replay pipeline for a deployment (default or ML mirror). */-export type SessionReplayPipelineFactory = (- config: SessionReplayPipelineConfig-) => BatchPipeline<- SessionReplayPipelineInput,- SessionReplayPipelineOutput,- { message: Message },- { message: Message },- OverflowOutput->+export type SessionReplayPipelineFactory = (config: SessionReplayPipelineConfig) => SessionReplayPipeline/** Collaborators a deployment can inject to vary ingester behavior; anything omitted uses the primary default. */export interface SessionRecordingIngesterCollaborators {@@ -107,13 +97,7 @@ export class SessionRecordingIngester {private readonly eventIngestionRestrictionManagerComponent: EventIngestionRestrictionManagerComponentprivate eventIngestionRestrictionManager!: EventIngestionRestrictionManagerprivate stopEventIngestionRestrictionManager?: () => Promise<void>- private sessionReplayPipeline!: BatchPipeline<- SessionReplayPipelineInput,- SessionReplayPipelineOutput,- { message: Message },- { message: Message },- OverflowOutput- >+ private sessionReplayPipeline!: SessionReplayPipelineprivate readonly outputs: IngestionOutputs<| IngestionWarningsOutput| DlqOutput@@ -286,7 +270,7 @@ export class SessionRecordingIngester {// Run messages through the pipeline (handles restrictions, parsing, team filtering, and recording)// 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)+ runSessionReplayPipeline(this.sessionReplayPipeline, messages, this.promiseScheduler))this.sessionBatchManager.trackProcessedOffsets(offsets)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/index.ts b/nodejs/src/ingestion/pipelines/sessionreplay/index.tsindex 2d85aed09000..78eec22ff09f 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/index.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/index.ts@@ -1,6 +1,7 @@export {createSessionReplayPipeline,runSessionReplayPipeline,+ type SessionReplayPipeline,type SessionReplayPipelineConfig,type SessionReplayPipelineInput,type SessionReplayPipelineOutput,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.tsindex 9789fb581ef8..f7b9f529106e 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@@ -250,7 +250,7 @@ describe('ml-mirror-pipeline', () => {getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),} as unknown as TeamService- await runSessionReplayPipeline(buildPipeline(), [message('sess-1')])+ await runSessionReplayPipeline(buildPipeline(), [message('sess-1')], promiseScheduler)expect(recordMock).toHaveBeenCalledTimes(1)const [windowId, event] = recordedEvents()[0]@@ -265,7 +265,7 @@ describe('ml-mirror-pipeline', () => {getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),} as unknown as TeamService- await runSessionReplayPipeline(buildPipeline(), [message('sess-2')])+ await runSessionReplayPipeline(buildPipeline(), [message('sess-2')], promiseScheduler)expect(recordMock).not.toHaveBeenCalled()})@@ -276,7 +276,7 @@ describe('ml-mirror-pipeline', () => {getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),} as unknown as TeamService- await runSessionReplayPipeline(buildPipeline(), [fullSnapshotMessage('sess-3')])+ await runSessionReplayPipeline(buildPipeline(), [fullSnapshotMessage('sess-3')], promiseScheduler)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.tsindex d41b9750c45b..267cc9e10361 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,11 +1,12 @@/** The primary session replay pipeline plus an AI-training opt-in filter and an anonymize step. */import { OverflowOutput } from '~/common/outputs'import { createApplyEventRestrictionsStep, createParseHeadersStep } from '~/ingestion/common/steps/event-preprocessing'-import { BatchPipeline } from '~/ingestion/framework/batch-pipeline.interface'-import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'+import { newBatchingPipeline } from '~/ingestion/framework/builders'import { createTopHogWrapper, sum, timer } from '~/ingestion/framework/extensions/tophog'import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'+import { ok } from '~/ingestion/framework/results'import {+ SessionReplayPipeline,SessionReplayPipelineConfig,SessionReplayPipelineInput,SessionReplayPipelineOutput,@@ -14,22 +15,16 @@ import { createAiTrainingOptInFilterStep } from '~/ingestion/pipelines/sessionreimport { createParseAndAnonymizeMessageStep } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'import { MessageContext } from '~/ingestion/pipelines/sessionreplay/pipeline-types'import { createRecordSessionEventStep } from '~/ingestion/pipelines/sessionreplay/record-session-event-step'+import { SessionBatchContext } from '~/ingestion/pipelines/sessionreplay/session-batch-context'import { createMarkSeenStep } from '~/ingestion/pipelines/sessionreplay/session-batch-mark-seen-step'import { createResolveRetentionStep } from '~/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step'+import { createAttachSessionBatchStep } from '~/ingestion/pipelines/sessionreplay/session-batch-step'import { createTrackAndGateStep } from '~/ingestion/pipelines/sessionreplay/session-batch-track-and-gate-step'import { createResolveKeyStep } from '~/ingestion/pipelines/sessionreplay/session-resolve-key-step'import { createTeamFilterStep } from '~/ingestion/pipelines/sessionreplay/team-filter-step'import { createValidateSessionReplayHeadersStep } from '~/ingestion/pipelines/sessionreplay/validate-headers-step'-export function createMlMirrorReplayPipeline(- config: SessionReplayPipelineConfig-): BatchPipeline<- SessionReplayPipelineInput,- SessionReplayPipelineOutput,- MessageContext,- MessageContext,- OverflowOutput-> {+export function createMlMirrorReplayPipeline(config: SessionReplayPipelineConfig): SessionReplayPipeline {const {outputs,eventIngestionRestrictionManager,@@ -49,106 +44,120 @@ export function createMlMirrorReplayPipeline(const pipelineConfig: PipelineConfig<OverflowOutput> = { outputs, promiseScheduler }const topHogWrapper = createTopHogWrapper(topHog)- const pipeline = newBatchPipelineBuilder<SessionReplayPipelineInput, MessageContext>()- .messageAware((b) =>- b- .sequentially((b) =>+ return newBatchingPipeline<+ SessionReplayPipelineInput,+ SessionReplayPipelineOutput,+ MessageContext,+ SessionBatchContext,+ MessageContext,+ OverflowOutput+ >(+ (beforeBatch) => beforeBatch.pipe(createAttachSessionBatchStep(sessionBatchManager)),+ (batch) =>+ batch+ .messageAware((b) =>b- .pipe(createParseHeadersStep())- .pipe(- createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {- overflowMode,- preservePartitionLocality: true,- })+ .sequentially((b) =>+ b+ .pipe(createParseHeadersStep())+ .pipe(+ createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {+ overflowMode,+ preservePartitionLocality: true,+ })+ )+ .pipe(createValidateSessionReplayHeadersStep())+ .pipe(createTeamFilterStep(teamService))+ // Mirror only data from orgs that opted into AI training.+ .pipe(createAiTrainingOptInFilterStep()))- .pipe(createValidateSessionReplayHeadersStep())- .pipe(createTeamFilterStep(teamService))- // Mirror only data from orgs that opted into AI training.- .pipe(createAiTrainingOptInFilterStep())- )- // Resolve retention up front (before parse), keyed on the (validated) session_id- // header; drop unresolvable sessions.- .gather()- .pipeBatch(createResolveRetentionStep(retentionService, sessionBatchManager), {- retry: { tries: 3, sleepMs: 100 },- })- // Track sessions and rate-limit new ones for the whole batch, tagging each with- // isNewSession and a gate verdict; blocked sessions are carried (not dropped) to the- // mark-seen step, all in this step's own retry scope.- .pipeBatch(createTrackAndGateStep(sessionTracker, sessionFilter), {- retry: { tries: 3, sleepMs: 100 },- })- // Resolve each session's encryption key once per session (grouped), concurrently across- // sessions with a bounded fan-out and per-session retry. Deleted sessions drop here.- .concurrentlyPerGroup(- (element) => `${element.team.teamId}:${element.headers.session_id}`,- (group) =>- group.sequentially((b) =>- b.pipe(createResolveKeyStep(keyStore), {- retry: { name: 'resolve_session_key', tries: 3, sleepMs: 100 },- })- ),- { maxConcurrency: sessionKeyResolutionMaxConcurrency }- )- // Re-collect the per-session groups into one batch — both to mark the whole batch seen- // in a single Redis write and as the barrier that guarantees every key is resolved first.- .gather()- // Mark the surviving new sessions seen, now that every key is durably resolved.- .pipeBatch(createMarkSeenStep(sessionTracker))- .filterMap(- (element) => ({- result: element.result,- context: {- ...element.context,- team: { id: element.result.value.team.teamId },- },- }),- (b) =>- b- .teamAware((b) =>+ // Resolve retention up front (before parse), keyed on the (validated) session_id+ // header; drop unresolvable sessions.+ .gather()+ .pipeBatch(createResolveRetentionStep(retentionService), {+ retry: { tries: 3, sleepMs: 100 },+ })+ // Track sessions and rate-limit new ones for the whole batch, tagging each with+ // isNewSession and a gate verdict; blocked sessions are carried (not dropped) to the+ // mark-seen step, all in this step's own retry scope.+ .pipeBatch(createTrackAndGateStep(sessionTracker, sessionFilter), {+ retry: { tries: 3, sleepMs: 100 },+ })+ // Resolve each session's encryption key once per session (grouped), concurrently across+ // sessions with a bounded fan-out and per-session retry. Deleted sessions drop here.+ .concurrentlyPerGroup(+ (element) => `${element.team.teamId}:${element.headers.session_id}`,+ (group) =>+ group.sequentially((b) =>+ b.pipe(createResolveKeyStep(keyStore), {+ retry: { name: 'resolve_session_key', tries: 3, sleepMs: 100 },+ })+ ),+ { maxConcurrency: sessionKeyResolutionMaxConcurrency }+ )+ // Re-collect the per-session groups into one batch — both to mark the whole batch seen+ // in a single Redis write and as the barrier that guarantees every key is resolved first.+ .gather()+ // Mark the surviving new sessions seen, now that every key is durably resolved.+ .pipeBatch(createMarkSeenStep(sessionTracker))+ .filterMap(+ (element) => ({+ result: element.result,+ context: {+ ...element.context,+ team: { id: element.result.value.team.teamId },+ },+ }),+ (b) =>b- .sequentially((b) => {- // The native Rust addon fuses parse+anonymize in one step.- const parsed = b.pipe(- topHogWrapper(createParseAndAnonymizeMessageStep(), [- timer('parse_time_ms_by_session_id', (input) => ({- token: input.headers.token ?? 'unknown',- session_id: input.headers.session_id ?? 'unknown',- })),- ])- )- return parsed.pipe(- topHogWrapper(- createRecordSessionEventStep({- sessionBatchManager,- isDebugLoggingEnabled,- }),- [- sum(- 'message_size_by_session_id',- (input) => ({- token: input.parsedMessage.token ?? 'unknown',- session_id: input.parsedMessage.session_id,+ .teamAware((b) =>+ b+ .sequentially((b) => {+ // The native Rust addon fuses parse+anonymize in one step.+ const parsed = b.pipe(+ topHogWrapper(createParseAndAnonymizeMessageStep(), [+ timer('parse_time_ms_by_session_id', (input) => ({+ token: input.headers.token ?? 'unknown',+ session_id: input.headers.session_id ?? 'unknown',+ })),+ ])+ )+ return parsed.pipe(+ topHogWrapper(+ createRecordSessionEventStep({+ isDebugLoggingEnabled,}),- (input) => input.parsedMessage.metadata.rawSize- ),- timer('consume_time_ms_by_session_id', (input) => ({- token: input.parsedMessage.token ?? 'unknown',- session_id: input.parsedMessage.session_id,- })),- ]- )- )- })- .gather()- )- .handleIngestionWarnings(outputs)+ [+ sum(+ 'message_size_by_session_id',+ (input) => ({+ token: input.parsedMessage.token ?? 'unknown',+ session_id: input.parsedMessage.session_id,+ }),+ (input) => input.parsedMessage.metadata.rawSize+ ),+ timer('consume_time_ms_by_session_id', (input) => ({+ token: input.parsedMessage.token ?? 'unknown',+ session_id: input.parsedMessage.session_id,+ })),+ ]+ )+ )+ })+ .gather()+ )+ .handleIngestionWarnings(outputs)+ ))- )- .handleResults(pipelineConfig)- .handleSideEffects(promiseScheduler, { await: false })- .gather()- .build()-- return pipeline+ .handleResults(pipelineConfig)+ .handleSideEffects(promiseScheduler, { await: false })+ .gather(),+ (afterBatch) =>+ 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 }+ )}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.test.tsindex fbc08e5b3493..98b4e2706fd4 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.test.ts@@ -3,7 +3,6 @@ import { DateTime } from 'luxon'import { PipelineResultType } from '~/ingestion/framework/results'import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'import { SessionRecordingIngesterMetrics } from '~/ingestion/pipelines/sessionreplay/metrics'-import { SessionBatchManager } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-manager'import { SessionBatchRecorder } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder'import { createMockSessionKey } from '~/ingestion/pipelines/sessionreplay/shared/test-helpers'import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'@@ -18,7 +17,6 @@ jest.mock('~/ingestion/pipelines/sessionreplay/metrics', () => ({}))describe('createRecordSessionEventStep', () => {- let mockSessionBatchManager: jest.Mocked<SessionBatchManager>let mockBatchRecorder: jest.Mocked<SessionBatchRecorder>const defaultTeam: TeamForReplay = {@@ -54,6 +52,8 @@ describe('createRecordSessionEventStep', () => {parsedMessage: createParsedMessage(overrides),retentionPeriod: '30d',sessionKey: createMockSessionKey(),+ // The recorder is tagged onto the element by the pipeline's beforeBatch.+ sessionBatchRecorder: mockBatchRecorder,})beforeEach(() => {@@ -62,22 +62,16 @@ describe('createRecordSessionEventStep', () => {mockBatchRecorder = {record: jest.fn().mockResolvedValue(100),} as unknown as jest.Mocked<SessionBatchRecorder>-- mockSessionBatchManager = {- getCurrentBatch: jest.fn().mockReturnValue(mockBatchRecorder),- } as unknown as jest.Mocked<SessionBatchManager>})- it('should record message to session batch', async () => {+ it('should record message to the batch recorder carried on the element', async () => {const step = createRecordSessionEventStep({- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled: () => false,})const input = createInput()await step(input)- expect(mockSessionBatchManager.getCurrentBatch).toHaveBeenCalledTimes(1)expect(mockBatchRecorder.record).toHaveBeenCalledTimes(1)expect(mockBatchRecorder.record).toHaveBeenCalledWith({@@ -91,7 +85,6 @@ describe('createRecordSessionEventStep', () => {it('should return ok result with input preserved', async () => {const step = createRecordSessionEventStep({- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled: () => false,})@@ -108,7 +101,6 @@ describe('createRecordSessionEventStep', () => {it('should reset sessions revoked metric', async () => {const step = createRecordSessionEventStep({- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled: () => false,})@@ -119,7 +111,6 @@ describe('createRecordSessionEventStep', () => {it('should observe session info metric', async () => {const step = createRecordSessionEventStep({- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled: () => false,})@@ -131,7 +122,6 @@ describe('createRecordSessionEventStep', () => {it('should preserve additional input properties', async () => {const step = createRecordSessionEventStep<RecordSessionEventStepInput & { extraProperty: string }>({- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled: () => false,})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.tsindex 52ad5162e995..0c3eeca90a75 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.ts@@ -3,13 +3,13 @@ import { ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'import { SessionRecordingIngesterMetrics } from '~/ingestion/pipelines/sessionreplay/metrics'-import { SessionBatchManager } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-manager'+import { SessionBatchContext } from '~/ingestion/pipelines/sessionreplay/session-batch-context'import { RetentionPeriod } from '~/ingestion/pipelines/sessionreplay/shared/constants'import { SessionKey } from '~/ingestion/pipelines/sessionreplay/shared/types'import { MessageWithTeam, TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'import { ValueMatcher } from '~/types'-export interface RecordSessionEventStepInput {+export interface RecordSessionEventStepInput extends SessionBatchContext {team: TeamForReplayparsedMessage: ParsedMessageDataretentionPeriod: RetentionPeriod@@ -17,7 +17,6 @@ export interface RecordSessionEventStepInput {}export interface RecordSessionEventStepConfig {- sessionBatchManager: SessionBatchManagerisDebugLoggingEnabled: ValueMatcher<number>}@@ -32,10 +31,10 @@ export interface RecordSessionEventStepConfig {export function createRecordSessionEventStep<T extends RecordSessionEventStepInput>(config: RecordSessionEventStepConfig): ProcessingStep<T, T> {- const { sessionBatchManager, isDebugLoggingEnabled } = config+ const { isDebugLoggingEnabled } = configreturn async function recordSessionEventStep(input) {- const { team, parsedMessage, retentionPeriod, sessionKey } = input+ const { team, parsedMessage, retentionPeriod, sessionKey, sessionBatchRecorder } = input// Reset revoked sessions counter once we're consumingSessionRecordingIngesterMetrics.resetSessionsRevoked()@@ -58,10 +57,9 @@ export function createRecordSessionEventStep<T extends RecordSessionEventStepInpSessionRecordingIngesterMetrics.observeSessionInfo(parsedMessage.metadata.rawSize)- // Record to the session batch- const batch = sessionBatchManager.getCurrentBatch()+ // Record to the batch's recorder, carried on the element by the pipeline's beforeBatch.const messageWithTeam: MessageWithTeam = { team, message: parsedMessage }- await batch.record(messageWithTeam, retentionPeriod, sessionKey)+ await sessionBatchRecorder.record(messageWithTeam, retentionPeriod, sessionKey)return ok(input)}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-context.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-context.tsnew file mode 100644index 000000000000..0b23121cb0e3--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-context.ts@@ -0,0 +1,13 @@+import { SessionBatchRecorder } from './sessions/session-batch-recorder'++/**+ * Batch context attached to every element of a pipeline batch: the recorder the record step folds+ * events into. Tagged on by the pipeline's beforeBatch hook, so steps read the recorder from their+ * element instead of holding a reference to shared batch state.+ *+ * This is a pipeline-level concern (the unit the pipeline threads through its steps), not a recorder+ * concern — the recorder is just what it happens to carry.+ */+export interface SessionBatchContext {+ sessionBatchRecorder: SessionBatchRecorder+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.test.tsindex 2f7d454de12b..63e24364a3c7 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.test.ts@@ -7,9 +7,9 @@ import { SessionMap, SessionSet } from '~/ingestion/pipelines/sessionreplay/sharimport { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'import { SessionReplayHeaders } from './pipeline-types'+import { SessionBatchContext } from './session-batch-context'import { createResolveRetentionStep } from './session-batch-resolve-retention-step'import { SessionBatchMetrics } from './sessions/metrics'-import { SessionBatchManager } from './sessions/session-batch-manager'import { SessionBatchRecorder } from './sessions/session-batch-recorder'jest.mock('~/common/utils/logger', () => ({ logger: { warn: jest.fn() } }))@@ -20,27 +20,20 @@ jest.mock('./sessions/metrics', () => ({describe('createResolveRetentionStep', () => {let mockRetentionService: jest.Mocked<RetentionService>let mockBatch: jest.Mocked<Pick<SessionBatchRecorder, 'getRetention'>>- let mockSessionBatchManager: jest.Mocked<Pick<SessionBatchManager, 'getCurrentBatch'>>- // Minimal element carrying just what the step reads (message offset, team id, session_id header).+ // Minimal element carrying just what the step reads (team id, session_id header, the recorder).const element = (teamId: number,- sessionId: string,- partition = 0,- offset = 0- ): { message: { partition: number; offset: number }; team: TeamForReplay; headers: SessionReplayHeaders } =>+ sessionId: string+ ): { team: TeamForReplay; headers: SessionReplayHeaders } & SessionBatchContext =>({- message: { partition, offset },team: { teamId, consoleLogIngestionEnabled: false, aiTrainingOptedIn: true },headers: { token: 'token', session_id: sessionId, distinct_id: 'distinct-1' },- }) as unknown as {- message: { partition: number; offset: number }- team: TeamForReplay- headers: SessionReplayHeaders- }+ // The recorder is tagged onto the element by the pipeline's beforeBatch.+ sessionBatchRecorder: mockBatch,+ }) as unknown as { team: TeamForReplay; headers: SessionReplayHeaders } & SessionBatchContext- const createStep = () =>- createResolveRetentionStep(mockRetentionService, mockSessionBatchManager as unknown as SessionBatchManager)+ const createStep = () => createResolveRetentionStep(mockRetentionService)beforeEach(() => {jest.clearAllMocks()@@ -51,9 +44,6 @@ describe('createResolveRetentionStep', () => {mockBatch = { getRetention: jest.fn().mockReturnValue(undefined) } as unknown as jest.Mocked<Pick<SessionBatchRecorder, 'getRetention'>>- mockSessionBatchManager = {- getCurrentBatch: jest.fn().mockReturnValue(mockBatch),- } as unknown as jest.Mocked<Pick<SessionBatchManager, 'getCurrentBatch'>>})it('resolves the batch in one call (keyed on the session_id header) and attaches retention', async () => {@@ -121,7 +111,7 @@ describe('createResolveRetentionStep', () => {)const step = createStep()- const results = await step([element(999, 'gone', 4, 42), element(2, 'ok')])+ const results = await step([element(999, 'gone'), element(2, 'ok')])expect(mockRetentionService.resolveSessionRetentions).toHaveBeenCalledWith(new SessionSet().add(999, 'gone').add(2, 'ok')diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.tsindex d564a4a7b829..171ed2ae3ada 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.ts@@ -1,5 +1,3 @@-import { Message } from 'node-rdkafka'-import { logger } from '~/common/utils/logger'import { BatchProcessingStep } from '~/ingestion/framework/base-batch-pipeline'import { drop, ok } from '~/ingestion/framework/results'@@ -9,8 +7,8 @@ import { SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-mimport { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'import { SessionReplayHeaders } from './pipeline-types'+import { SessionBatchContext } from './session-batch-context'import { SessionBatchMetrics } from './sessions/metrics'-import { SessionBatchManager } from './sessions/session-batch-manager'/*** Record-phase batch step: resolve per-session retention for the whole batch and attach it to each@@ -28,16 +26,15 @@ import { SessionBatchManager } from './sessions/session-batch-manager'* stage picks it up (see {@link runSessionReplayPipeline}).*/export function createResolveRetentionStep<- T extends { message: Pick<Message, 'partition' | 'offset'>; team: TeamForReplay; headers: SessionReplayHeaders },->(- retentionService: RetentionService,- sessionBatchManager: SessionBatchManager-): BatchProcessingStep<T, T & { retentionPeriod: RetentionPeriod }> {+ T extends { team: TeamForReplay; headers: SessionReplayHeaders } & SessionBatchContext,+>(retentionService: RetentionService): BatchProcessingStep<T, T & { retentionPeriod: RetentionPeriod }> {return async function resolveRetentionStep(values) {- const batch = sessionBatchManager.getCurrentBatch()- // Reuse retention already resolved for sessions still in the current batch; resolve the rest.- // Collecting into a SessionSet dedupes repeated sessions so each is looked up only once.- const batchRetentions = values.map((value) => batch.getRetention(value.team.teamId, value.headers.session_id))+ // Reuse retention already resolved for sessions still in the current (unflushed) recorder,+ // carried on every element by the pipeline's beforeBatch; resolve the rest. Collecting into+ // a SessionSet dedupes repeated sessions so each is looked up only once.+ const batchRetentions = values.map((value) =>+ value.sessionBatchRecorder.getRetention(value.team.teamId, value.headers.session_id)+ )const toResolve = new SessionSet()values.forEach((value, index) => {if (batchRetentions[index] === undefined) {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-step.tsnew file mode 100644index 000000000000..44724629532f--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-step.ts@@ -0,0 +1,25 @@+import { BeforeBatchInput, BeforeBatchOutput } from '~/ingestion/framework/batching-pipeline'+import { ok } from '~/ingestion/framework/results'+import { ProcessingStep } from '~/ingestion/framework/steps'++import { SessionBatchContext } from './session-batch-context'+import { SessionBatchManager } from './sessions/session-batch-manager'++/**+ * beforeBatch hook for the session replay pipeline: tags the manager's current recorder onto the+ * batch context, which the batching pipeline merges into every element ({@link SessionBatchContext}).+ * Steps that fold into or read from the batch take the recorder off their element, so they stay+ * decoupled from the manager and its current-batch state.+ */+export function createAttachSessionBatchStep<TInput, CInput>(+ sessionBatchManager: SessionBatchManager+): ProcessingStep<BeforeBatchInput<TInput, CInput>, BeforeBatchOutput<TInput, CInput, SessionBatchContext>> {+ return function attachSessionBatchStep(input) {+ return Promise.resolve(+ ok({+ elements: input.elements,+ batchContext: { ...input.batchContext, sessionBatchRecorder: sessionBatchManager.getCurrentBatch() },+ })+ )+ }+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-rate-limiter.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-rate-limiter.test.tsindex 77318a7b989d..9f9e27de373e 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-rate-limiter.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-rate-limiter.test.ts@@ -265,7 +265,7 @@ describe('session-replay-pipeline rate limiter failure modes', () => {}async function runBatch(sessionId: string, offset: number): Promise<void> {- await runSessionReplayPipeline(buildPipeline(), [createMessage(sessionId, offset)])+ await runSessionReplayPipeline(buildPipeline(), [createMessage(sessionId, offset)], new PromiseScheduler())}// Assert a one-shot fault armed with failNext() actually fired — guards against a silently-inert faultdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.tsindex 82a33ead6ee9..879c5ae30900 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts@@ -307,7 +307,7 @@ describe('session-replay-pipeline', () => {const messages = [createMessage(0, 1, 'session-1'), createMessage(0, 2, 'session-2')]- const offsets = await runSessionReplayPipeline(pipeline, messages)+ const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1', 'session-2'])// Highest offset reached on the partition is tracked.@@ -346,7 +346,7 @@ describe('session-replay-pipeline', () => {createMessage(0, 3, 'session-3'),]- const offsets = await runSessionReplayPipeline(pipeline, messages)+ const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1', 'session-3'])// The dropped message (offset 2) is not recorded, but its offset is still accounted for —@@ -386,7 +386,7 @@ describe('session-replay-pipeline', () => {createMessage(0, 3, 'session-3'),]- const offsets = await runSessionReplayPipeline(pipeline, messages)+ const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1', 'session-2'])// The highest offset on the partition belongs to the dropped message; it must still be@@ -432,7 +432,7 @@ describe('session-replay-pipeline', () => {createMessage(0, 3, 'session-3'),]- const offsets = await runSessionReplayPipeline(pipeline, messages)+ const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1', 'session-2'])// The highest offset on the partition belongs to the blocked session; it must still be tracked@@ -507,7 +507,7 @@ describe('session-replay-pipeline', () => {createMessage(1, 5, 'session-4'), // recorded on partition 1 at a higher offset]- const offsets = await runSessionReplayPipeline(pipeline, messages)+ const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)expect(recordedSessionIds().sort()).toEqual(['session-1', 'session-2', 'session-4'])expect(offsets).toEqual(@@ -549,7 +549,7 @@ describe('session-replay-pipeline', () => {const messages = [createMessage(0, 1, 'session-1'), invalidMessage, createMessage(0, 3, 'session-3')]- const offsets = await runSessionReplayPipeline(pipeline, messages)+ const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1', 'session-3'])// The unparseable message (offset 2) is DLQ'd, but its offset is still accounted for.@@ -587,7 +587,7 @@ describe('session-replay-pipeline', () => {const messages = [invalidMessage]- await runSessionReplayPipeline(pipeline, messages)+ await runSessionReplayPipeline(pipeline, messages, promiseScheduler)// Wait for side effects to completeawait promiseScheduler.waitForAll()@@ -633,7 +633,7 @@ describe('session-replay-pipeline', () => {createMessage(0, 3, 'session-3'),]- const offsets = await runSessionReplayPipeline(pipeline, messages)+ const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)// Wait for side effects to completeawait promiseScheduler.waitForAll()@@ -663,7 +663,7 @@ describe('session-replay-pipeline', () => {isDebugLoggingEnabled,})- const offsets = await runSessionReplayPipeline(pipeline, [])+ const offsets = await runSessionReplayPipeline(pipeline, [], promiseScheduler)expect(offsets.size).toBe(0)})@@ -701,7 +701,7 @@ describe('session-replay-pipeline', () => {messages.push(createMessage(0, i))}- const offsets = await runSessionReplayPipeline(pipeline, messages)+ const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)// 100 messages dropped (10, 20, ..., 1000), 900 recordedconst recorded = recordedSessionIds()@@ -748,7 +748,7 @@ describe('session-replay-pipeline', () => {createMessage(0, 2, 'session-2', { token: 'team-token-789' }),]- await runSessionReplayPipeline(pipeline, messages)+ await runSessionReplayPipeline(pipeline, messages, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1', 'session-2'])// Verify headers were correctly parsed and passed through@@ -789,7 +789,7 @@ describe('session-replay-pipeline', () => {messages.push(createMessage(0, i))}- const offsets = await runSessionReplayPipeline(pipeline, messages)+ const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)const recorded = recordedSessionIds()expect(recorded).toHaveLength(500)@@ -832,7 +832,7 @@ describe('session-replay-pipeline', () => {createMessage(0, 3, 'session-3', { token: 'valid-token' }),]- const offsets = await runSessionReplayPipeline(pipeline, messages)+ const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1', 'session-3'])// The invalid-team message (offset 2) isn't recorded, but its offset is still tracked.@@ -859,7 +859,7 @@ describe('session-replay-pipeline', () => {// Explicitly pass empty headers (no token)const messages = [createMessage(0, 1, 'session-1', {})]- const offsets = await runSessionReplayPipeline(pipeline, messages)+ const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)// Message is dropped by team filter due to missing token — not recorded, offset still tracked.expect(recordedSessionIds()).toEqual([])@@ -885,7 +885,7 @@ describe('session-replay-pipeline', () => {const messages = [createMessage(0, 1, 'session-1', { token: 'test-token', lib_version: '1.74.0' })]- await runSessionReplayPipeline(pipeline, messages)+ await runSessionReplayPipeline(pipeline, messages, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1'])expect(outputs.queueMessages).toHaveBeenCalledTimes(1)@@ -929,7 +929,7 @@ describe('session-replay-pipeline', () => {const messages = [createMessage(0, 1, 'session-1', { token: 'test-token', lib_version: '1.75.0' })]- await runSessionReplayPipeline(pipeline, messages)+ await runSessionReplayPipeline(pipeline, messages, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1'])expect(outputs.queueMessages).not.toHaveBeenCalled()@@ -954,7 +954,7 @@ describe('session-replay-pipeline', () => {const messages = [createMessage(0, 1, 'session-1', { token: 'test-token' })]- await runSessionReplayPipeline(pipeline, messages)+ await runSessionReplayPipeline(pipeline, messages, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1'])expect(outputs.queueMessages).not.toHaveBeenCalled()@@ -980,7 +980,7 @@ 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 offsets = await runSessionReplayPipeline(pipeline, messages)+ const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)// Message is dropped (not recorded) but its offset is tracked and a warning is sent.expect(recordedSessionIds()).toEqual([])@@ -1020,7 +1020,7 @@ describe('session-replay-pipeline', () => {const messages = [createMessage(0, 1, 'session-1')]- await runSessionReplayPipeline(pipeline, messages)+ await runSessionReplayPipeline(pipeline, messages, promiseScheduler)expect(mockSessionBatchManager.getCurrentBatch).toHaveBeenCalled()const mockBatch = mockSessionBatchManager.getCurrentBatch()@@ -1060,7 +1060,7 @@ describe('session-replay-pipeline', () => {createMessage(0, 3, 'session-3'),]- await runSessionReplayPipeline(pipeline, messages)+ await runSessionReplayPipeline(pipeline, messages, promiseScheduler)const mockBatch = mockSessionBatchManager.getCurrentBatch()expect(mockBatch.record).toHaveBeenCalledTimes(3)@@ -1088,7 +1088,7 @@ describe('session-replay-pipeline', () => {const messages = [createMessage(0, 1, 'session-1')]- const offsets = await runSessionReplayPipeline(pipeline, messages)+ const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)const mockBatch = mockSessionBatchManager.getCurrentBatch()expect(mockBatch.record).not.toHaveBeenCalled()@@ -1119,7 +1119,7 @@ describe('session-replay-pipeline', () => {const messages = [createMessage(0, 1, 'session-1', { token: 'invalid-token' })]- const offsets = await runSessionReplayPipeline(pipeline, messages)+ const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)const mockBatch = mockSessionBatchManager.getCurrentBatch()expect(mockBatch.record).not.toHaveBeenCalled()@@ -1146,7 +1146,7 @@ describe('session-replay-pipeline', () => {const messages = [createMessage(0, 1, 'session-1', { token: 'test-token' })]- await runSessionReplayPipeline(pipeline, messages)+ await runSessionReplayPipeline(pipeline, messages, promiseScheduler)// Verify parse time metric was registered and recordedconst parseTimeRecorder = topHog.sumRecorders.get('parse_time_ms_by_session_id')@@ -1177,7 +1177,7 @@ describe('session-replay-pipeline', () => {const messages = [createMessage(0, 1, 'session-1', { token: 'test-token' })]- await runSessionReplayPipeline(pipeline, messages)+ await runSessionReplayPipeline(pipeline, messages, promiseScheduler)// Verify message size metric was registered and recordedconst messageSizeRecorder = topHog.sumRecorders.get('message_size_by_session_id')@@ -1208,7 +1208,7 @@ describe('session-replay-pipeline', () => {const messages = [createMessage(0, 1, 'session-1', { token: 'test-token' })]- await runSessionReplayPipeline(pipeline, messages)+ await runSessionReplayPipeline(pipeline, messages, promiseScheduler)// Verify consume time metric was registered and recordedconst consumeTimeRecorder = topHog.sumRecorders.get('consume_time_ms_by_session_id')@@ -1243,7 +1243,7 @@ describe('session-replay-pipeline', () => {createMessage(0, 3, 'session-3', { token: 'token-1' }),]- await runSessionReplayPipeline(pipeline, messages)+ await runSessionReplayPipeline(pipeline, messages, promiseScheduler)// Verify all three messages were recorded for each metricconst parseTimeRecorder = topHog.sumRecorders.get('parse_time_ms_by_session_id')@@ -1291,7 +1291,7 @@ describe('session-replay-pipeline', () => {const messages = [createMessage(0, 1, 'session-1')]- await runSessionReplayPipeline(pipeline, messages)+ await runSessionReplayPipeline(pipeline, messages, promiseScheduler)// Metrics should not be recorded for dropped messages since they never reach the stepsconst parseTimeRecorder = topHog.sumRecorders.get('parse_time_ms_by_session_id')@@ -1353,7 +1353,7 @@ describe('session-replay-pipeline', () => {size: 100,}- await runSessionReplayPipeline(pipeline, [messageWithoutToken])+ await runSessionReplayPipeline(pipeline, [messageWithoutToken], promiseScheduler)// The parsed message should have token from Kafka headersconst messageSizeRecorder = topHog.sumRecorders.get('message_size_by_session_id')diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.tsindex d38d48bfbe4b..cbed355b8824 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts@@ -6,11 +6,12 @@ import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestionimport { PromiseScheduler } from '~/common/utils/promise-scheduler'import { createApplyEventRestrictionsStep, createParseHeadersStep } from '~/ingestion/common/steps/event-preprocessing'import { IngestionOverflowMode } from '~/ingestion/config'-import { BatchPipeline } from '~/ingestion/framework/batch-pipeline.interface'-import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'+import { BatchingContext, BatchingPipeline } from '~/ingestion/framework/batching-pipeline'+import { newBatchingPipeline } from '~/ingestion/framework/builders'import { TopHogRegistry, createTopHogWrapper, sum, timer } from '~/ingestion/framework/extensions/tophog'import { createBatch } from '~/ingestion/framework/helpers'import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'+import { ok } from '~/ingestion/framework/results'import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'import { SessionBatchManager } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-manager'import { SessionFilter } from '~/ingestion/pipelines/sessionreplay/sessions/session-filter'@@ -25,8 +26,10 @@ import { createLibVersionMonitorStep } from './lib-version-monitor-step'import { createParseMessageStep } from './parse-message-step'import { MessageContext } from './pipeline-types'import { createRecordSessionEventStep } from './record-session-event-step'+import { SessionBatchContext } from './session-batch-context'import { createMarkSeenStep } from './session-batch-mark-seen-step'import { createResolveRetentionStep } from './session-batch-resolve-retention-step'+import { createAttachSessionBatchStep } from './session-batch-step'import { createTrackAndGateStep } from './session-batch-track-and-gate-step'import { createResolveKeyStep } from './session-resolve-key-step'import { createTeamFilterStep } from './team-filter-step'@@ -41,6 +44,20 @@ export interface SessionReplayPipelineOutput {parsedMessage: ParsedMessageData}+/**+ * The session replay pipeline: a batching pipeline whose beforeBatch tags the current session batch+ * recorder onto every element ({@link SessionBatchContext}), so the steps fold into the recorder+ * they were fed with rather than reaching into shared batch state.+ */+export type SessionReplayPipeline = BatchingPipeline<+ SessionReplayPipelineInput,+ SessionReplayPipelineOutput,+ MessageContext,+ SessionBatchContext,+ MessageContext & BatchingContext,+ OverflowOutput+>+export interface SessionReplayPipelineConfig {outputs: IngestionOutputs<IngestionWarningsOutput | DlqOutput | OverflowOutput>eventIngestionRestrictionManager: EventIngestionRestrictionManager@@ -68,22 +85,15 @@ export interface SessionReplayPipelineConfig {/*** Creates the session replay pipeline.*- * The pipeline processes messages through these phases:+ * Each feed() is one batch: the beforeBatch hook tags the manager's current recorder onto every+ * element, and the per-message sub-pipeline processes messages through these phases:* 1. Restrictions - Parse headers and apply event ingestion restrictions (drop/overflow)* 2. Team Filter - Validate team ownership and enrich with team context* 3. Parse - Parse Kafka messages into structured session recording data (inside teamAware for warning handling)* 4. Version Monitor - Check library version and emit warnings for old versions- * 5. Record - Record parsed messages to session batches+ * 5. Record - Record parsed messages to the batch's recorder*/-export function createSessionReplayPipeline(- config: SessionReplayPipelineConfig-): BatchPipeline<- SessionReplayPipelineInput,- SessionReplayPipelineOutput,- MessageContext,- MessageContext,- OverflowOutput-> {+export function createSessionReplayPipeline(config: SessionReplayPipelineConfig): SessionReplayPipeline {const {outputs,eventIngestionRestrictionManager,@@ -107,117 +117,131 @@ export function createSessionReplayPipeline(const topHogWrapper = createTopHogWrapper(topHog)- const pipeline = newBatchPipelineBuilder<SessionReplayPipelineInput, MessageContext>()- .messageAware((b) =>- b- .sequentially((b) =>+ return newBatchingPipeline<+ SessionReplayPipelineInput,+ SessionReplayPipelineOutput,+ MessageContext,+ SessionBatchContext,+ MessageContext,+ OverflowOutput+ >(+ (beforeBatch) => beforeBatch.pipe(createAttachSessionBatchStep(sessionBatchManager)),+ (batch) =>+ batch+ .messageAware((b) =>b- // Parse headers and apply restrictions (drop/overflow)- .pipe(createParseHeadersStep())- .pipe(- createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {- overflowMode,- preservePartitionLocality: true, // Sessions must stay on the same partition- })+ .sequentially((b) =>+ b+ // Parse headers and apply restrictions (drop/overflow)+ .pipe(createParseHeadersStep())+ .pipe(+ createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {+ overflowMode,+ preservePartitionLocality: true, // Sessions must stay on the same partition+ })+ )+ // Validate the headers capture guarantees (DLQ if missing) and narrow the type+ .pipe(createValidateSessionReplayHeadersStep())+ // Validate team ownership and enrich with team context+ .pipe(createTeamFilterStep(teamService)))- // Validate the headers capture guarantees (DLQ if missing) and narrow the type- .pipe(createValidateSessionReplayHeadersStep())- // Validate team ownership and enrich with team context- .pipe(createTeamFilterStep(teamService))- )- // Resolve retention for the whole batch in one call, before the message is parsed and- // recorded — keyed on the (validated) session_id header. Sessions with unresolvable- // retention are dropped before any parse or write.- .gather()- .pipeBatch(createResolveRetentionStep(retentionService, sessionBatchManager), {- retry: { tries: 3, sleepMs: 100 },- })- // Track sessions and rate-limit new ones for the whole batch, tagging the survivors with- // isNewSession and dropping the blocked ones right here (they carry no key, so nothing- // downstream acts on them). Its own retry scope means a later key-resolution failure never- // re-runs the rate limiter and double-charges the budget.- .pipeBatch(createTrackAndGateStep(sessionTracker, sessionFilter), {- retry: { tries: 3, sleepMs: 100 },- })- // Resolve each session's encryption key. Grouped by session so it runs once per session- // (the cached keystore fans the key to its other messages) and concurrently across- // sessions, capped to bound KMS/DynamoDB fan-out. Per-session retry isolates a transient- // keystore blip to that one session. Deleted sessions are dropped here.- .concurrentlyPerGroup(- (element) => `${element.team.teamId}:${element.headers.session_id}`,- (group) =>- group.sequentially((b) =>- b.pipe(createResolveKeyStep(keyStore), {- retry: { name: 'resolve_session_key', tries: 3, sleepMs: 100 },- })- ),- { maxConcurrency: sessionKeyResolutionMaxConcurrency }- )- // Re-collect the per-session groups into one batch — both to mark the whole batch seen- // in a single Redis write and as the barrier that guarantees every key is resolved first.- .gather()- // Mark the surviving new sessions seen, now that every key is durably resolved.- .pipeBatch(createMarkSeenStep(sessionTracker))- // Map TeamForReplay.teamId to context.team.id for handleIngestionWarnings- .filterMap(- (element) => ({- result: element.result,- context: {- ...element.context,- team: { id: element.result.value.team.teamId },- },- }),- (b) =>- b- .teamAware((b) =>+ // Resolve retention for the whole batch in one call, before the message is parsed and+ // recorded — keyed on the (validated) session_id header. Sessions with unresolvable+ // retention are dropped before any parse or write.+ .gather()+ .pipeBatch(createResolveRetentionStep(retentionService), {+ retry: { tries: 3, sleepMs: 100 },+ })+ // Track sessions and rate-limit new ones for the whole batch, tagging the survivors with+ // isNewSession and dropping the blocked ones right here (they carry no key, so nothing+ // downstream acts on them). Its own retry scope means a later key-resolution failure never+ // re-runs the rate limiter and double-charges the budget.+ .pipeBatch(createTrackAndGateStep(sessionTracker, sessionFilter), {+ retry: { tries: 3, sleepMs: 100 },+ })+ // Resolve each session's encryption key. Grouped by session so it runs once per session+ // (the cached keystore fans the key to its other messages) and concurrently across+ // sessions, capped to bound KMS/DynamoDB fan-out. Per-session retry isolates a transient+ // keystore blip to that one session. Deleted sessions are dropped here.+ .concurrentlyPerGroup(+ (element) => `${element.team.teamId}:${element.headers.session_id}`,+ (group) =>+ group.sequentially((b) =>+ b.pipe(createResolveKeyStep(keyStore), {+ retry: { name: 'resolve_session_key', tries: 3, sleepMs: 100 },+ })+ ),+ { maxConcurrency: sessionKeyResolutionMaxConcurrency }+ )+ // Re-collect the per-session groups into one batch — both to mark the whole batch seen+ // in a single Redis write and as the barrier that guarantees every key is resolved first.+ .gather()+ // Mark the surviving new sessions seen, now that every key is durably resolved.+ .pipeBatch(createMarkSeenStep(sessionTracker))+ // Map TeamForReplay.teamId to context.team.id for handleIngestionWarnings+ .filterMap(+ (element) => ({+ result: element.result,+ context: {+ ...element.context,+ team: { id: element.result.value.team.teamId },+ },+ }),+ (b) =>b- .sequentially((b) =>+ .teamAware((b) =>b- // Parse message content- .pipe(- topHogWrapper(createParseMessageStep(), [- timer('parse_time_ms_by_session_id', (input) => ({- token: input.headers.token ?? 'unknown',- session_id: input.headers.session_id ?? 'unknown',- })),- ])- )- // Monitor library version and emit warnings for old versions- .pipe(createLibVersionMonitorStep())- .pipe(- topHogWrapper(- createRecordSessionEventStep({- sessionBatchManager,- isDebugLoggingEnabled,- }),- [- sum(- 'message_size_by_session_id',- (input) => ({- token: input.parsedMessage.token ?? 'unknown',- session_id: input.parsedMessage.session_id,+ .sequentially((b) =>+ b+ // Parse message content+ .pipe(+ topHogWrapper(createParseMessageStep(), [+ timer('parse_time_ms_by_session_id', (input) => ({+ token: input.headers.token ?? 'unknown',+ session_id: input.headers.session_id ?? 'unknown',+ })),+ ])+ )+ // Monitor library version and emit warnings for old versions+ .pipe(createLibVersionMonitorStep())+ .pipe(+ topHogWrapper(+ createRecordSessionEventStep({+ isDebugLoggingEnabled,}),- (input) => input.parsedMessage.metadata.rawSize- ),- timer('consume_time_ms_by_session_id', (input) => ({- token: input.parsedMessage.token ?? 'unknown',- session_id: input.parsedMessage.session_id,- })),- ]- )+ [+ sum(+ 'message_size_by_session_id',+ (input) => ({+ token: input.parsedMessage.token ?? 'unknown',+ session_id: input.parsedMessage.session_id,+ }),+ (input) => input.parsedMessage.metadata.rawSize+ ),+ timer('consume_time_ms_by_session_id', (input) => ({+ token: input.parsedMessage.token ?? 'unknown',+ session_id: input.parsedMessage.session_id,+ })),+ ]+ )+ ))+ .gather())- .gather()- )- .handleIngestionWarnings(outputs)+ .handleIngestionWarnings(outputs)+ ))- )- .handleResults(pipelineConfig)- .handleSideEffects(promiseScheduler, { await: false })- .gather()- .build()-- return pipeline+ .handleResults(pipelineConfig)+ .handleSideEffects(promiseScheduler, { await: false })+ .gather(),+ (afterBatch) =>+ 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 }+ )}/**@@ -232,16 +256,16 @@ export function createSessionReplayPipeline(** Relies on the pipeline draining the whole fed batch before it returns null, so every fed message* yields exactly one terminal result here.+ *+ * Element side effects (DLQ/overflow produces) are already scheduled inside the sub-pipeline, but+ * side effects returned by the batching pipeline's before/afterBatch hooks ride on each BatchResult.+ * They go onto the same scheduler here, so the consumer's pre-flush drain awaits them before any+ * offset commits — the hooks are pure today, but a driver must not silently drop them.*/export async function runSessionReplayPipeline(- pipeline: BatchPipeline<- SessionReplayPipelineInput,- SessionReplayPipelineOutput,- { message: Message },- { message: Message },- OverflowOutput- >,- messages: Message[]+ pipeline: SessionReplayPipeline,+ messages: Message[],+ promiseScheduler: PromiseScheduler): Promise<Map<number, number>> {const maxOffsetByPartition = new Map<number, number>()if (messages.length === 0) {@@ -249,18 +273,26 @@ export async function runSessionReplayPipeline(}const batch = createBatch(messages.map((message) => ({ message })))- pipeline.feed(batch)+ // The consumer drains each batch fully before feeding the next and the hooks always succeed,+ // so a rejected feed can only be a framework invariant violation.+ const feedResult = await pipeline.feed(batch)+ if (!feedResult.ok) {+ throw new Error(`session replay pipeline rejected feed: ${feedResult.kind} (${feedResult.reason})`)+ }- let results = await pipeline.next()- while (results !== null) {- for (const { context } of results) {+ let batchResult = await pipeline.next()+ while (batchResult !== null) {+ for (const sideEffect of batchResult.sideEffects ?? []) {+ void promiseScheduler.schedule(sideEffect)+ }+ for (const { context } of batchResult.elements) {const { partition, offset } = context.messageconst current = maxOffsetByPartition.get(partition)if (current === undefined || offset > current) {maxOffsetByPartition.set(partition, offset)}}- results = await pipeline.next()+ batchResult = await pipeline.next()}return maxOffsetByPartition