: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
feat(replay): resolve retention and validate headers before recording (#67467)
Paweł Ledwońe977d461e34c
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/config.tsindex 218d5041f1bc..4d304b206434 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/config.ts@@ -69,6 +69,9 @@ export type SessionRecordingConfig = {SESSION_RECORDING_V2_S3_ACCESS_KEY_ID: stringSESSION_RECORDING_V2_S3_SECRET_ACCESS_KEY: stringSESSION_RECORDING_V2_S3_TIMEOUT_MS: number+ // Per-command timeout on the session-recording Redis client, so a slow/unavailable Redis fails+ // fast instead of blocking the pipeline; the retention service falls back to the team service.+ SESSION_RECORDING_REDIS_TIMEOUT_MS: numberSESSION_RECORDING_V2_CONSOLE_LOG_STORE_SYNC_BATCH_LIMIT: numberSESSION_RECORDING_V2_MAX_EVENTS_PER_SESSION_PER_BATCH: numberSESSION_RECORDING_NEW_SESSION_BUCKET_CAPACITY: number@@ -128,6 +131,7 @@ export function getDefaultSessionRecordingConfig(): SessionRecordingConfig {SESSION_RECORDING_V2_S3_ACCESS_KEY_ID: 'any',SESSION_RECORDING_V2_S3_SECRET_ACCESS_KEY: 'any',SESSION_RECORDING_V2_S3_TIMEOUT_MS: isDevEnv() ? 120000 : 30000,+ SESSION_RECORDING_REDIS_TIMEOUT_MS: 200,SESSION_RECORDING_V2_CONSOLE_LOG_STORE_SYNC_BATCH_LIMIT: 1000,SESSION_RECORDING_V2_MAX_EVENTS_PER_SESSION_PER_BATCH: Number.MAX_SAFE_INTEGER,SESSION_RECORDING_NEW_SESSION_BUCKET_CAPACITY: 3000,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.tsindex f48b02ea52c0..1e82bef18de0 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts@@ -98,6 +98,7 @@ export class SessionRecordingIngester {private readonly redisPool: RedisPoolprivate readonly restrictionRedisPool: RedisPoolprivate readonly teamService: TeamService+ private readonly retentionService: RetentionServiceprivate readonly fileStorage: SessionBatchFileStorageprivate readonly eventIngestionRestrictionManagerComponent: EventIngestionRestrictionManagerComponentprivate eventIngestionRestrictionManager!: EventIngestionRestrictionManager@@ -173,7 +174,7 @@ export class SessionRecordingIngester {{ pipeline: 'session_recordings' })- const retentionService = new RetentionService(this.redisPool, this.teamService)+ this.retentionService = new RetentionService(this.redisPool, this.teamService)const offsetManager = new KafkaOffsetManager(this.commitOffsets.bind(this), this.topic)this.createPipeline = collaborators.createPipeline ?? createSessionReplayPipeline@@ -193,8 +194,7 @@ export class SessionRecordingIngester {s3Client,this.config.SESSION_RECORDING_V2_S3_BUCKET,this.config.SESSION_RECORDING_V2_S3_PREFIX,- this.config.SESSION_RECORDING_V2_S3_TIMEOUT_MS,- retentionService+ this.config.SESSION_RECORDING_V2_S3_TIMEOUT_MS): new BlackholeSessionBatchFileStorage())@@ -215,7 +215,7 @@ export class SessionRecordingIngester {this.keyStore =collaborators.keyStore ??new MemoryCachedKeyStore(- getKeyStore(retentionService, region, {+ getKeyStore(region, {kmsEndpoint: config.SESSION_RECORDING_KMS_ENDPOINT,dynamoDBEndpoint: config.SESSION_RECORDING_DYNAMODB_ENDPOINT,})@@ -317,6 +317,7 @@ export class SessionRecordingIngester {overflowEnabled: this.overflowEnabled(),promiseScheduler: this.promiseScheduler,teamService: this.teamService,+ retentionService: this.retentionService,topHog: this.topHog,sessionBatchManager: this.sessionBatchManager,isDebugLoggingEnabled: this.isDebugLoggingEnabled,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/kafka/types.ts b/nodejs/src/ingestion/pipelines/sessionreplay/kafka/types.tsindex 830291515e4f..438cd471c036 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/kafka/types.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/kafka/types.ts@@ -1,5 +1,4 @@import { DateTime } from 'luxon'-import { MessageHeader } from 'node-rdkafka'import { z } from 'zod'const dateTimeSchema = z.custom<DateTime>((val) => val instanceof DateTime)@@ -62,7 +61,6 @@ export const ParsedMessageDataSchema = z.object({eventsRange: EventsRangeSchema,snapshot_source: z.string().nullable(),snapshot_library: z.string().nullable(),- headers: z.array(z.custom<MessageHeader>()).optional(),metadata: MessageMetadataSchema,})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/lib-version-monitor-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/lib-version-monitor-step.test.tsindex e8632bf2656c..e657cf63817d 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/lib-version-monitor-step.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/lib-version-monitor-step.test.ts@@ -1,37 +1,25 @@-import { DateTime } from 'luxon'-import { PipelineResultType } from '~/ingestion/framework/results'-import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'import { LibVersionMonitorStepInput, createLibVersionMonitorStep } from './lib-version-monitor-step'describe('createLibVersionMonitorStep', () => {- const createParsedMessage = (headers: Record<string, string>[] = []): ParsedMessageData => ({- metadata: {+ const createInput = (headers: Record<string, string>[] = []): LibVersionMonitorStepInput => ({+ message: {partition: 0,topic: 'test-topic',offset: 1,timestamp: 1234567890,- rawSize: 100,+ size: 100,+ value: Buffer.from(''),+ key: null,+ headers: headers.map((h) => {+ const result: Record<string, Buffer> = {}+ for (const [key, value] of Object.entries(h)) {+ result[key] = Buffer.from(value)+ }+ return result+ }),},- headers: headers.map((h) => {- const result: Record<string, Buffer> = {}- for (const [key, value] of Object.entries(h)) {- result[key] = Buffer.from(value)- }- return result- }),- distinct_id: 'distinct_id',- session_id: 'session-1',- token: 'test-token',- eventsByWindowId: { window1: [] },- eventsRange: { start: DateTime.fromMillis(0), end: DateTime.fromMillis(0) },- snapshot_source: null,- snapshot_library: null,- })-- const createInput = (headers: Record<string, string>[] = []): LibVersionMonitorStepInput => ({- parsedMessage: createParsedMessage(headers),})it('should emit warning for old lib version (< 1.75.0)', async () => {@@ -115,7 +103,7 @@ describe('createLibVersionMonitorStep', () => {expect(result.type).toBe(PipelineResultType.OK)if (result.type === PipelineResultType.OK) {- expect(result.value.parsedMessage).toBe(input.parsedMessage)+ expect(result.value.message).toBe(input.message)}})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/lib-version-monitor-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/lib-version-monitor-step.tsindex 3e2e67ee5a21..6c8b3d2bb990 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/lib-version-monitor-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/lib-version-monitor-step.ts@@ -1,10 +1,11 @@+import { Message } from 'node-rdkafka'+import { PipelineWarning } from '~/ingestion/framework/pipeline.interface'import { ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'-import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'export interface LibVersionMonitorStepInput {- parsedMessage: ParsedMessageData+ message: Message}/**@@ -16,9 +17,9 @@ export interface LibVersionMonitorStepInput {*/export function createLibVersionMonitorStep<T extends LibVersionMonitorStepInput>(): ProcessingStep<T, T> {return function libVersionMonitorStep(input) {- const { parsedMessage } = input+ const { message } = input- const libVersion = readLibVersionFromHeaders(parsedMessage.headers)+ const libVersion = readLibVersionFromHeaders(message.headers)const parsedVersion = parseVersion(libVersion)if (parsedVersion && parsedVersion.major === 1 && parsedVersion.minor < 75) {@@ -38,7 +39,7 @@ export function createLibVersionMonitorStep<T extends LibVersionMonitorStepInput}}-function readLibVersionFromHeaders(headers: ParsedMessageData['headers']): string | undefined {+function readLibVersionFromHeaders(headers: Message['headers']): string | undefined {const libVersionHeader = headers?.find((header) => header['lib_version'])?.['lib_version']return typeof libVersionHeader === 'string' ? libVersionHeader : libVersionHeader?.toString()}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 4c1ad6c3d0db..311d0f0076f7 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@@ -12,6 +12,11 @@ import { runSessionReplayPipeline } from '~/ingestion/pipelines/sessionreplay'import { defaultAllowLists } from '~/ingestion/pipelines/sessionreplay/anonymize/default-dict'import { SessionBatchManager } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-manager'import { SessionBatchRecorder } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder'+import {+ RetentionResolution,+ RetentionService,+} from '~/ingestion/pipelines/sessionreplay/shared/retention/retention-service'+import { SessionMap, SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'import { TeamService } from '~/ingestion/pipelines/sessionreplay/shared/teams/team-service'import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'@@ -45,6 +50,17 @@ describe('ml-mirror-pipeline', () => {IngestionOutputs<typeof DLQ_OUTPUT | typeof OVERFLOW_OUTPUT | typeof INGESTION_WARNINGS_OUTPUT>>const scrubContext = { allow: defaultAllowLists() }++ // Resolves every session to 30d so messages flow through to recording.+ const retentionService = {+ resolveSessionRetentions: jest.fn().mockImplementation((sessions: SessionSet) => {+ const resolutions = new SessionMap<RetentionResolution>()+ for (const s of sessions) {+ resolutions.set(s.teamId, s.sessionId, { resolved: true, retentionPeriod: '30d' })+ }+ return Promise.resolve(resolutions)+ }),+ } as unknown as RetentionServiceconst now = DateTime.now()const team = (aiTrainingOptedIn: boolean): TeamForReplay => ({@@ -58,7 +74,10 @@ describe('ml-mirror-pipeline', () => {outputs = createMockIngestionOutputs()recordMock = jest.fn().mockResolvedValue(undefined)- const recorder = { record: recordMock } as unknown as jest.Mocked<SessionBatchRecorder>+ const recorder = {+ record: recordMock,+ getRetention: jest.fn().mockReturnValue(undefined),+ } as unknown as jest.Mocked<SessionBatchRecorder>mockSessionBatchManager = {getCurrentBatch: jest.fn().mockReturnValue(recorder),shouldFlush: jest.fn().mockReturnValue(false),@@ -88,6 +107,7 @@ describe('ml-mirror-pipeline', () => {overflowEnabled: false,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled: () => false,@@ -120,7 +140,11 @@ describe('ml-mirror-pipeline', () => {value: Buffer.from(payload),key: Buffer.from('k'),timestamp: Date.now(),- headers: [{ token: Buffer.from('test-token') }, { session_id: Buffer.from(sessionId) }],+ headers: [+ { token: Buffer.from('test-token') },+ { session_id: Buffer.from(sessionId) },+ { distinct_id: Buffer.from('user-123') },+ ],size: payload.length,} as unknown as Message}@@ -163,7 +187,11 @@ describe('ml-mirror-pipeline', () => {value: Buffer.from(payload),key: Buffer.from('k'),timestamp: Date.now(),- headers: [{ token: Buffer.from('test-token') }, { session_id: Buffer.from(sessionId) }],+ headers: [+ { token: Buffer.from('test-token') },+ { session_id: Buffer.from(sessionId) },+ { distinct_id: Buffer.from('user-123') },+ ],size: payload.length,} as unknown as Message}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 630e77c0c36b..d466ef99665c 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@@ -17,7 +17,9 @@ import { createAnonymizeStep } from '~/ingestion/pipelines/sessionreplay/anonymiimport { ScrubContext } from '~/ingestion/pipelines/sessionreplay/anonymize/config'import { createParseMessageStep } from '~/ingestion/pipelines/sessionreplay/parse-message-step'import { createRecordSessionEventStep } from '~/ingestion/pipelines/sessionreplay/record-session-event-step'+import { createResolveRetentionStep } from '~/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step'import { createTeamFilterStep } from '~/ingestion/pipelines/sessionreplay/team-filter-step'+import { createValidateSessionReplayHeadersStep } from '~/ingestion/pipelines/sessionreplay/validate-headers-step'export type MlMirrorReplayPipelineConfig = SessionReplayPipelineConfig & {/** Shared, immutable scrub context (allow lists + tunables). */@@ -39,6 +41,7 @@ export function createMlMirrorReplayPipeline(overflowEnabled,promiseScheduler,teamService,+ retentionService,topHog,sessionBatchManager,isDebugLoggingEnabled,@@ -60,10 +63,18 @@ export function createMlMirrorReplayPipeline(preservePartitionLocality: true,}))+ .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()+ .pipeBatchWithRetry(createResolveRetentionStep(retentionService, sessionBatchManager), {+ tries: 3,+ sleepMs: 100,+ }).filterMap((element) => ({result: element.result,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.test.tsindex eb991293af8e..d64d9d7b8178 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.test.ts@@ -5,6 +5,7 @@ import { gzip } from 'zlib'import { PipelineResultType } from '~/ingestion/framework/results'import { ParseMessageStepInput, createParseMessageStep } from './parse-message-step'+import { SessionReplayHeaders } from './validate-headers-step'const compressWithGzip = promisify(gzip)@@ -82,15 +83,23 @@ describe('createParseMessageStep', () => {return { ...message, ...overrides }}+ // The validate step guarantees these before parse; they must mirror the message body's+ // session_id/distinct_id or parse DLQs the message as inconsistent.+ function createReplayHeaders(overrides: Partial<SessionReplayHeaders> = {}): SessionReplayHeaders {+ return { token: 'test-token', session_id: 'session-1', distinct_id: 'user-123', ...overrides }+ }+function createInput(partition: number,offset: number,payload?: string,headers?: Record<string, string>,- overrides?: Partial<Message>+ overrides?: Partial<Message>,+ replayHeaders: SessionReplayHeaders = createReplayHeaders()): ParseMessageStepInput {return {message: createMessage(partition, offset, payload, headers, overrides),+ headers: replayHeaders,}}@@ -205,7 +214,7 @@ describe('createParseMessageStep', () => {size: gzippedPayload.length,}- const result = await step({ message })+ const result = await step({ message, headers: createReplayHeaders({ session_id: 'session-gzip' }) })expect(result.type).toBe(PipelineResultType.OK)if (result.type === PipelineResultType.OK) {@@ -213,10 +222,10 @@ describe('createParseMessageStep', () => {}})- it('should extract token from headers', async () => {+ it('should set token from the validated session replay headers', async () => {const step = createParseMessageStep()const payload = createValidSnapshotPayload('session-1')- const input = createInput(0, 1, payload, { token: 'my-team-token' })+ const input = createInput(0, 1, payload, undefined, undefined, createReplayHeaders({ token: 'my-team-token' }))const result = await step(input)@@ -226,16 +235,36 @@ describe('createParseMessageStep', () => {}})- it('should set token to null when not in headers', async () => {+ it('DLQs when the header session_id does not match the message body', async () => {const step = createParseMessageStep()const payload = createValidSnapshotPayload('session-1')- const input = createInput(0, 1, payload)+ const input = createInput(0, 1, payload, undefined, undefined, createReplayHeaders({ session_id: 'session-2' }))const result = await step(input)- expect(result.type).toBe(PipelineResultType.OK)- if (result.type === PipelineResultType.OK) {- expect(result.value.parsedMessage.token).toBeNull()+ expect(result.type).toBe(PipelineResultType.DLQ)+ if (result.type === PipelineResultType.DLQ) {+ expect(result.reason).toBe('session_id_header_body_mismatch')+ }+ })++ it('DLQs when the header distinct_id does not match the message body', async () => {+ const step = createParseMessageStep()+ const payload = createValidSnapshotPayload('session-1') // body distinct_id is user-123+ const input = createInput(+ 0,+ 1,+ payload,+ undefined,+ undefined,+ createReplayHeaders({ distinct_id: 'someone-else' })+ )++ const result = await step(input)++ expect(result.type).toBe(PipelineResultType.DLQ)+ if (result.type === PipelineResultType.DLQ) {+ expect(result.reason).toBe('distinct_id_header_body_mismatch')}})@@ -298,7 +327,7 @@ describe('createParseMessageStep', () => {size: 5,}- const result = await step({ message })+ const result = await step({ message, headers: createReplayHeaders() })expect(result.type).toBe(PipelineResultType.DLQ)if (result.type === PipelineResultType.DLQ) {@@ -547,7 +576,15 @@ describe('createParseMessageStep', () => {],distinctId: 'user-123',})- const input = createInput(0, 1, payload)+ // The header id is already normalized by the validate step; the body carries the raw id.+ const input = createInput(+ 0,+ 1,+ payload,+ undefined,+ undefined,+ createReplayHeaders({ session_id: expectedSessionId })+ )const result = await step(input)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.tsindex eb4806f00424..abb40f391cd4 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.ts@@ -15,6 +15,8 @@ import {} from '~/ingestion/pipelines/sessionreplay/kafka/types'import { SessionRecordingIngesterMetrics } from '~/ingestion/pipelines/sessionreplay/metrics'+import { SessionReplayHeaders } from './validate-headers-step'+const lz4: { decodeBlock(input: Buffer, output: Buffer): number } = require('lz4')const MESSAGE_TIMESTAMP_DIFF_THRESHOLD_DAYS = 7@@ -22,6 +24,7 @@ const GZIP_HEADER = Uint8Array.from([0x1f, 0x8b, 0x08, 0x00])export interface ParseMessageStepInput {message: Message+ headers: SessionReplayHeaders}export interface ParseMessageStepOutput {@@ -187,8 +190,16 @@ export function createParseMessageStep<T extends ParseMessageStepInput>(): Proce)}- const tokenHeader = message.headers?.find((header: MessageHeader) => header.token)?.token- const token = typeof tokenHeader === 'string' ? tokenHeader : tokenHeader?.toString()+ // session_id and distinct_id are carried both in the headers (set by capture) and in the+ // message body; they must agree — a mismatch means the message is corrupt or mis-routed.+ // headers.session_id is already normalized by the validate step, matching the body's.+ const { headers } = input+ if (headers.session_id !== sessionId) {+ return dlq('session_id_header_body_mismatch')+ }+ if (headers.distinct_id !== messageResult.data.distinct_id) {+ return dlq('distinct_id_header_body_mismatch')+ }const parsedMessage: ParsedMessageData = {metadata: {@@ -198,10 +209,9 @@ export function createParseMessageStep<T extends ParseMessageStepInput>(): Proceoffset: message.offset,timestamp: message.timestamp,},- headers: message.headers,distinct_id: messageResult.data.distinct_id,session_id: sessionId,- token: token ?? null,+ token: headers.token,eventsByWindowId: {[$window_id ?? '']: validEvents,},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 f80a27425459..400c8dbb2117 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@@ -34,7 +34,6 @@ describe('createRecordSessionEventStep', () => {timestamp: 1234567890,rawSize: 100,},- headers: [],distinct_id: 'user-123',session_id: 'session-456',token: 'test-token',@@ -51,6 +50,7 @@ describe('createRecordSessionEventStep', () => {): RecordSessionEventStepInput => ({team,parsedMessage: createParsedMessage(overrides),+ retentionPeriod: '30d',})beforeEach(() => {@@ -76,10 +76,13 @@ describe('createRecordSessionEventStep', () => {expect(mockSessionBatchManager.getCurrentBatch).toHaveBeenCalledTimes(1)expect(mockBatchRecorder.record).toHaveBeenCalledTimes(1)- expect(mockBatchRecorder.record).toHaveBeenCalledWith({- team: defaultTeam,- message: input.parsedMessage,- })+ expect(mockBatchRecorder.record).toHaveBeenCalledWith(+ {+ team: defaultTeam,+ message: input.parsedMessage,+ },+ '30d'+ )})it('should return ok result with input preserved', async () => {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.tsindex 0669ae8361f2..05abfd824761 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.ts@@ -4,12 +4,14 @@ 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 { RetentionPeriod } from '~/ingestion/pipelines/sessionreplay/shared/constants'import { MessageWithTeam, TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'import { ValueMatcher } from '~/types'export interface RecordSessionEventStepInput {team: TeamForReplayparsedMessage: ParsedMessageData+ retentionPeriod: RetentionPeriod}export interface RecordSessionEventStepConfig {@@ -31,7 +33,7 @@ export function createRecordSessionEventStep<T extends RecordSessionEventStepInpconst { sessionBatchManager, isDebugLoggingEnabled } = configreturn async function recordSessionEventStep(input) {- const { team, parsedMessage } = input+ const { team, parsedMessage, retentionPeriod } = input// Reset revoked sessions counter once we're consumingSessionRecordingIngesterMetrics.resetSessionsRevoked()@@ -57,7 +59,7 @@ export function createRecordSessionEventStep<T extends RecordSessionEventStepInp// Record to the session batchconst batch = sessionBatchManager.getCurrentBatch()const messageWithTeam: MessageWithTeam = { team, message: parsedMessage }- await batch.record(messageWithTeam)+ await batch.record(messageWithTeam, retentionPeriod)return ok(input)}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.tsnew file mode 100644index 000000000000..0d41d4e023f3--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.test.ts@@ -0,0 +1,144 @@+import { PipelineResultType, isOkResult } from '~/ingestion/framework/results'+import {+ RetentionResolution,+ RetentionService,+} from '~/ingestion/pipelines/sessionreplay/shared/retention/retention-service'+import { SessionMap, SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'+import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'++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'+import { SessionReplayHeaders } from './validate-headers-step'++jest.mock('~/common/utils/logger', () => ({ logger: { warn: jest.fn() } }))+jest.mock('./sessions/metrics', () => ({+ SessionBatchMetrics: { incrementSessionsDroppedMissingRetention: jest.fn() },+}))++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).+ const element = (+ teamId: number,+ sessionId: string,+ partition = 0,+ offset = 0+ ): { message: { partition: number; offset: number }; team: TeamForReplay; headers: SessionReplayHeaders } =>+ ({+ 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+ }++ const createStep = () =>+ createResolveRetentionStep(mockRetentionService, mockSessionBatchManager as unknown as SessionBatchManager)++ beforeEach(() => {+ jest.clearAllMocks()+ mockRetentionService = {+ resolveSessionRetentions: jest.fn().mockResolvedValue(new SessionMap<RetentionResolution>()),+ } as unknown as jest.Mocked<RetentionService>+ // Default: no session is already in the batch, so everything is resolved via the service.+ 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 () => {+ mockRetentionService.resolveSessionRetentions.mockResolvedValue(+ new SessionMap<RetentionResolution>()+ .set(1, 'a', { resolved: true, retentionPeriod: '30d' })+ .set(2, 'b', { resolved: true, retentionPeriod: '1y' })+ )+ const step = createStep()++ const results = await step([element(1, 'a'), element(2, 'b')])++ expect(mockRetentionService.resolveSessionRetentions).toHaveBeenCalledTimes(1)+ expect(mockRetentionService.resolveSessionRetentions).toHaveBeenCalledWith(+ new SessionSet().add(1, 'a').add(2, 'b')+ )+ expect(results.map((r) => (isOkResult(r) ? r.value.retentionPeriod : null))).toEqual(['30d', '1y'])+ expect(SessionBatchMetrics.incrementSessionsDroppedMissingRetention).not.toHaveBeenCalled()+ })++ it('collapses a repeated session into a single resolve, fanned back out to every message', async () => {+ mockRetentionService.resolveSessionRetentions.mockResolvedValue(+ new SessionMap<RetentionResolution>().set(1, 'a', { resolved: true, retentionPeriod: '30d' })+ )+ const step = createStep()++ const results = await step([element(1, 'a'), element(1, 'a'), element(1, 'a')])++ // The three copies dedupe to one session before the service is asked.+ expect(mockRetentionService.resolveSessionRetentions).toHaveBeenCalledWith(new SessionSet().add(1, 'a'))+ expect(results.map((r) => (isOkResult(r) ? r.value.retentionPeriod : null))).toEqual(['30d', '30d', '30d'])+ })++ it('reuses retention already held in the batch and only resolves the unseen sessions', async () => {+ // Session 'a' (team 1) is already in the batch; 'b' (team 2) is not.+ mockBatch.getRetention.mockImplementation((teamId: number) => (teamId === 1 ? '90d' : undefined))+ mockRetentionService.resolveSessionRetentions.mockResolvedValue(+ new SessionMap<RetentionResolution>().set(2, 'b', { resolved: true, retentionPeriod: '1y' })+ )+ const step = createStep()++ const results = await step([element(1, 'a'), element(2, 'b')])++ // Only the unseen session is sent to the service.+ expect(mockRetentionService.resolveSessionRetentions).toHaveBeenCalledWith(new SessionSet().add(2, 'b'))+ expect(results.map((r) => (isOkResult(r) ? r.value.retentionPeriod : null))).toEqual(['90d', '1y'])+ })++ it('sends nothing to the service when every session is already in the batch', async () => {+ mockBatch.getRetention.mockReturnValue('30d')+ const step = createStep()++ const results = await step([element(1, 'a'), element(2, 'b')])++ // Everything came from the batch, so the resolve set is empty (the service no-ops on it).+ expect(mockRetentionService.resolveSessionRetentions).toHaveBeenCalledWith(new SessionSet())+ expect(results.map((r) => (isOkResult(r) ? r.value.retentionPeriod : null))).toEqual(['30d', '30d'])+ })++ it('drops an unresolvable session and keeps the rest', async () => {+ mockRetentionService.resolveSessionRetentions.mockResolvedValue(+ new SessionMap<RetentionResolution>()+ .set(999, 'gone', { resolved: false })+ .set(2, 'ok', { resolved: true, retentionPeriod: '90d' })+ )+ const step = createStep()++ const results = await step([element(999, 'gone', 4, 42), element(2, 'ok')])++ expect(mockRetentionService.resolveSessionRetentions).toHaveBeenCalledWith(+ new SessionSet().add(999, 'gone').add(2, 'ok')+ )+ // The unresolvable session becomes a DROP; its Kafka offset is tracked downstream by the+ // single offset-tracking stage in the runner, not here.+ expect(results[0].type).toBe(PipelineResultType.DROP)+ expect(isOkResult(results[1]) ? results[1].value.retentionPeriod : null).toBe('90d')+ expect(SessionBatchMetrics.incrementSessionsDroppedMissingRetention).toHaveBeenCalledTimes(1)+ })++ it('propagates a transient failure so the retry wrapper can retry the whole step', async () => {+ mockRetentionService.resolveSessionRetentions.mockRejectedValue(new Error('Redis connection lost'))+ const step = createStep()++ await expect(step([element(1, 'a')])).rejects.toThrow('Redis connection lost')+ expect(mockRetentionService.resolveSessionRetentions).toHaveBeenCalledWith(new SessionSet().add(1, 'a'))+ expect(SessionBatchMetrics.incrementSessionsDroppedMissingRetention).not.toHaveBeenCalled()+ })+})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.tsnew file mode 100644index 000000000000..e812510b41a9--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.ts@@ -0,0 +1,66 @@+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'+import { RetentionPeriod } from '~/ingestion/pipelines/sessionreplay/shared/constants'+import { RetentionService } from '~/ingestion/pipelines/sessionreplay/shared/retention/retention-service'+import { SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'+import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'++import { SessionBatchMetrics } from './sessions/metrics'+import { SessionBatchManager } from './sessions/session-batch-manager'+import { SessionReplayHeaders } from './validate-headers-step'++/**+ * Record-phase batch step: resolve per-session retention for the whole batch and attach it to each+ * element, before the message is parsed and recorded — so retention is resolved off the S3 write+ * path, and a session bound for the wrong retention is never parsed or written.+ *+ * A session already held in the current (unflushed) batch reuses the retention resolved for it+ * earlier; only the rest are resolved via the retention service (batched Redis MGET + a deduped+ * team service fallback). Keys on the `session_id` header, which {@link createValidateSessionReplayHeadersStep}+ * guarantees is present. A session whose retention can't be resolved because its team is unknown or+ * deleted is dropped; a corrupt/invalid stored value instead throws (crashes) rather than recording+ * against a wrong retention. A transient failure (e.g. Redis) is thrown by the service so the+ * pipeline's retry wrapper can re-run the step. A dropped message still commits its offset — the+ * drop result flows out of the pipeline carrying its source message, so the single offset-tracking+ * 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 }> {+ 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))+ const toResolve = new SessionSet()+ values.forEach((value, index) => {+ if (batchRetentions[index] === undefined) {+ toResolve.add(value.team.teamId, value.headers.session_id)+ }+ })+ const resolutions = await retentionService.resolveSessionRetentions(toResolve)++ return values.map((value, index) => {+ const cached = batchRetentions[index]+ if (cached !== undefined) {+ return ok({ ...value, retentionPeriod: cached })+ }+ const resolution = resolutions.get(value.team.teamId, value.headers.session_id)!+ if (resolution.resolved) {+ return ok({ ...value, retentionPeriod: resolution.retentionPeriod })+ }+ SessionBatchMetrics.incrementSessionsDroppedMissingRetention()+ logger.warn('🔁', 'session_replay_retention_unresolved_dropping_session', {+ sessionId: value.headers.session_id,+ teamId: value.team.teamId,+ })+ return drop('retention_unresolved')+ })+ }+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.tsindex d8ee1fa6dd6a..e167f731caf9 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts@@ -11,6 +11,11 @@ import { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'import { drop, ok, redirect } from '~/ingestion/framework/results'import { SessionBatchManager } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-manager'import { SessionBatchRecorder } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder'+import {+ RetentionResolution,+ RetentionService,+} from '~/ingestion/pipelines/sessionreplay/shared/retention/retention-service'+import { SessionMap, SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'import { TeamService } from '~/ingestion/pipelines/sessionreplay/shared/teams/team-service'import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'@@ -25,6 +30,7 @@ jest.mock('~/ingestion/common/steps/event-preprocessing', () => ({function createMockSessionBatchManager(): jest.Mocked<SessionBatchManager> {const mockBatchRecorder = {record: jest.fn().mockResolvedValue(undefined),+ getRetention: jest.fn().mockReturnValue(undefined),} as unknown as jest.Mocked<SessionBatchRecorder>return {@@ -88,6 +94,17 @@ describe('session-replay-pipeline', () => {// Debug logging disabled by default in testsconst isDebugLoggingEnabled = () => false+ // Resolves every session to 30d so messages flow through to recording.+ const retentionService = {+ resolveSessionRetentions: jest.fn().mockImplementation((sessions: SessionSet) => {+ const resolutions = new SessionMap<RetentionResolution>()+ for (const s of sessions) {+ resolutions.set(s.teamId, s.sessionId, { resolved: true, retentionPeriod: '30d' })+ }+ return Promise.resolve(resolutions)+ }),+ } as unknown as RetentionService+const defaultTeam: TeamForReplay = {teamId: 1,consoleLogIngestionEnabled: false,@@ -183,11 +200,14 @@ describe('session-replay-pipeline', () => {headers?: Record<string, string>): Message {const actualSessionId = sessionId ?? `session-${offset}`- // Default to including token and session_id headers since they're required for metrics+ // Default the headers the validate step requires; session_id/distinct_id must mirror the body.const headersWithDefaults = headers ?? { token: 'test-token' }if (!headersWithDefaults.session_id) {headersWithDefaults.session_id = actualSessionId}+ if (!headersWithDefaults.distinct_id) {+ headersWithDefaults.distinct_id = 'user-123'+ }const kafkaHeaders = Object.entries(headersWithDefaults).map(([key, value]) => ({[key]: Buffer.from(value),}))@@ -217,6 +237,9 @@ describe('session-replay-pipeline', () => {if (!headersWithDefaults.session_id) {headersWithDefaults.session_id = sessionId}+ if (!headersWithDefaults.distinct_id) {+ headersWithDefaults.distinct_id = 'user-123'+ }const kafkaHeaders = Object.entries(headersWithDefaults).map(([key, value]) => ({[key]: Buffer.from(value),}))@@ -250,6 +273,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -260,6 +284,7 @@ describe('session-replay-pipeline', () => {const offsets = await runSessionReplayPipeline(pipeline, messages)expect(recordedSessionIds()).toEqual(['session-1', 'session-2'])+ // Highest offset reached on the partition is tracked.expect(offsets).toEqual(new Map([[0, 2]]))})@@ -279,6 +304,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -314,6 +340,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -340,6 +367,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -373,6 +401,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -422,6 +451,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -453,6 +483,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -480,6 +511,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -523,6 +555,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -542,8 +575,13 @@ describe('session-replay-pipeline', () => {token: 'team-token-123',distinctId: 'user-456',session_id: 'session-1',+ distinct_id: 'user-123',+ })+ expect(capturedHeaders[1]).toEqual({+ token: 'team-token-789',+ session_id: 'session-2',+ distinct_id: 'user-123',})- expect(capturedHeaders[1]).toEqual({ token: 'team-token-789', session_id: 'session-2' })})it('processes large batch with all messages passing through', async () => {@@ -553,6 +591,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -591,6 +630,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: teamServiceThatDropsSecond,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -616,6 +656,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -638,6 +679,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -675,6 +717,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -695,6 +738,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -715,6 +759,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -751,6 +796,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -769,7 +815,8 @@ describe('session-replay-pipeline', () => {message: expect.objectContaining({session_id: 'session-1',}),- })+ }),+ '30d')})@@ -780,6 +827,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -807,6 +855,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -833,6 +882,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: teamServiceThatReturnsNull,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -855,6 +905,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -881,6 +932,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -907,6 +959,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -933,6 +986,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -980,6 +1034,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,@@ -1010,8 +1065,13 @@ describe('session-replay-pipeline', () => {// Override parse headers to not include token in parsed headers, but still have it in message headersmockCreateParseHeadersStep.mockReturnValue((input: { message: Message; headers?: Record<string, string> }) => {- // Return empty headers (no token)- return Promise.resolve(ok({ ...input, headers: { token: 'test-token' } }))+ // session_id/distinct_id must be present (validate) and mirror the body (parse consistency check)+ return Promise.resolve(+ ok({+ ...input,+ headers: { token: 'test-token', session_id: 'session-1', distinct_id: 'user-123' },+ })+ )})@@ -1021,6 +1081,7 @@ describe('session-replay-pipeline', () => {overflowEnabled: true,promiseScheduler,teamService: mockTeamService,+ retentionService,topHog,sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.tsindex 0cdc3d126c36..bb7951450c6d 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts@@ -12,6 +12,7 @@ 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'+import { RetentionService } from '~/ingestion/pipelines/sessionreplay/shared/retention/retention-service'import { TeamService } from '~/ingestion/pipelines/sessionreplay/shared/teams/team-service'import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'import { ValueMatcher } from '~/types'@@ -19,7 +20,9 @@ import { ValueMatcher } from '~/types'import { createLibVersionMonitorStep } from './lib-version-monitor-step'import { createParseMessageStep } from './parse-message-step'import { createRecordSessionEventStep } from './record-session-event-step'+import { createResolveRetentionStep } from './session-batch-resolve-retention-step'import { createTeamFilterStep } from './team-filter-step'+import { createValidateSessionReplayHeadersStep } from './validate-headers-step'export interface SessionReplayPipelineInput {message: Message@@ -36,6 +39,8 @@ export interface SessionReplayPipelineConfig {overflowEnabled: booleanpromiseScheduler: PromiseSchedulerteamService: TeamService+ /** Resolves per-session retention before recording, so keys and storage route correctly */+ retentionService: RetentionService/** TopHog registry for tracking metrics. */topHog: TopHogRegistry/** Session batch manager for recording sessions. */@@ -69,6 +74,7 @@ export function createSessionReplayPipeline(overflowEnabled,promiseScheduler,teamService,+ retentionService,topHog,sessionBatchManager,isDebugLoggingEnabled,@@ -94,9 +100,19 @@ export function createSessionReplayPipeline(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)))+ // 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()+ .pipeBatchWithRetry(createResolveRetentionStep(retentionService, sessionBatchManager), {+ tries: 3,+ sleepMs: 100,+ })// Map TeamForReplay.teamId to context.team.id for handleIngestionWarnings.filterMap((element) => ({@@ -123,7 +139,6 @@ export function createSessionReplayPipeline()// Monitor library version and emit warnings for old versions.pipe(createLibVersionMonitorStep())- // Record to session batch.pipe(topHogWrapper(createRecordSessionEventStep({@@ -167,9 +182,8 @@ export function createSessionReplayPipeline(* 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.+ * tracks offsets while recording, and drop/dlq steps no longer have to remember to. The caller feeds+ * the returned offsets to the offset manager, which commits them on the next flush.** Relies on the pipeline draining the whole fed batch before it returns null, so every fed message* yields exactly one terminal result here.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/blackhole-session-batch-writer.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/blackhole-session-batch-writer.test.tsindex 4c678c037cd8..eac9b492f8e7 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/blackhole-session-batch-writer.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/blackhole-session-batch-writer.test.ts@@ -11,7 +11,7 @@ describe('BlackholeSessionBatchFileStorage', () => {it('should write session data and return bytes written', async () => {const buffer = Buffer.from('test data')- const result = await writer.writeSession({ buffer, teamId: 1, sessionId: '123' })+ const result = await writer.writeSession({ buffer, teamId: 1, sessionId: '123', retentionPeriod: '30d' })expect(result.bytesWritten).toBe(buffer.length)expect(result.url).toBeNull()@@ -21,7 +21,7 @@ describe('BlackholeSessionBatchFileStorage', () => {it('should handle empty buffers', async () => {const buffer = Buffer.from('')- const result = await writer.writeSession({ buffer, teamId: 1, sessionId: '123' })+ const result = await writer.writeSession({ buffer, teamId: 1, sessionId: '123', retentionPeriod: '30d' })expect(result.bytesWritten).toBe(0)expect(result.url).toBeNull()@@ -31,7 +31,7 @@ describe('BlackholeSessionBatchFileStorage', () => {it('should handle large buffers', async () => {const buffer = Buffer.alloc(100 * 1024 * 1024, 'x') // 100MB of data- const result = await writer.writeSession({ buffer, teamId: 1, sessionId: '123' })+ const result = await writer.writeSession({ buffer, teamId: 1, sessionId: '123', retentionPeriod: '30d' })expect(result.bytesWritten).toBe(buffer.length)expect(result.url).toBeNull()@@ -43,8 +43,18 @@ describe('BlackholeSessionBatchFileStorage', () => {const buffer1 = Buffer.from('data1')const buffer2 = Buffer.from('data2')- const result1 = await writer.writeSession({ buffer: buffer1, teamId: 1, sessionId: '123' })- const result2 = await writer.writeSession({ buffer: buffer2, teamId: 2, sessionId: '321' })+ const result1 = await writer.writeSession({+ buffer: buffer1,+ teamId: 1,+ sessionId: '123',+ retentionPeriod: '30d',+ })+ const result2 = await writer.writeSession({+ buffer: buffer2,+ teamId: 2,+ sessionId: '321',+ retentionPeriod: '30d',+ })expect(result1.bytesWritten).toBe(buffer1.length)expect(result2.bytesWritten).toBe(buffer2.length)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/metrics.tsindex cc4ee0d327cb..b0ac38d23cad 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/metrics.ts@@ -6,6 +6,15 @@ export class SessionBatchMetrics {help: 'Number of session recording batches that have been flushed',})+ private static readonly sessionsDroppedMissingRetention = new Counter({+ name: 'recording_blob_ingestion_v2_sessions_dropped_missing_retention_total',+ help: 'Number of sessions dropped before recording because retention could not be resolved (e.g. deleted team)',+ })++ public static incrementSessionsDroppedMissingRetention(count: number = 1): void {+ this.sessionsDroppedMissingRetention.inc(count)+ }+private static readonly sessionsFlushed = new Counter({name: 'recording_blob_ingestion_v2_sessions_flushed_total',help: 'Number of individual sessions that have been flushed',diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/retention-aware-batch-writer.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/retention-aware-batch-writer.test.tsindex 287f82330131..7f724a96940c 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/retention-aware-batch-writer.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/retention-aware-batch-writer.test.ts@@ -1,9 +1,6 @@import { S3Client } from '@aws-sdk/client-s3'import { Upload } from '@aws-sdk/lib-storage'-import { RetentionService } from '~/ingestion/pipelines/sessionreplay/shared/retention/retention-service'-import { TeamId } from '~/types'-import { RetentionAwareStorage } from './retention-aware-batch-writer'jest.mock('@aws-sdk/lib-storage')@@ -17,7 +14,6 @@ describe('RetentionAwareStorage', () => {let mockUploadDone: jest.Mocklet uploadedData: Bufferlet mockS3Client: jest.Mocked<S3Client>- let mockRetentionService: jest.Mocked<RetentionService>beforeEach(() => {uploadedData = Buffer.alloc(0)@@ -39,17 +35,7 @@ describe('RetentionAwareStorage', () => {})jest.mocked(Upload).mockImplementation(mockUpload)- mockRetentionService = {- getSessionRetention: jest.fn().mockImplementation((teamId: TeamId, sessionId: string) => {- const sessionKey = `${teamId}$${sessionId}`- return {- '1$123': '1y',- '2$456': '90d',- }[sessionKey]- }),- } as unknown as jest.Mocked<RetentionService>-- storage = new RetentionAwareStorage(mockS3Client, 'test-bucket', 'test-prefix', 5000, mockRetentionService)+ storage = new RetentionAwareStorage(mockS3Client, 'test-bucket', 'test-prefix', 5000)})afterEach(() => {@@ -61,7 +47,12 @@ describe('RetentionAwareStorage', () => {it('should write session data to correct retention prefix and return bytes written with URL', async () => {const writer = storage.newBatch()const testData = Buffer.from('test data')- const result = await writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123' })+ const result = await writer.writeSession({+ buffer: testData,+ teamId: 1,+ sessionId: '123',+ retentionPeriod: '1y',+ })expect(mockUpload).toHaveBeenCalledTimes(1)expect(mockUpload).toHaveBeenCalledWith(@@ -85,7 +76,12 @@ describe('RetentionAwareStorage', () => {const writer = storage.newBatch()const testData = Buffer.from('test data\nmore test data\n')- const result = await writer.writeSession({ buffer: testData, teamId: 2, sessionId: '456' })+ const result = await writer.writeSession({+ buffer: testData,+ teamId: 2,+ sessionId: '456',+ retentionPeriod: '90d',+ })await writer.finish()expect(mockUpload).toHaveBeenCalledTimes(1)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/retention-aware-batch-writer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/retention-aware-batch-writer.tsindex d35d6033ea17..354c42e6417a 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/retention-aware-batch-writer.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/retention-aware-batch-writer.ts@@ -2,7 +2,6 @@ import { S3Client } from '@aws-sdk/client-s3'import { ValidRetentionPeriods } from '~/ingestion/pipelines/sessionreplay/constants'import { RetentionPeriodToDaysMap } from '~/ingestion/pipelines/sessionreplay/constants'-import { RetentionService } from '~/ingestion/pipelines/sessionreplay/shared/retention/retention-service'import { RetentionPeriod } from '~/ingestion/pipelines/sessionreplay/types'import { S3SessionBatchFileStorage } from './s3-session-batch-writer'@@ -16,10 +15,7 @@ import {class RetentionAwareBatchFileWriter implements SessionBatchFileWriter {private writerMap: { [key in RetentionPeriod]: SessionBatchFileWriter | null }- constructor(- private readonly retentionService: RetentionService,- private readonly storageMap: { [key in RetentionPeriod]: SessionBatchFileStorage }- ) {+ constructor(private readonly storageMap: { [key in RetentionPeriod]: SessionBatchFileStorage }) {this.writerMap = ValidRetentionPeriods.reduce((writers, retentionPeriod) => {writers[retentionPeriod] = null@@ -30,10 +26,9 @@ class RetentionAwareBatchFileWriter implements SessionBatchFileWriter {}public async writeSession(sessionData: WriteSessionData): Promise<WriteSessionResult> {- const retentionPeriod = await this.retentionService.getSessionRetention(- sessionData.teamId,- sessionData.sessionId- )+ // Retention is resolved upstream (in the resolve-retention record step) and carried on the+ // session data, so routing to the right per-retention storage needs no Redis lookup here.+ const retentionPeriod = sessionData.retentionPeriodlet writer = this.writerMap[retentionPeriod]@@ -72,8 +67,7 @@ export class RetentionAwareStorage implements SessionBatchFileStorage {private readonly s3: S3Client,private readonly bucket: string,private readonly prefix: string,- private readonly timeout: number = 5000,- private readonly retentionService: RetentionService+ private readonly timeout: number = 5000) {this.storageMap = ValidRetentionPeriods.reduce((storage, retentionPeriod) => {@@ -90,7 +84,7 @@ export class RetentionAwareStorage implements SessionBatchFileStorage {}public newBatch(): RetentionAwareBatchFileWriter {- return new RetentionAwareBatchFileWriter(this.retentionService, this.storageMap)+ return new RetentionAwareBatchFileWriter(this.storageMap)}public checkHealth(): Promise<boolean> {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/s3-session-batch-writer.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/s3-session-batch-writer.test.tsindex 710e7472f954..414d990691a2 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/s3-session-batch-writer.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/s3-session-batch-writer.test.ts@@ -58,7 +58,12 @@ describe('S3SessionBatchFileStorage', () => {it('should write session data and return bytes written with URL', async () => {const writer = storage.newBatch()const testData = Buffer.from('test data')- const result = await writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123' })+ const result = await writer.writeSession({+ buffer: testData,+ teamId: 1,+ sessionId: '123',+ retentionPeriod: '30d',+ })expect(mockUpload).toHaveBeenCalledTimes(1)expect(mockUpload).toHaveBeenCalledWith(@@ -82,7 +87,12 @@ describe('S3SessionBatchFileStorage', () => {const writer = storage.newBatch()const testData = Buffer.from('test data\nmore test data\n')- const result = await writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123' })+ const result = await writer.writeSession({+ buffer: testData,+ teamId: 1,+ sessionId: '123',+ retentionPeriod: '30d',+ })await writer.finish()expect(mockUpload).toHaveBeenCalledTimes(1)@@ -110,16 +120,21 @@ describe('S3SessionBatchFileStorage', () => {const writer = storage.newBatch()const testData = Buffer.from('test data')- await expect(writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123' })).rejects.toThrow(- testError- )+ await expect(+ writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123', retentionPeriod: '30d' })+ ).rejects.toThrow(testError)})it('should handle writing large amounts of data', async () => {const writer = storage.newBatch()const chunk = Buffer.alloc(1024 * 1024 * 100, 'x') // 100MB- const result = await writer.writeSession({ buffer: chunk, teamId: 1, sessionId: '123' })+ const result = await writer.writeSession({+ buffer: chunk,+ teamId: 1,+ sessionId: '123',+ retentionPeriod: '30d',+ })await writer.finish()expect(mockUpload).toHaveBeenCalledTimes(1)@@ -135,7 +150,12 @@ describe('S3SessionBatchFileStorage', () => {const lines = ['line1\n', 'line2\n', 'line3\n']for (const line of lines) {- await writer.writeSession({ buffer: Buffer.from(line), teamId: 1, sessionId: '123' })+ await writer.writeSession({+ buffer: Buffer.from(line),+ teamId: 1,+ sessionId: '123',+ retentionPeriod: '30d',+ })}await writer.finish()@@ -172,7 +192,7 @@ describe('S3SessionBatchFileStorage', () => {const writer = storage.newBatch()const testData = Buffer.from('test data')- await writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123' })+ await writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123', retentionPeriod: '30d' })await writer.finish()expect(SessionBatchMetrics.incrementS3BatchesUploaded).toHaveBeenCalledTimes(1)@@ -199,9 +219,9 @@ describe('S3SessionBatchFileStorage', () => {const writer = storage.newBatch()const testData = Buffer.from('test data')- await expect(writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123' })).rejects.toThrow(- testError- )+ await expect(+ writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123', retentionPeriod: '30d' })+ ).rejects.toThrow(testError)expect(SessionBatchMetrics.incrementS3UploadErrors).toHaveBeenCalledTimes(1)})@@ -212,7 +232,7 @@ describe('S3SessionBatchFileStorage', () => {const writer = storage.newBatch()const testData = Buffer.from('test data')- await writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123' })+ await writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123', retentionPeriod: '30d' })// Advance time to simulate some upload durationjest.advanceTimersByTime(100)@@ -260,7 +280,7 @@ describe('S3SessionBatchFileStorage', () => {const writer = storage.newBatch()const testData = Buffer.from('test data')- await writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123' })+ await writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123', retentionPeriod: '30d' })const finishPromise = writer.finish()@@ -278,7 +298,7 @@ describe('S3SessionBatchFileStorage', () => {const writer = storage.newBatch()const testData = Buffer.from('test data')- await writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123' })+ await writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123', retentionPeriod: '30d' })const finishPromise = writer.finish()@@ -292,7 +312,7 @@ describe('S3SessionBatchFileStorage', () => {it('should clear timeout on successful upload', async () => {const writer = storage.newBatch()const testData = Buffer.from('test data')- await writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123' })+ await writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123', retentionPeriod: '30d' })await writer.finish()// Advance timers - should not throw since timeout was cleared@@ -309,7 +329,7 @@ describe('S3SessionBatchFileStorage', () => {storage = new S3SessionBatchFileStorage(mockS3Client, 'test-bucket', 'test-prefix', customTimeout)const writer = storage.newBatch()const testData = Buffer.from('test data')- await writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123' })+ await writer.writeSession({ buffer: testData, teamId: 1, sessionId: '123', retentionPeriod: '30d' })const finishPromise = writer.finish()diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-file-storage.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-file-storage.tsindex e7f5d6d2d31f..db777f8d799f 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-file-storage.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-file-storage.ts@@ -1,3 +1,4 @@+import { RetentionPeriod } from '~/ingestion/pipelines/sessionreplay/shared/constants'import { TeamId } from '~/types'export interface WriteSessionData {@@ -7,6 +8,9 @@ export interface WriteSessionData {sessionId: stringteamId: TeamId++ /** The session's retention period, resolved upstream — routes the block to the matching storage */+ retentionPeriod: RetentionPeriod}export interface WriteSessionResult {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.tsindex 2a2194587c20..914cfea05905 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@@ -4,6 +4,7 @@ import { validate as uuidValidate } from 'uuid'import { parseJSON } from '~/common/utils/json-parse'import { KafkaOffsetManager } from '~/ingestion/pipelines/sessionreplay/kafka/offset-manager'import { ParsedMessageData, SnapshotEvent } from '~/ingestion/pipelines/sessionreplay/kafka/types'+import { RetentionPeriod } from '~/ingestion/pipelines/sessionreplay/shared/constants'import { SessionFeatureStore } from '~/ingestion/pipelines/sessionreplay/shared/features/session-feature-store'import { SessionMetadataStore } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-metadata-store'import { createMockEncryptor, createMockKeyStore } from '~/ingestion/pipelines/sessionreplay/shared/test-helpers'@@ -208,6 +209,10 @@ describe('SessionBatchRecorder', () => {let mockKeyStore: jest.Mocked<KeyStore>let mockEncryptor: jest.Mocked<RecordingEncryptor>+ // Records a message with its resolved retention (defaults to 30d — most tests don't vary it).+ const record = (message: MessageWithTeam, retentionPeriod: RetentionPeriod = '30d'): Promise<number> =>+ recorder.record(message, retentionPeriod)+beforeEach(() => {jest.clearAllMocks()@@ -324,6 +329,23 @@ describe('SessionBatchRecorder', () => {return mockWriteSession.mock.calls.map(([data]) => data.buffer.toString())}+ describe('getRetention', () => {+ it('returns the retention a recorded session was stored with', async () => {+ await record(createMessage('session1', []), '1y')+ expect(recorder.getRetention(1, 'session1')).toBe('1y')+ })++ it('returns undefined for a session the batch has not seen', () => {+ expect(recorder.getRetention(1, 'unknown-session')).toBeUndefined()+ })++ it('scopes by team, so the same session id under another team is not found', async () => {+ await record(createMessage('session1', [], {}, 1), '30d')+ expect(recorder.getRetention(1, 'session1')).toBe('30d')+ expect(recorder.getRetention(2, 'session1')).toBeUndefined()+ })+ })+describe('recording and writing', () => {it('should write events in correct format', async () => {const message = createMessage('session1', [@@ -334,7 +356,7 @@ describe('SessionBatchRecorder', () => {},])- await recorder.record(message)+ await record(message)await recorder.flush()const writtenData = captureWrittenData(mockWriter.writeSession as jest.Mock)@@ -351,7 +373,7 @@ describe('SessionBatchRecorder', () => {},])- await recorder.record(message)+ await record(message)await recorder.flush()const writtenData = captureWrittenData(mockWriter.writeSession as jest.Mock)@@ -382,7 +404,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- await recorder.record(message)+ await record(message)}await recorder.flush()@@ -416,7 +438,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- await recorder.record(message)+ await record(message)}await recorder.flush()@@ -433,7 +455,7 @@ describe('SessionBatchRecorder', () => {it('should handle empty events array', async () => {const message = createMessage('session1', [])- const bytesWritten = await recorder.record(message)+ const bytesWritten = await record(message)await recorder.flush()@@ -478,7 +500,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- await recorder.record(message)+ await record(message)}await recorder.flush()@@ -559,7 +581,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- await recorder.record(message)+ await record(message)}await recorder.flush()@@ -610,7 +632,7 @@ describe('SessionBatchRecorder', () => {},])- await recorder.record(message)+ await record(message)await recorder.flush()expect(SessionConsoleLogRecorder).toHaveBeenCalledWith(@@ -643,7 +665,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- await recorder.record(message)+ await record(message)}await recorder.flush()@@ -679,7 +701,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- await recorder.record(message)+ await record(message)}await recorder.flush()@@ -727,7 +749,7 @@ describe('SessionBatchRecorder', () => {return Promise.resolve()})- await recorder.record(message)+ await record(message)await recorder.flush()expect(mockConsoleLogStore.flush).toHaveBeenCalledTimes(1)@@ -775,7 +797,7 @@ describe('SessionBatchRecorder', () => {// Record all messagesfor (const message of messages) {- await recorder.record(message)+ await record(message)}await recorder.flush()@@ -830,7 +852,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- await recorder.record(message)+ await record(message)}await recorder.flush()@@ -875,7 +897,7 @@ describe('SessionBatchRecorder', () => {},])- await recorder.record(message1)+ await record(message1)await recorder.flush()const writtenData1 = captureWrittenData(mockWriter.writeSession as jest.Mock)@@ -894,7 +916,7 @@ describe('SessionBatchRecorder', () => {},])- await recorder.record(message2)+ await record(message2)await recorder.flush()const writtenData2 = captureWrittenData(mockWriter.writeSession as jest.Mock)@@ -916,7 +938,7 @@ describe('SessionBatchRecorder', () => {},])- await recorder.record(message)+ await record(message)await recorder.flush()expect(mockStorage.newBatch).toHaveBeenCalledTimes(1)@@ -998,7 +1020,7 @@ describe('SessionBatchRecorder', () => {return Promise.resolve()})- await recorder.record(message)+ await record(message)await recorder.flush()expect(mockWriter.finish).toHaveBeenCalledTimes(1)@@ -1043,7 +1065,7 @@ describe('SessionBatchRecorder', () => {},])- await recorder.record(message)+ await record(message)await expect(recorder.flush()).rejects.toThrow(error)expect(mockWriter.finish).toHaveBeenCalledTimes(1)@@ -1064,7 +1086,7 @@ describe('SessionBatchRecorder', () => {},])- await recorder.record(message)+ await record(message)await expect(recorder.flush()).rejects.toThrow(error)expect(mockWriter.finish).toHaveBeenCalledTimes(1)@@ -1098,7 +1120,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- await recorder.record(message)+ await record(message)}await recorder.flush()@@ -1181,7 +1203,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- await recorder.record(message)+ await record(message)}await recorder.flush()@@ -1222,7 +1244,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- await recorder.record(message)+ await record(message)}recorder.discardPartition(1)await recorder.flush()@@ -1257,8 +1279,8 @@ describe('SessionBatchRecorder', () => {{ partition: 2 })- const size1 = await recorder.record(message1)- const size2 = await recorder.record(message2)+ const size1 = await record(message1)+ const size2 = await record(message2)expect(recorder.size).toBe(size1 + size2)recorder.discardPartition(1)@@ -1279,7 +1301,7 @@ describe('SessionBatchRecorder', () => {},])- const bytesWritten = await recorder.record(message)+ const bytesWritten = await record(message)expect(recorder.size).toBe(bytesWritten)recorder.discardPartition(999)@@ -1312,7 +1334,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- await recorder.record(message)+ await record(message)}await recorder.flush()@@ -1358,7 +1380,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- await recorder.record(message)+ await record(message)}recorder.discardPartition(1)await recorder.flush()@@ -1389,7 +1411,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- await recorder.record(message)+ await record(message)}await recorder.flush()@@ -1412,7 +1434,7 @@ describe('SessionBatchRecorder', () => {data: { custom: 'data' },},])- await recorder.record(message3)+ await record(message3)await recorder.flush()expect(SessionBatchMetrics.incrementBatchesFlushed).toHaveBeenCalledTimes(2)@@ -1483,7 +1505,7 @@ describe('SessionBatchRecorder', () => {mockEncryptor,Number.MAX_SAFE_INTEGER)- await recorder.record(message)+ await record(message)await recorder.flush()// Verify that the metadata store received both the non-default values and console log counts@@ -1520,7 +1542,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- await recorder.record(message)+ await record(message)}await recorder.flush()@@ -1535,7 +1557,7 @@ describe('SessionBatchRecorder', () => {})it('should generate UUIDv7 format batch IDs', async () => {- await recorder.record(createMessage('session1', [{ type: EventType.Meta, timestamp: 1000, data: {} }]))+ await record(createMessage('session1', [{ type: EventType.Meta, timestamp: 1000, data: {} }]))await recorder.flush()const batchId = mockMetadataStore.storeSessionBlocks.mock.calls[0][0][0].batchId@@ -1566,7 +1588,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- await recorder.record(message)+ await record(message)}await recorder.flush()@@ -1598,7 +1620,7 @@ describe('SessionBatchRecorder', () => {},])- await recorder.record(message1)+ await record(message1)await recorder.flush()expect(mockMetadataStore.storeSessionBlocks).toHaveBeenLastCalledWith([@@ -1616,7 +1638,7 @@ describe('SessionBatchRecorder', () => {},])- await recorder.record(message2)+ await record(message2)await recorder.flush()expect(mockMetadataStore.storeSessionBlocks).toHaveBeenLastCalledWith([@@ -1646,7 +1668,7 @@ describe('SessionBatchRecorder', () => {}) as unknown as SnappySessionRecorder)- await recorder.record(createMessage('session', events))+ await record(createMessage('session', events))const flushPromise = recorder.flush()@@ -1662,7 +1684,7 @@ describe('SessionBatchRecorder', () => {mockWriter.writeSession.mockRejectedValueOnce(error)const message = createMessage('session1', [{ type: 1, timestamp: 1, data: {} }])- await recorder.record(message)+ await record(message)await expect(recorder.flush()).rejects.toThrow(error)@@ -1694,7 +1716,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- const bytesWritten = await recorder.record(message)+ const bytesWritten = await record(message)expect(bytesWritten).toBeGreaterThan(0)}@@ -1723,9 +1745,9 @@ describe('SessionBatchRecorder', () => {createMessage('session1', [{ type: EventType.Meta, timestamp: 3000, data: {} }]),]- const bytesWritten1 = await recorder.record(messages[0])- const bytesWritten2 = await recorder.record(messages[1])- const bytesWritten3 = await recorder.record(messages[2])+ const bytesWritten1 = await record(messages[0])+ const bytesWritten2 = await record(messages[1])+ const bytesWritten3 = await record(messages[2])expect(bytesWritten1).toBeGreaterThan(0)expect(bytesWritten2).toBeGreaterThan(0)@@ -1755,8 +1777,8 @@ describe('SessionBatchRecorder', () => {createMessage('session1', [{ type: EventType.Meta, timestamp: 2000, data: {} }]),]- await recorder.record(messages[0])- await recorder.record(messages[1])+ await record(messages[0])+ await record(messages[1])await recorder.flush()expect(mockWriter.writeSession).not.toHaveBeenCalled()@@ -1787,7 +1809,7 @@ describe('SessionBatchRecorder', () => {const results = []for (const message of messages) {- results.push(await recorder.record(message))+ results.push(await record(message))}expect(results[0]).toBeGreaterThan(0)@@ -1821,7 +1843,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages1) {- await recorder.record(message)+ await record(message)}await recorder.flush()@@ -1833,8 +1855,8 @@ describe('SessionBatchRecorder', () => {createMessage('session1', [{ type: EventType.Meta, timestamp: 4000, data: {} }]),]- const bytesWritten1 = await recorder.record(messages2[0])- const bytesWritten2 = await recorder.record(messages2[1])+ const bytesWritten1 = await record(messages2[0])+ const bytesWritten2 = await record(messages2[1])expect(bytesWritten1).toBeGreaterThan(0)expect(bytesWritten2).toBeGreaterThan(0)@@ -1861,15 +1883,15 @@ describe('SessionBatchRecorder', () => {partition: 1,})- await recorder.record(message1)- await recorder.record(message2)+ await record(message1)+ await record(message2)recorder.discardPartition(1)const message3 = createMessage('session1', [{ type: EventType.Meta, timestamp: 3000, data: {} }], {partition: 2,})- const bytesWritten = await recorder.record(message3)+ const bytesWritten = await record(message3)expect(bytesWritten).toBeGreaterThan(0)})@@ -1896,7 +1918,7 @@ describe('SessionBatchRecorder', () => {const results = []for (const message of messages) {- results.push(await recorder.record(message))+ results.push(await record(message))}expect(results[0]).toBeGreaterThan(0)@@ -1930,7 +1952,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- await recorder.record(message)+ await record(message)}expect(SessionBatchMetrics.incrementSessionsRateLimited).toHaveBeenCalledTimes(1)@@ -1961,7 +1983,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- await recorder.record(message)+ await record(message)}expect(SessionBatchMetrics.incrementSessionsRateLimited).toHaveBeenCalledTimes(1)@@ -1993,7 +2015,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages) {- await recorder.record(message)+ await record(message)}expect(SessionBatchMetrics.incrementSessionsRateLimited).toHaveBeenCalledTimes(2)@@ -2023,7 +2045,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages1) {- await recorder.record(message)+ await record(message)}await recorder.flush()@@ -2036,7 +2058,7 @@ describe('SessionBatchRecorder', () => {]for (const message of messages2) {- await recorder.record(message)+ await record(message)}expect(SessionBatchMetrics.incrementSessionsRateLimited).toHaveBeenCalledTimes(1)@@ -2060,7 +2082,7 @@ describe('SessionBatchRecorder', () => {{ partition: 1, offset: 42 })- const bytesWritten = await recorder.record(message)+ const bytesWritten = await record(message)expect(bytesWritten).toBe(0)})@@ -2093,8 +2115,8 @@ describe('SessionBatchRecorder', () => {{ partition: 1, offset: 1 })- const bytes1 = await recorder.record(message1)- const bytes2 = await recorder.record(message2)+ const bytes1 = await record(message1)+ const bytes2 = await record(message2)expect(bytes1).toBeGreaterThan(0)expect(bytes2).toBe(0)@@ -2109,7 +2131,7 @@ describe('SessionBatchRecorder', () => {{ type: EventType.FullSnapshot, timestamp: 1000, data: { source: 1 } },])- await recorder.record(message)+ await record(message)expect(mockSessionFilter.handleNewSession).toHaveBeenCalledWith(1, 'session1')})@@ -2121,7 +2143,7 @@ describe('SessionBatchRecorder', () => {{ type: EventType.FullSnapshot, timestamp: 1000, data: { source: 1 } },])- await recorder.record(message)+ await record(message)expect(mockSessionFilter.handleNewSession).not.toHaveBeenCalled()})@@ -2135,7 +2157,7 @@ describe('SessionBatchRecorder', () => {{ type: EventType.FullSnapshot, timestamp: 1000, data: { source: 1 } },])- const bytesWritten = await recorder.record(message)+ const bytesWritten = await record(message)expect(bytesWritten).toBe(0)expect(mockSessionFilter.handleNewSession).toHaveBeenCalledWith(1, 'session1')@@ -2150,7 +2172,7 @@ describe('SessionBatchRecorder', () => {{ type: EventType.FullSnapshot, timestamp: 1000, data: { source: 1 } },])- const bytesWritten = await recorder.record(message)+ const bytesWritten = await record(message)expect(bytesWritten).toBeGreaterThan(0)})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.tsindex d108ccb7cc93..8ea340a9a31b 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts@@ -3,12 +3,14 @@ import { v7 as uuidv7 } from 'uuid'import { logger } from '~/common/utils/logger'import { captureException } from '~/common/utils/posthog'import { KafkaOffsetManager } from '~/ingestion/pipelines/sessionreplay/kafka/offset-manager'+import { RetentionPeriod, RetentionPeriodToDaysMap } from '~/ingestion/pipelines/sessionreplay/shared/constants'import {SessionFeatureBlock,SessionFeatureStore,} from '~/ingestion/pipelines/sessionreplay/shared/features/session-feature-store'import { SessionBlockMetadata } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata'import { SessionMetadataSink } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-metadata-store'+import { SessionMap } from '~/ingestion/pipelines/sessionreplay/shared/session-map'import { KeyStore, RecordingEncryptor, SessionKey } from '~/ingestion/pipelines/sessionreplay/shared/types'import { MessageWithTeam } from '~/ingestion/pipelines/sessionreplay/teams/types'@@ -22,6 +24,17 @@ import { SessionRateLimiter } from './session-rate-limiter'import { SessionTracker } from './session-tracker'import { SnappySessionRecorder } from './snappy-session-recorder'+/** Per-session recording state held in the batch, keyed by `(teamId, sessionId)`. */+interface SessionBatchEntry {+ sessionBlockRecorder: SnappySessionRecorder+ consoleLogRecorder: SessionConsoleLogRecorder+ featureRecorder: SessionFeatureRecorder+ sessionKey: SessionKey+ retentionPeriod: RetentionPeriod+ /** Kafka partition the session is pinned to; used to drop the session on partition revocation. */+ partition: number+}+/*** Manages the recording of a batch of session recordings:*@@ -66,10 +79,10 @@ import { SnappySessionRecorder } from './snappy-session-recorder'* as only the relevant session block needs to be retrieved and decompressed.*/export class SessionBatchRecorder {- private readonly partitionSessions = new Map<- number,- Map<string, [SnappySessionRecorder, SessionConsoleLogRecorder, SessionFeatureRecorder, SessionKey]>- >()+ // Sessions are keyed by (teamId, sessionId) across all partitions. A session is pinned to one+ // partition, so the key is unique; each entry carries its partition for revocation. Not readonly:+ // discard and flush swap it for a fresh map.+ private sessions = new SessionMap<SessionBatchEntry>()private readonly partitionSizes = new Map<number, number>()private _size: number = 0private readonly batchId: string@@ -97,13 +110,14 @@ export class SessionBatchRecorder {* Appends events into the appropriate session** @param message - The message to record, including team context+ * @param retentionPeriod - The session's retention, resolved upstream; sets the key expiry and+ * routes the flush to the matching per-retention storage.* @returns Number of raw bytes written (without compression)*/- public async record(message: MessageWithTeam): Promise<number> {+ public async record(message: MessageWithTeam, retentionPeriod: RetentionPeriod): Promise<number> {const { partition } = message.message.metadataconst sessionId = message.message.session_idconst teamId = message.team.teamId- const teamSessionKey = `${teamId}$${sessionId}`// Check if this is a new session and check if we're in breach of the rate limitconst isNewSession = await this.sessionTracker.trackSession(teamId, sessionId)@@ -123,7 +137,7 @@ export class SessionBatchRecorder {}const sessionKey = isNewSession- ? await this.keyStore.generateKey(sessionId, teamId)+ ? await this.keyStore.generateKey(sessionId, teamId, RetentionPeriodToDaysMap[retentionPeriod]): await this.keyStore.getKey(sessionId, teamId)if (sessionKey.sessionState === 'deleted') {@@ -136,24 +150,19 @@ export class SessionBatchRecorder {return 0}- const isEventAllowed = this.rateLimiter.handleMessage(teamSessionKey, partition, message.message)+ const isEventAllowed = this.rateLimiter.handleMessage(teamId, sessionId, partition, message.message)if (!isEventAllowed) {logger.debug('🔁', 'session_batch_recorder_event_rate_limited', {partition,sessionId,teamId,- eventCount: this.rateLimiter.getEventCount(teamSessionKey),+ eventCount: this.rateLimiter.getEventCount(teamId, sessionId),batchId: this.batchId,})- if (!this.partitionSessions.has(partition)) {- return 0- }-- const sessions = this.partitionSessions.get(partition)!- if (sessions.has(teamSessionKey)) {- sessions.delete(teamSessionKey)+ if (this.sessions.has(teamId, sessionId)) {+ this.sessions.delete(teamId, sessionId)logger.info('🔁', 'session_batch_recorder_deleted_rate_limited_session', {partition,sessionId,@@ -165,16 +174,14 @@ export class SessionBatchRecorder {return 0}- if (!this.partitionSessions.has(partition)) {- this.partitionSessions.set(partition, new Map())+ if (!this.partitionSizes.has(partition)) {this.partitionSizes.set(partition, 0)}- const sessions = this.partitionSessions.get(partition)!- const existingBatchState = sessions.get(teamSessionKey)+ const existingBatchState = this.sessions.get(teamId, sessionId)if (existingBatchState) {- const [sessionBlockRecorder, _logRecorder, _featureRecorder, existingSessionKey] = existingBatchState+ const { sessionBlockRecorder, sessionKey: existingSessionKey } = existingBatchStateif (sessionBlockRecorder.teamId !== teamId) {logger.warn('🔁', 'session_batch_recorder_team_id_mismatch', {sessionId,@@ -194,15 +201,27 @@ export class SessionBatchRecorder {return 0}} else {- sessions.set(teamSessionKey, [- new SnappySessionRecorder(sessionId, teamId, this.batchId),- new SessionConsoleLogRecorder(sessionId, teamId, this.batchId, this.consoleLogStore),- new SessionFeatureRecorder(sessionId, teamId, this.batchId, this.featuresRolloutPercentage),+ this.sessions.set(teamId, sessionId, {+ sessionBlockRecorder: new SnappySessionRecorder(sessionId, teamId, this.batchId),+ consoleLogRecorder: new SessionConsoleLogRecorder(+ sessionId,+ teamId,+ this.batchId,+ this.consoleLogStore+ ),+ featureRecorder: new SessionFeatureRecorder(+ sessionId,+ teamId,+ this.batchId,+ this.featuresRolloutPercentage+ ),sessionKey,- ])+ retentionPeriod,+ partition,+ })}- const [sessionBlockRecorder, consoleLogRecorder, featureRecorder] = sessions.get(teamSessionKey)!+ const { sessionBlockRecorder, consoleLogRecorder, featureRecorder } = this.sessions.get(teamId, sessionId)!const bytesWritten = sessionBlockRecorder.recordMessage(message.message)await consoleLogRecorder.recordMessage(message)try {@@ -233,6 +252,15 @@ export class SessionBatchRecorder {return bytesWritten}+ /**+ * Retention already resolved for a session held in this (unflushed) batch, or undefined if the+ * batch hasn't seen it. Lets the resolve-retention step skip re-resolving a session a previous+ * batch already placed here.+ */+ public getRetention(teamId: number, sessionId: string): RetentionPeriod | undefined {+ return this.sessions.get(teamId, sessionId)?.retentionPeriod+ }+/*** Discards all sessions for a given partition, so that they are not persisted in this batch* Used when partitions are revoked during Kafka rebalancing@@ -249,7 +277,15 @@ export class SessionBatchRecorder {this._size -= partitionSizethis.partitionSizes.delete(partition)- this.partitionSessions.delete(partition)+ // Revocation is rare, so rebuilding the session map without the partition is fine — it+ // keeps the per-message lookups a single, flat map access.+ const remaining = new SessionMap<SessionBatchEntry>()+ for (const entry of this.sessions.values()) {+ if (entry.partition !== partition) {+ remaining.set(entry.sessionBlockRecorder.teamId, entry.sessionBlockRecorder.sessionId, entry)+ }+ }+ this.sessions = remainingthis.offsetManager.discardPartition(partition)}}@@ -261,13 +297,17 @@ export class SessionBatchRecorder {*/public async flush(): Promise<SessionBlockMetadata[]> {logger.info('🔁', 'session_batch_recorder_flushing', {- partitions: this.partitionSessions.size,+ sessions: this.sessions.size,totalSize: this._size,})- // If no sessions, commit offsets but skip writing the file- if (this.partitionSessions.size === 0) {+ // If no sessions, commit offsets but skip writing the file. Sessions can still have been+ // recorded then dropped (e.g. rate limited), leaving batch state to reset.+ if (this.sessions.size === 0) {await this.offsetManager.commit()+ this.partitionSizes.clear()+ this._size = 0+ this.rateLimiter.clear()logger.info('🔁', 'session_batch_recorder_flushed_no_sessions')return []}@@ -282,89 +322,89 @@ export class SessionBatchRecorder {let totalBytes = 0try {- for (const sessions of this.partitionSessions.values()) {- for (const [- sessionBlockRecorder,- consoleLogRecorder,- featureRecorder,- sessionKey,- ] of sessions.values()) {- const {- buffer,- eventCount,- startDateTime,- endDateTime,- firstUrl,- urls,- clickCount,- keypressCount,- mouseActivityCount,- activeMilliseconds,- size,- messageCount,- snapshotSource,- snapshotLibrary,- batchId,- } = await sessionBlockRecorder.end()-- const features = featureRecorder.end()- if (features) {- featureBlocks.push({- sessionId: sessionBlockRecorder.sessionId,- teamId: sessionBlockRecorder.teamId,- distinctId: sessionBlockRecorder.distinctId,- batchId,- features,- })- }-- const { consoleLogCount, consoleWarnCount, consoleErrorCount } = consoleLogRecorder.end()-- const { data: encryptedBuffer } = this.encryptor.encryptBlockWithKey(- sessionBlockRecorder.sessionId,- sessionBlockRecorder.teamId,- buffer,- sessionKey- )-- const { bytesWritten, url, retentionPeriodDays } = await writer.writeSession({- buffer: encryptedBuffer,- teamId: sessionBlockRecorder.teamId,- sessionId: sessionBlockRecorder.sessionId,- })-- blockMetadata.push({+ for (const {+ sessionBlockRecorder,+ consoleLogRecorder,+ featureRecorder,+ sessionKey,+ retentionPeriod,+ } of this.sessions.values()) {+ const {+ buffer,+ eventCount,+ startDateTime,+ endDateTime,+ firstUrl,+ urls,+ clickCount,+ keypressCount,+ mouseActivityCount,+ activeMilliseconds,+ size,+ messageCount,+ snapshotSource,+ snapshotLibrary,+ batchId,+ } = await sessionBlockRecorder.end()++ const features = featureRecorder.end()+ if (features) {+ featureBlocks.push({sessionId: sessionBlockRecorder.sessionId,teamId: sessionBlockRecorder.teamId,distinctId: sessionBlockRecorder.distinctId,- blockLength: bytesWritten,- startDateTime,- endDateTime,- blockUrl: url,- firstUrl,- urls,- clickCount,- keypressCount,- mouseActivityCount,- activeMilliseconds,- consoleLogCount,- consoleWarnCount,- consoleErrorCount,- size,- messageCount,- snapshotSource,- snapshotLibrary,batchId,- eventCount,- retentionPeriodDays,- isDeleted: false,+ features,})-- totalEvents += eventCount- totalBytes += bytesWritten}- totalSessions += sessions.size++ const { consoleLogCount, consoleWarnCount, consoleErrorCount } = consoleLogRecorder.end()++ const { data: encryptedBuffer } = this.encryptor.encryptBlockWithKey(+ sessionBlockRecorder.sessionId,+ sessionBlockRecorder.teamId,+ buffer,+ sessionKey+ )++ const { bytesWritten, url, retentionPeriodDays } = await writer.writeSession({+ buffer: encryptedBuffer,+ teamId: sessionBlockRecorder.teamId,+ sessionId: sessionBlockRecorder.sessionId,+ retentionPeriod,+ })++ blockMetadata.push({+ sessionId: sessionBlockRecorder.sessionId,+ teamId: sessionBlockRecorder.teamId,+ distinctId: sessionBlockRecorder.distinctId,+ blockLength: bytesWritten,+ startDateTime,+ endDateTime,+ blockUrl: url,+ firstUrl,+ urls,+ clickCount,+ keypressCount,+ mouseActivityCount,+ activeMilliseconds,+ consoleLogCount,+ consoleWarnCount,+ consoleErrorCount,+ size,+ messageCount,+ snapshotSource,+ snapshotLibrary,+ batchId,+ eventCount,+ retentionPeriodDays,+ isDeleted: false,+ })++ totalEvents += eventCount+ totalBytes += bytesWritten}+ totalSessions = this.sessions.sizeawait writer.finish()await this.consoleLogStore.flush()@@ -379,7 +419,7 @@ export class SessionBatchRecorder {SessionBatchMetrics.incrementBytesWritten(totalBytes)// Clear sessions, partition sizes, total size, and rate limiter state after successful flush- this.partitionSessions.clear()+ this.sessions = new SessionMap()this.partitionSizes.clear()this._size = 0this.rateLimiter.clear()diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.test.tsindex b9e5eb309701..8d9c6cc4feab 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.test.ts@@ -24,51 +24,51 @@ describe('SessionRateLimiter', () => {describe('handleMessage', () => {it('should allow events up to the limit', () => {const limiter = new SessionRateLimiter(3)- const sessionKey = 'team123$session456'+ const session: [number, string] = [123, 'session456']- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(true)- expect(limiter.getEventCount(sessionKey)).toBe(3)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)+ expect(limiter.getEventCount(...session)).toBe(3)})it('should block messages after limit is exceeded', () => {const limiter = new SessionRateLimiter(2)- const sessionKey = 'team123$session456'+ const session: [number, string] = [123, 'session456']- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(false)- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)})it('should track multiple sessions independently', () => {const limiter = new SessionRateLimiter(2)- const session1 = 'team123$session1'- const session2 = 'team123$session2'+ const session1: [number, string] = [123, 'session1']+ const session2: [number, string] = [123, 'session2']- expect(limiter.handleMessage(session1, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(session2, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(session1, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(session2, 1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session1, 1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session2, 1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session1, 1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session2, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(session1, 1, createMessage(1))).toBe(false)- expect(limiter.handleMessage(session2, 1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session1, 1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session2, 1, createMessage(1))).toBe(false)})it('should continue blocking after limit is hit', () => {const limiter = new SessionRateLimiter(1)- const sessionKey = 'team123$session456'+ const session: [number, string] = [123, 'session456']- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(false)- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(false)- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)})it('should count events across multiple windows', () => {const limiter = new SessionRateLimiter(5)- const sessionKey = 'team123$session456'+ const session: [number, string] = [123, 'session456']const messageWithMultipleWindows = {eventsByWindowId: {@@ -77,157 +77,157 @@ describe('SessionRateLimiter', () => {},} as any- expect(limiter.handleMessage(sessionKey, 1, messageWithMultipleWindows)).toBe(true)- expect(limiter.getEventCount(sessionKey)).toBe(4)+ expect(limiter.handleMessage(...session, 1, messageWithMultipleWindows)).toBe(true)+ expect(limiter.getEventCount(...session)).toBe(4)})it('should handle messages with varying event counts', () => {const limiter = new SessionRateLimiter(10)- const sessionKey = 'team123$session456'+ const session: [number, string] = [123, 'session456']- expect(limiter.handleMessage(sessionKey, 1, createMessage(3))).toBe(true)- expect(limiter.getEventCount(sessionKey)).toBe(3)+ expect(limiter.handleMessage(...session, 1, createMessage(3))).toBe(true)+ expect(limiter.getEventCount(...session)).toBe(3)- expect(limiter.handleMessage(sessionKey, 1, createMessage(5))).toBe(true)- expect(limiter.getEventCount(sessionKey)).toBe(8)+ expect(limiter.handleMessage(...session, 1, createMessage(5))).toBe(true)+ expect(limiter.getEventCount(...session)).toBe(8)- expect(limiter.handleMessage(sessionKey, 1, createMessage(2))).toBe(true)- expect(limiter.getEventCount(sessionKey)).toBe(10)+ expect(limiter.handleMessage(...session, 1, createMessage(2))).toBe(true)+ expect(limiter.getEventCount(...session)).toBe(10)- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(false)- expect(limiter.getEventCount(sessionKey)).toBe(11)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)+ expect(limiter.getEventCount(...session)).toBe(11)})it('should allow unlimited events with MAX_SAFE_INTEGER', () => {const limiter = new SessionRateLimiter(Number.MAX_SAFE_INTEGER)- const sessionKey = 'team123$session456'+ const session: [number, string] = [123, 'session456']for (let i = 0; i < 1000; i++) {- expect(limiter.handleMessage(sessionKey, 1, createMessage(1000))).toBe(true)+ expect(limiter.handleMessage(...session, 1, createMessage(1000))).toBe(true)}- expect(limiter.getEventCount(sessionKey)).toBe(1000000)+ expect(limiter.getEventCount(...session)).toBe(1000000)})})describe('getEventCount', () => {it('should return 0 for new session', () => {const limiter = new SessionRateLimiter(10)- expect(limiter.getEventCount('team123$session456')).toBe(0)+ expect(limiter.getEventCount(123, 'session456')).toBe(0)})it('should return current count for tracked session', () => {const limiter = new SessionRateLimiter(10)- const sessionKey = 'team123$session456'+ const session: [number, string] = [123, 'session456']- limiter.handleMessage(sessionKey, 1, createMessage(1))- expect(limiter.getEventCount(sessionKey)).toBe(1)+ limiter.handleMessage(...session, 1, createMessage(1))+ expect(limiter.getEventCount(...session)).toBe(1)- limiter.handleMessage(sessionKey, 1, createMessage(2))- expect(limiter.getEventCount(sessionKey)).toBe(3)+ limiter.handleMessage(...session, 1, createMessage(2))+ expect(limiter.getEventCount(...session)).toBe(3)})it('should increment count even after limit is hit', () => {const limiter = new SessionRateLimiter(2)- const sessionKey = 'team123$session456'+ const session: [number, string] = [123, 'session456']- limiter.handleMessage(sessionKey, 1, createMessage(1))- limiter.handleMessage(sessionKey, 1, createMessage(1))- expect(limiter.getEventCount(sessionKey)).toBe(2)+ limiter.handleMessage(...session, 1, createMessage(1))+ limiter.handleMessage(...session, 1, createMessage(1))+ expect(limiter.getEventCount(...session)).toBe(2)- limiter.handleMessage(sessionKey, 1, createMessage(1))- limiter.handleMessage(sessionKey, 1, createMessage(1))- expect(limiter.getEventCount(sessionKey)).toBe(4)+ limiter.handleMessage(...session, 1, createMessage(1))+ limiter.handleMessage(...session, 1, createMessage(1))+ expect(limiter.getEventCount(...session)).toBe(4)})})describe('removeSession', () => {it('should remove session tracking', () => {const limiter = new SessionRateLimiter(10)- const sessionKey = 'team123$session456'+ const session: [number, string] = [123, 'session456']- limiter.handleMessage(sessionKey, 1, createMessage(2))- expect(limiter.getEventCount(sessionKey)).toBe(2)+ limiter.handleMessage(...session, 1, createMessage(2))+ expect(limiter.getEventCount(...session)).toBe(2)- limiter.removeSession(sessionKey)- expect(limiter.getEventCount(sessionKey)).toBe(0)+ limiter.removeSession(...session)+ expect(limiter.getEventCount(...session)).toBe(0)- limiter.handleMessage(sessionKey, 1, createMessage(1))- expect(limiter.getEventCount(sessionKey)).toBe(1)+ limiter.handleMessage(...session, 1, createMessage(1))+ expect(limiter.getEventCount(...session)).toBe(1)})it('should remove limited session status', () => {const limiter = new SessionRateLimiter(1)- const sessionKey = 'team123$session456'+ const session: [number, string] = [123, 'session456']- limiter.handleMessage(sessionKey, 1, createMessage(1))- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(false)+ limiter.handleMessage(...session, 1, createMessage(1))+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)- limiter.removeSession(sessionKey)- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(true)+ limiter.removeSession(...session)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)})it('should handle removing non-existent session', () => {const limiter = new SessionRateLimiter(10)- expect(() => limiter.removeSession('nonexistent')).not.toThrow()+ expect(() => limiter.removeSession(1, 'nonexistent')).not.toThrow()})})describe('clear', () => {it('should clear all sessions', () => {const limiter = new SessionRateLimiter(10)- const session1 = 'team123$session1'- const session2 = 'team123$session2'+ const session1: [number, string] = [123, 'session1']+ const session2: [number, string] = [123, 'session2']- limiter.handleMessage(session1, 1, createMessage(2))- limiter.handleMessage(session2, 1, createMessage(1))+ limiter.handleMessage(...session1, 1, createMessage(2))+ limiter.handleMessage(...session2, 1, createMessage(1))- expect(limiter.getEventCount(session1)).toBe(2)- expect(limiter.getEventCount(session2)).toBe(1)+ expect(limiter.getEventCount(...session1)).toBe(2)+ expect(limiter.getEventCount(...session2)).toBe(1)limiter.clear()- expect(limiter.getEventCount(session1)).toBe(0)- expect(limiter.getEventCount(session2)).toBe(0)+ expect(limiter.getEventCount(...session1)).toBe(0)+ expect(limiter.getEventCount(...session2)).toBe(0)})it('should clear limited session status', () => {const limiter = new SessionRateLimiter(1)- const sessionKey = 'team123$session456'+ const session: [number, string] = [123, 'session456']- limiter.handleMessage(sessionKey, 1, createMessage(1))- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(false)+ limiter.handleMessage(...session, 1, createMessage(1))+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)limiter.clear()- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)})})describe('edge cases', () => {it('should handle limit of 0', () => {const limiter = new SessionRateLimiter(0)- const sessionKey = 'team123$session456'+ const session: [number, string] = [123, 'session456']- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(false)- expect(limiter.getEventCount(sessionKey)).toBe(1)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)+ expect(limiter.getEventCount(...session)).toBe(1)})it('should handle limit of 1', () => {const limiter = new SessionRateLimiter(1)- const sessionKey = 'team123$session456'+ const session: [number, string] = [123, 'session456']- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)})it('should handle many concurrent sessions', () => {const limiter = new SessionRateLimiter(5)- const sessions = Array.from({ length: 100 }, (_, i) => `team123$session${i}`)+ const sessions = Array.from({ length: 100 }, (_, i): [number, string] => [123, `session${i}`])for (const session of sessions) {for (let i = 0; i < 5; i++) {- expect(limiter.handleMessage(session, 1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)}- expect(limiter.handleMessage(session, 1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)}})})@@ -235,42 +235,42 @@ describe('SessionRateLimiter', () => {describe('discardPartition', () => {it('should remove all sessions for a partition', () => {const limiter = new SessionRateLimiter(10)- const session1 = 'team123$session1'- const session2 = 'team123$session2'- const session3 = 'team123$session3'+ const session1: [number, string] = [123, 'session1']+ const session2: [number, string] = [123, 'session2']+ const session3: [number, string] = [123, 'session3']- limiter.handleMessage(session1, 1, createMessage(2))- limiter.handleMessage(session2, 1, createMessage(1))- limiter.handleMessage(session3, 2, createMessage(1))+ limiter.handleMessage(...session1, 1, createMessage(2))+ limiter.handleMessage(...session2, 1, createMessage(1))+ limiter.handleMessage(...session3, 2, createMessage(1))- expect(limiter.getEventCount(session1)).toBe(2)- expect(limiter.getEventCount(session2)).toBe(1)- expect(limiter.getEventCount(session3)).toBe(1)+ expect(limiter.getEventCount(...session1)).toBe(2)+ expect(limiter.getEventCount(...session2)).toBe(1)+ expect(limiter.getEventCount(...session3)).toBe(1)limiter.discardPartition(1)- expect(limiter.getEventCount(session1)).toBe(0)- expect(limiter.getEventCount(session2)).toBe(0)- expect(limiter.getEventCount(session3)).toBe(1)+ expect(limiter.getEventCount(...session1)).toBe(0)+ expect(limiter.getEventCount(...session2)).toBe(0)+ expect(limiter.getEventCount(...session3)).toBe(1)})it('should remove limited session status for partition', () => {const limiter = new SessionRateLimiter(1)- const session1 = 'team123$session1'- const session2 = 'team123$session2'+ const session1: [number, string] = [123, 'session1']+ const session2: [number, string] = [123, 'session2']- limiter.handleMessage(session1, 1, createMessage(1))- limiter.handleMessage(session1, 1, createMessage(1))- limiter.handleMessage(session2, 2, createMessage(1))- limiter.handleMessage(session2, 2, createMessage(1))+ limiter.handleMessage(...session1, 1, createMessage(1))+ limiter.handleMessage(...session1, 1, createMessage(1))+ limiter.handleMessage(...session2, 2, createMessage(1))+ limiter.handleMessage(...session2, 2, createMessage(1))- expect(limiter.handleMessage(session1, 1, createMessage(1))).toBe(false)- expect(limiter.handleMessage(session2, 2, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session1, 1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session2, 2, createMessage(1))).toBe(false)limiter.discardPartition(1)- expect(limiter.handleMessage(session1, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(session2, 2, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session1, 1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session2, 2, createMessage(1))).toBe(false)})it('should handle discarding non-existent partition', () => {@@ -280,20 +280,20 @@ describe('SessionRateLimiter', () => {it('should allow session to restart on new partition after discard', () => {const limiter = new SessionRateLimiter(2)- const sessionKey = 'team123$session456'+ const session: [number, string] = [123, 'session456']- limiter.handleMessage(sessionKey, 1, createMessage(1))- limiter.handleMessage(sessionKey, 1, createMessage(1))- limiter.handleMessage(sessionKey, 1, createMessage(1))+ limiter.handleMessage(...session, 1, createMessage(1))+ limiter.handleMessage(...session, 1, createMessage(1))+ limiter.handleMessage(...session, 1, createMessage(1))- expect(limiter.handleMessage(sessionKey, 1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)limiter.discardPartition(1)- limiter.handleMessage(sessionKey, 2, createMessage(1))- limiter.handleMessage(sessionKey, 2, createMessage(1))- expect(limiter.getEventCount(sessionKey)).toBe(2)- expect(limiter.handleMessage(sessionKey, 2, createMessage(1))).toBe(false)+ limiter.handleMessage(...session, 2, createMessage(1))+ limiter.handleMessage(...session, 2, createMessage(1))+ expect(limiter.getEventCount(...session)).toBe(2)+ expect(limiter.handleMessage(...session, 2, createMessage(1))).toBe(false)})})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.tsindex c8941de7da6a..5c00861c986c 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.ts@@ -13,34 +13,36 @@ export class SessionRateLimiter {constructor(private readonly maxEventsPerSession: number = Number.MAX_SAFE_INTEGER) {}+ private static key(teamId: number, sessionId: string): string {+ return `${teamId}$${sessionId}`+ }+/*** Handle a message for a session- * @param sessionKey - Unique session identifier (e.g., "teamId$sessionId")- * @param partition - Partition number for this message- * @param message - The message containing events* @returns true if message should be processed, false if rate limited*/- public handleMessage(sessionKey: string, partition: number, message: ParsedMessageData): boolean {+ public handleMessage(teamId: number, sessionId: string, partition: number, message: ParsedMessageData): boolean {+ const key = SessionRateLimiter.key(teamId, sessionId)+// Count total events in the message across all windowslet eventCount = 0for (const events of Object.values(message.eventsByWindowId)) {eventCount += events.length}- const currentCount = this.eventCounts.get(sessionKey) ?? 0- const newCount = currentCount + eventCount+ const newCount = (this.eventCounts.get(key) ?? 0) + eventCount// Always increment the count and track partition- this.eventCounts.set(sessionKey, newCount)- this.sessionPartitions.set(sessionKey, partition)+ this.eventCounts.set(key, newCount)+ this.sessionPartitions.set(key, partition)- if (this.limitedSessions.has(sessionKey)) {+ if (this.limitedSessions.has(key)) {SessionBatchMetrics.incrementEventsRateLimited()return false}if (newCount > this.maxEventsPerSession) {- this.limitedSessions.add(sessionKey)+ this.limitedSessions.add(key)SessionBatchMetrics.incrementSessionsRateLimited()SessionBatchMetrics.incrementEventsRateLimited()return false@@ -52,33 +54,29 @@ export class SessionRateLimiter {/*** Get current event count for a session*/- public getEventCount(sessionKey: string): number {- return this.eventCounts.get(sessionKey) ?? 0+ public getEventCount(teamId: number, sessionId: string): number {+ return this.eventCounts.get(SessionRateLimiter.key(teamId, sessionId)) ?? 0}/*** Remove tracking for a session (used when partition is discarded)*/- public removeSession(sessionKey: string): void {- this.eventCounts.delete(sessionKey)- this.limitedSessions.delete(sessionKey)- this.sessionPartitions.delete(sessionKey)+ public removeSession(teamId: number, sessionId: string): void {+ this.removeByKey(SessionRateLimiter.key(teamId, sessionId))}/*** Discard all sessions for a given partition*/public discardPartition(partition: number): void {- const sessionsToRemove: string[] = []-- for (const [sessionKey, sessionPartition] of this.sessionPartitions.entries()) {+ const keysToRemove: string[] = []+ for (const [key, sessionPartition] of this.sessionPartitions.entries()) {if (sessionPartition === partition) {- sessionsToRemove.push(sessionKey)+ keysToRemove.push(key)}}-- for (const sessionKey of sessionsToRemove) {- this.removeSession(sessionKey)+ for (const key of keysToRemove) {+ this.removeByKey(key)}}@@ -90,4 +88,10 @@ export class SessionRateLimiter {this.limitedSessions.clear()this.sessionPartitions.clear()}++ private removeByKey(key: string): void {+ this.eventCounts.delete(key)+ this.limitedSessions.delete(key)+ this.sessionPartitions.delete(key)+ }}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/constants.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/constants.tsindex 8e2bf287b06e..6abc9727f4f2 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/constants.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/constants.ts@@ -2,7 +2,11 @@ export const ValidRetentionPeriods = ['30d', '90d', '1y', '5y'] as constexport type RetentionPeriod = (typeof ValidRetentionPeriods)[number]-export const RetentionPeriodToDaysMap: { [key in RetentionPeriod]: number | null } = {+export function isValidRetentionPeriod(retentionPeriod: string): retentionPeriod is RetentionPeriod {+ return ValidRetentionPeriods.includes(retentionPeriod as RetentionPeriod)+}++export const RetentionPeriodToDaysMap: { [key in RetentionPeriod]: number } = {'30d': 30,'90d': 90,'1y': 365,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cache/memory-cache.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cache/memory-cache.test.tsindex d9d6900cb20e..0a3dc4948983 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cache/memory-cache.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cache/memory-cache.test.ts@@ -42,9 +42,9 @@ describe('MemoryCachedKeyStore', () => {describe('generateKey', () => {it('should call delegate and cache the result', async () => {- const result = await cachedKeyStore.generateKey('session-123', 1)+ const result = await cachedKeyStore.generateKey('session-123', 1, 30)- expect(mockDelegate.generateKey).toHaveBeenCalledWith('session-123', 1)+ expect(mockDelegate.generateKey).toHaveBeenCalledWith('session-123', 1, 30)expect(result).toEqual(mockSessionKey)// Second call should use cache@@ -58,7 +58,7 @@ describe('MemoryCachedKeyStore', () => {it('should propagate delegate generateKey error', async () => {mockDelegate.generateKey.mockRejectedValue(new Error('Generate failed'))- await expect(cachedKeyStore.generateKey('session-123', 1)).rejects.toThrow('Generate failed')+ await expect(cachedKeyStore.generateKey('session-123', 1, 30)).rejects.toThrow('Generate failed')})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cache/memory-cache.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cache/memory-cache.tsindex 06c3114e4b18..a20c4c111ab1 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cache/memory-cache.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cache/memory-cache.ts@@ -26,8 +26,8 @@ export class MemoryCachedKeyStore implements KeyStore {await this.delegate.start()}- async generateKey(sessionId: string, teamId: number): Promise<SessionKey> {- const key = await this.delegate.generateKey(sessionId, teamId)+ async generateKey(sessionId: string, teamId: number, retentionDays: number): Promise<SessionKey> {+ const key = await this.delegate.generateKey(sessionId, teamId, retentionDays)this.cache.set(this.cacheKey(sessionId, teamId), key)return key}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cache/redis-cache.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cache/redis-cache.test.tsindex 368450cc84a3..a567a06e80d7 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cache/redis-cache.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cache/redis-cache.test.ts@@ -64,9 +64,9 @@ describe('RedisCachedKeyStore', () => {describe('generateKey', () => {it('should call delegate and cache in Redis', async () => {- const result = await cachedKeyStore.generateKey('session-123', 1)+ const result = await cachedKeyStore.generateKey('session-123', 1, 30)- expect(mockDelegate.generateKey).toHaveBeenCalledWith('session-123', 1)+ expect(mockDelegate.generateKey).toHaveBeenCalledWith('session-123', 1, 30)expect(mockRedisPool.acquire).toHaveBeenCalled()expect(mockRedisClient.setex).toHaveBeenCalledWith('@posthog/replay/recording-key:1:session-123',@@ -80,13 +80,13 @@ describe('RedisCachedKeyStore', () => {it('should propagate delegate generateKey error', async () => {mockDelegate.generateKey.mockRejectedValue(new Error('Generate failed'))- await expect(cachedKeyStore.generateKey('session-123', 1)).rejects.toThrow('Generate failed')+ await expect(cachedKeyStore.generateKey('session-123', 1, 30)).rejects.toThrow('Generate failed')})it('should release Redis client even if setex fails', async () => {mockRedisClient.setex.mockRejectedValue(new Error('Redis setex failed'))- await expect(cachedKeyStore.generateKey('session-123', 1)).rejects.toThrow('Redis setex failed')+ await expect(cachedKeyStore.generateKey('session-123', 1, 30)).rejects.toThrow('Redis setex failed')expect(mockRedisPool.release).toHaveBeenCalledWith(mockRedisClient)})})@@ -219,7 +219,7 @@ describe('RedisCachedKeyStore', () => {it('should use custom TTL when provided', async () => {const customTtlCachedKeyStore = new RedisCachedKeyStore(mockDelegate, mockRedisPool, 3600)- await customTtlCachedKeyStore.generateKey('session-123', 1)+ await customTtlCachedKeyStore.generateKey('session-123', 1, 30)expect(mockRedisClient.setex).toHaveBeenCalledWith('@posthog/replay/recording-key:1:session-123',diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cache/redis-cache.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cache/redis-cache.tsindex 04c3354c566f..b4dc2046ae80 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cache/redis-cache.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cache/redis-cache.ts@@ -58,8 +58,8 @@ export class RedisCachedKeyStore implements KeyStore {}}- async generateKey(sessionId: string, teamId: number): Promise<SessionKey> {- const key = await this.delegate.generateKey(sessionId, teamId)+ async generateKey(sessionId: string, teamId: number, retentionDays: number): Promise<SessionKey> {+ const key = await this.delegate.generateKey(sessionId, teamId, retentionDays)await this.setCached(sessionId, teamId, key)return key}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cleartext-keystore.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cleartext-keystore.test.tsindex 3591cff4fb94..89f6fcaf7e54 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cleartext-keystore.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cleartext-keystore.test.ts@@ -15,7 +15,7 @@ describe('CleartextKeyStore', () => {describe('generateKey', () => {it('should return empty keys with sessionState cleartext', async () => {- const result = await keyStore.generateKey('session-123', 1)+ const result = await keyStore.generateKey('session-123', 1, 30)expect(result.plaintextKey).toEqual(Buffer.alloc(0))expect(result.encryptedKey).toEqual(Buffer.alloc(0))diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cleartext-keystore.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cleartext-keystore.tsindex 40d58a45822d..a4ff9fb22232 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cleartext-keystore.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/cleartext-keystore.ts@@ -9,7 +9,7 @@ export class CleartextKeyStore implements KeyStore {return Promise.resolve()}- generateKey(_sessionId: string, _teamId: number): Promise<SessionKey> {+ generateKey(_sessionId: string, _teamId: number, _retentionDays: number): Promise<SessionKey> {return Promise.resolve({plaintextKey: Buffer.alloc(0),encryptedKey: Buffer.alloc(0),diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/dynamodb-keystore.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/dynamodb-keystore.test.tsindex 483fb0924eea..7351073e4f98 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/dynamodb-keystore.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/dynamodb-keystore.test.ts@@ -1,15 +1,12 @@import { ConditionalCheckFailedException, DynamoDBClient } from '@aws-sdk/client-dynamodb'import { KMSClient } from '@aws-sdk/client-kms'-import { RetentionService } from '~/ingestion/pipelines/sessionreplay/shared/retention/retention-service'-import { DynamoDBKeyStore } from './dynamodb-keystore'describe('DynamoDBKeyStore', () => {let keyStore: DynamoDBKeyStorelet mockDynamoDBClient: jest.Mocked<DynamoDBClient>let mockKMSClient: jest.Mocked<KMSClient>- let mockRetentionService: jest.Mocked<RetentionService>const mockPlaintextKey = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])const mockEncryptedKey = new Uint8Array([101, 102, 103, 104, 105])@@ -18,11 +15,8 @@ describe('DynamoDBKeyStore', () => {it('should create a DynamoDBKeyStore instance and initialize sodium on start', async () => {const dynamoDBClient = { send: jest.fn() } as unknown as jest.Mocked<DynamoDBClient>const kmsClient = { send: jest.fn() } as unknown as jest.Mocked<KMSClient>- const retentionService = {- getSessionRetentionDays: jest.fn(),- } as unknown as jest.Mocked<RetentionService>- const store = new DynamoDBKeyStore(dynamoDBClient, kmsClient, retentionService)+ const store = new DynamoDBKeyStore(dynamoDBClient, kmsClient)await store.start()expect(store).toBeInstanceOf(DynamoDBKeyStore)@@ -44,11 +38,7 @@ describe('DynamoDBKeyStore', () => {}),} as unknown as jest.Mocked<KMSClient>- mockRetentionService = {- getSessionRetentionDays: jest.fn().mockResolvedValue(30),- } as unknown as jest.Mocked<RetentionService>-- keyStore = new DynamoDBKeyStore(mockDynamoDBClient, mockKMSClient, mockRetentionService)+ keyStore = new DynamoDBKeyStore(mockDynamoDBClient, mockKMSClient)await keyStore.start()})@@ -58,7 +48,7 @@ describe('DynamoDBKeyStore', () => {describe('generateKey', () => {it('should generate a new key and store it in DynamoDB with condition expression', async () => {- const result = await keyStore.generateKey('session-123', 1)+ const result = await keyStore.generateKey('session-123', 1, 30)expect(mockKMSClient.send).toHaveBeenCalledTimes(1)expect(mockDynamoDBClient.send).toHaveBeenCalledTimes(1)@@ -98,17 +88,15 @@ describe('DynamoDBKeyStore', () => {.mockResolvedValueOnce({ Plaintext: mockPlaintextKey, CiphertextBlob: mockEncryptedKey }).mockResolvedValueOnce({ Plaintext: existingPlaintextKey })- const result = await keyStore.generateKey('session-123', 1)+ const result = await keyStore.generateKey('session-123', 1, 30)expect(result.plaintextKey).toEqual(Buffer.from(existingPlaintextKey))expect(result.encryptedKey).toEqual(Buffer.from(existingEncryptedKey))expect(result.sessionState).toBe('ciphertext')})- it('should calculate expiration based on retention days', async () => {- mockRetentionService.getSessionRetentionDays.mockResolvedValue(90)-- await keyStore.generateKey('session-123', 1)+ it('should calculate expiration based on the retention days it is given', async () => {+ await keyStore.generateKey('session-123', 1, 90)const dynamoCall = mockDynamoDBClient.send.mock.calls[0][0] as anyconst createdAt = Math.floor(new Date('2024-01-15T12:00:00Z').getTime() / 1000)@@ -124,19 +112,15 @@ describe('DynamoDBKeyStore', () => {CiphertextBlob: undefined,})- await expect(keyStore.generateKey('session-123', 1)).rejects.toThrow('Failed to generate data key from KMS')- })-- it('should query retention service for session retention days', async () => {- await keyStore.generateKey('session-456', 2)-- expect(mockRetentionService.getSessionRetentionDays).toHaveBeenCalledWith(2, 'session-456')+ await expect(keyStore.generateKey('session-123', 1, 30)).rejects.toThrow(+ 'Failed to generate data key from KMS'+ )})it('should throw error if DynamoDB fails to store key', async () => {;(mockDynamoDBClient.send as jest.Mock).mockRejectedValue(new Error('DynamoDB error'))- await expect(keyStore.generateKey('session-123', 1)).rejects.toThrow('DynamoDB error')+ await expect(keyStore.generateKey('session-123', 1, 30)).rejects.toThrow('DynamoDB error')})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/dynamodb-keystore.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/dynamodb-keystore.tsindex e90da35db743..92ce2dbdc0ab 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/dynamodb-keystore.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/dynamodb-keystore.ts@@ -8,7 +8,6 @@ import {import { DecryptCommand, GenerateDataKeyCommand, KMSClient } from '@aws-sdk/client-kms'import sodium from 'libsodium-wrappers'-import { RetentionService } from '~/ingestion/pipelines/sessionreplay/shared/retention/retention-service'import { DeleteKeyResult, KeyStore, SessionKey } from '~/ingestion/pipelines/sessionreplay/shared/types'const KEYS_TABLE_NAME = 'session-recording-keys'@@ -21,18 +20,16 @@ const TOMBSTONE_TTL_SECONDS = 30 * 24 * 60 * 60 // 30 daysexport class DynamoDBKeyStore implements KeyStore {constructor(private dynamoDBClient: DynamoDBClient,- private kmsClient: KMSClient,- private retentionService: RetentionService+ private kmsClient: KMSClient) {}async start(): Promise<void> {await sodium.ready}- async generateKey(sessionId: string, teamId: number): Promise<SessionKey> {- const sessionRetentionDays = await this.retentionService.getSessionRetentionDays(teamId, sessionId)+ async generateKey(sessionId: string, teamId: number, retentionDays: number): Promise<SessionKey> {const createdAt = Math.floor(Date.now() / 1000)- const expiresAt = createdAt + sessionRetentionDays * 24 * 60 * 60+ const expiresAt = createdAt + retentionDays * 24 * 60 * 60const { Plaintext, CiphertextBlob } = await this.kmsClient.send(new GenerateDataKeyCommand({diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/index.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/index.test.tsindex e55c9f55dc9e..996f4c90e26d 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/index.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/index.test.ts@@ -1,5 +1,4 @@import * as envUtils from '~/common/utils/env-utils'-import { RetentionService } from '~/ingestion/pipelines/sessionreplay/shared/retention/retention-service'import { CleartextKeyStore } from './cleartext-keystore'import { DynamoDBKeyStore } from './dynamodb-keystore'@@ -11,18 +10,10 @@ jest.mock('~/common/utils/env-utils', () => ({}))describe('getKeyStore', () => {- let mockRetentionService: jest.Mocked<RetentionService>-- beforeEach(() => {- mockRetentionService = {- getSessionRetentionDays: jest.fn().mockResolvedValue(30),- } as unknown as jest.Mocked<RetentionService>- })-it('should return DynamoDBKeyStore when running on cloud', () => {;(envUtils.isCloud as jest.Mock).mockReturnValue(true)- const keyStore = getKeyStore(mockRetentionService, 'us-east-1')+ const keyStore = getKeyStore('us-east-1')expect(keyStore).toBeInstanceOf(DynamoDBKeyStore)})@@ -30,7 +21,7 @@ describe('getKeyStore', () => {it('should return CleartextKeyStore when not running on cloud', () => {;(envUtils.isCloud as jest.Mock).mockReturnValue(false)- const keyStore = getKeyStore(mockRetentionService, 'us-east-1')+ const keyStore = getKeyStore('us-east-1')expect(keyStore).toBeInstanceOf(CleartextKeyStore)})@@ -38,7 +29,7 @@ describe('getKeyStore', () => {it('should accept custom kmsEndpoint and dynamoDBEndpoint', () => {;(envUtils.isCloud as jest.Mock).mockReturnValue(true)- const keyStore = getKeyStore(mockRetentionService, 'us-east-1', {+ const keyStore = getKeyStore('us-east-1', {kmsEndpoint: 'http://localhost:4566',dynamoDBEndpoint: 'http://localhost:4566',})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/index.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/index.tsindex c6e1d294fdc1..fa29a7b2a252 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/index.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/index.ts@@ -3,7 +3,6 @@ import { KMSClient } from '@aws-sdk/client-kms'import { isCloud } from '~/common/utils/env-utils'import { logger } from '~/common/utils/logger'-import { RetentionService } from '~/ingestion/pipelines/sessionreplay/shared/retention/retention-service'import { KeyStore } from '~/ingestion/pipelines/sessionreplay/shared/types'import { CleartextKeyStore } from './cleartext-keystore'@@ -19,7 +18,7 @@ export interface KeyStoreConfig {dynamoDBEndpoint?: string}-export function getKeyStore(retentionService: RetentionService, region: string, config?: KeyStoreConfig): KeyStore {+export function getKeyStore(region: string, config?: KeyStoreConfig): KeyStore {if (isCloud()) {logger.info('[KeyStore] Creating DynamoDBKeyStore with AWS clients', {region,@@ -36,7 +35,7 @@ export function getKeyStore(retentionService: RetentionService, region: string,endpoint: config?.dynamoDBEndpoint,})- return new DynamoDBKeyStore(dynamoDBClient, kmsClient, retentionService)+ return new DynamoDBKeyStore(dynamoDBClient, kmsClient)}logger.info('[KeyStore] Creating CleartextKeyStore (not running on cloud)')return new CleartextKeyStore()diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/memory-keystore.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/memory-keystore.test.tsindex 1f08c5c33acd..acaf9ea1cc28 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/memory-keystore.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/memory-keystore.test.ts@@ -17,7 +17,7 @@ describe('MemoryKeyStore', () => {describe('generateKey', () => {it('should generate a key with ciphertext sessionState', async () => {- const result = await keyStore.generateKey('session-123', 1)+ const result = await keyStore.generateKey('session-123', 1, 30)expect(result.sessionState).toBe('ciphertext')expect(result.plaintextKey).toBeInstanceOf(Buffer)@@ -26,22 +26,22 @@ describe('MemoryKeyStore', () => {})it('should generate different keys for different sessions', async () => {- const key1 = await keyStore.generateKey('session-1', 1)- const key2 = await keyStore.generateKey('session-2', 1)+ const key1 = await keyStore.generateKey('session-1', 1, 30)+ const key2 = await keyStore.generateKey('session-2', 1, 30)expect(key1.plaintextKey.equals(key2.plaintextKey)).toBe(false)})it('should generate different keys for different teams with same session id', async () => {- const key1 = await keyStore.generateKey('session-1', 1)- const key2 = await keyStore.generateKey('session-1', 2)+ const key1 = await keyStore.generateKey('session-1', 1, 30)+ const key2 = await keyStore.generateKey('session-1', 2, 30)expect(key1.plaintextKey.equals(key2.plaintextKey)).toBe(false)})it('should overwrite existing key when called again', async () => {- const key1 = await keyStore.generateKey('session-1', 1)- const key2 = await keyStore.generateKey('session-1', 1)+ const key1 = await keyStore.generateKey('session-1', 1, 30)+ const key2 = await keyStore.generateKey('session-1', 1, 30)expect(key1.plaintextKey.equals(key2.plaintextKey)).toBe(false)@@ -53,7 +53,7 @@ describe('MemoryKeyStore', () => {describe('getKey', () => {it('should return existing key if previously generated', async () => {- const generated = await keyStore.generateKey('session-123', 1)+ const generated = await keyStore.generateKey('session-123', 1, 30)const retrieved = await keyStore.getKey('session-123', 1)expect(retrieved.plaintextKey.equals(generated.plaintextKey)).toBe(true)@@ -70,7 +70,7 @@ describe('MemoryKeyStore', () => {})it('should return same key on subsequent calls', async () => {- await keyStore.generateKey('session-123', 1)+ await keyStore.generateKey('session-123', 1, 30)const first = await keyStore.getKey('session-123', 1)const second = await keyStore.getKey('session-123', 1)@@ -79,7 +79,7 @@ describe('MemoryKeyStore', () => {})it('should return deleted state if key was deleted', async () => {- await keyStore.generateKey('session-123', 1)+ await keyStore.generateKey('session-123', 1, 30)await keyStore.deleteKey('session-123', 1, '[email protected]')const result = await keyStore.getKey('session-123', 1)@@ -89,7 +89,7 @@ describe('MemoryKeyStore', () => {})it('should include deletedAt timestamp in deleted state', async () => {- await keyStore.generateKey('session-123', 1)+ await keyStore.generateKey('session-123', 1, 30)// Timestamps are in secondsconst beforeDelete = Math.floor(Date.now() / 1000)@@ -105,7 +105,7 @@ describe('MemoryKeyStore', () => {describe('deleteKey', () => {it('should return status deleted if key existed', async () => {- await keyStore.generateKey('session-123', 1)+ await keyStore.generateKey('session-123', 1, 30)const result = await keyStore.deleteKey('session-123', 1, '[email protected]')expect(result).toEqual({ status: 'deleted', deletedAt: expect.any(Number), deletedBy: '[email protected]' })@@ -122,7 +122,7 @@ describe('MemoryKeyStore', () => {})it('should return already_deleted with timestamp if key was already deleted', async () => {- await keyStore.generateKey('session-123', 1)+ await keyStore.generateKey('session-123', 1, 30)await keyStore.deleteKey('session-123', 1, '[email protected]')const result = await keyStore.deleteKey('session-123', 1, '[email protected]')@@ -132,7 +132,7 @@ describe('MemoryKeyStore', () => {})it('should return deleted state on subsequent getKey calls', async () => {- await keyStore.generateKey('session-123', 1)+ await keyStore.generateKey('session-123', 1, 30)await keyStore.deleteKey('session-123', 1, '[email protected]')const result = await keyStore.getKey('session-123', 1)@@ -140,8 +140,8 @@ describe('MemoryKeyStore', () => {})it('should not affect other sessions', async () => {- await keyStore.generateKey('session-1', 1)- await keyStore.generateKey('session-2', 1)+ await keyStore.generateKey('session-1', 1, 30)+ await keyStore.generateKey('session-2', 1, 30)await keyStore.deleteKey('session-1', 1, '[email protected]')@@ -155,8 +155,8 @@ describe('MemoryKeyStore', () => {})it('should not affect same session id in different teams', async () => {- await keyStore.generateKey('session-1', 1)- await keyStore.generateKey('session-1', 2)+ await keyStore.generateKey('session-1', 1, 30)+ await keyStore.generateKey('session-1', 2, 30)await keyStore.deleteKey('session-1', 1, '[email protected]')diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/memory-keystore.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/memory-keystore.tsindex 2f4775e92b6e..de7b40e87d2c 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/memory-keystore.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/keystore/memory-keystore.ts@@ -14,7 +14,7 @@ export class MemoryKeyStore implements KeyStore {await sodium.ready}- generateKey(sessionId: string, teamId: number): Promise<SessionKey> {+ generateKey(sessionId: string, teamId: number, _retentionDays: number): Promise<SessionKey> {const plaintextKey = Buffer.from(sodium.crypto_secretbox_keygen())const sessionKey: SessionKey = {plaintextKey,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/retention/retention-service.integration.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/retention/retention-service.integration.test.tsnew file mode 100644index 000000000000..c99a119ac685--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/retention/retention-service.integration.test.ts@@ -0,0 +1,87 @@+import { defaultConfig } from '~/common/config/config'+import { createIngestionRedisConnectionConfig } from '~/common/config/redis-pools'+import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'+import { createRedisPoolFromConfig } from '~/common/utils/db/redis'+import { ValidRetentionPeriods } from '~/ingestion/pipelines/sessionreplay/shared/constants'+import { SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'+import { TeamService } from '~/ingestion/pipelines/sessionreplay/shared/teams/team-service'+import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'+import { RedisPool } from '~/types'++import { RetentionService } from './retention-service'++describe('RetentionService (integration)', () => {+ let redisPool: RedisPool+ let postgres: PostgresRouter+ let teamId: number++ beforeEach(async () => {+ await resetTestDatabase()+ postgres = new PostgresRouter(defaultConfig)+ teamId = (await getFirstTeam(postgres)).id // seeded with retention '30d'++ redisPool = createRedisPoolFromConfig({+ connection: createIngestionRedisConnectionConfig(defaultConfig),+ poolMinSize: 1,+ poolMaxSize: 3,+ })+ })++ afterEach(async () => {+ await redisPool.drain()+ await redisPool.clear()+ await postgres.end()+ })++ const setTeamRetention = async (period: string): Promise<void> => {+ await postgres.query(+ PostgresUse.COMMON_WRITE,+ `UPDATE posthog_team SET session_recording_retention_period = $1 WHERE id = $2`,+ [period, teamId],+ 'test-set-retention'+ )+ }++ it('resolves via the team service on a miss, then serves the second lookup from Redis', async () => {+ const teamService = new TeamService(postgres) // team service is Postgres-backed+ const getRetentionSpy = jest.spyOn(teamService, 'getRetentionPeriodByTeamId')+ const service = new RetentionService(redisPool, teamService)+ const sessionId = `it-hit-${Date.now()}` // unique so the first lookup is a real cache miss++ const first = await service.resolveSessionRetentions(new SessionSet().add(teamId, sessionId))+ expect(first.get(teamId, sessionId)).toEqual({ resolved: true, retentionPeriod: '30d' })++ const second = await service.resolveSessionRetentions(new SessionSet().add(teamId, sessionId))+ expect(second.get(teamId, sessionId)).toEqual({ resolved: true, retentionPeriod: '30d' })++ // The team service is consulted once; the second lookup is served from Redis.+ expect(getRetentionSpy).toHaveBeenCalledTimes(1)+ })++ it('marks a session unresolvable when the team has no retention, and does not cache the miss', async () => {+ const teamService = new TeamService(postgres)+ const getRetentionSpy = jest.spyOn(teamService, 'getRetentionPeriodByTeamId')+ const service = new RetentionService(redisPool, teamService)+ const unknownTeamId = 9_999_999+ const sessionId = `it-null-${Date.now()}`++ const first = await service.resolveSessionRetentions(new SessionSet().add(unknownTeamId, sessionId))+ expect(first.get(unknownTeamId, sessionId)).toEqual({ resolved: false })++ // A null retention is not written to Redis, so the second lookup consults the team service+ // again rather than serving a stale miss from the cache.+ const second = await service.resolveSessionRetentions(new SessionSet().add(unknownTeamId, sessionId))+ expect(second.get(unknownTeamId, sessionId)).toEqual({ resolved: false })+ expect(getRetentionSpy).toHaveBeenCalledTimes(2)+ })++ // Every allowed period must resolve and round-trip through Redis; driven off the authoritative set.+ it.each([...ValidRetentionPeriods])('resolves retention %s end-to-end (team service -> Redis)', async (period) => {+ await setTeamRetention(period)+ const service = new RetentionService(redisPool, new TeamService(postgres))+ const sessionId = `it-matrix-${period}-${Date.now()}`++ const result = await service.resolveSessionRetentions(new SessionSet().add(teamId, sessionId))+ expect(result.get(teamId, sessionId)).toEqual({ resolved: true, retentionPeriod: period })+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/retention/retention-service.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/retention/retention-service.test.tsindex 493911762a67..7cebc75e9191 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/retention/retention-service.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/retention/retention-service.test.ts@@ -1,11 +1,18 @@import { Redis } from 'ioredis'+import { SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'import { TeamService } from '~/ingestion/pipelines/sessionreplay/shared/teams/team-service'import { RedisPool, TeamId } from '~/types'import { RetentionServiceMetrics } from './metrics'import { RetentionService } from './retention-service'+const sessionSet = (...pairs: [number, string][]): SessionSet => {+ const set = new SessionSet()+ pairs.forEach(([teamId, sessionId]) => set.add(teamId, sessionId))+ return set+}+jest.mock('./metrics', () => ({RetentionServiceMetrics: {incrementLookupErrors: jest.fn(),@@ -21,13 +28,16 @@ jest.mock('~/ingestion/pipelines/sessionreplay/sessions/metrics', () => ({describe('RetentionService', () => {let retentionService: RetentionServicelet mockRedisClient: jest.Mocked<Redis>+ let mockPipeline: { set: jest.Mock; exec: jest.Mock }+ let mockTeamService: jest.Mocked<TeamService>beforeEach(() => {jest.useFakeTimers()+ mockPipeline = { set: jest.fn().mockReturnThis(), exec: jest.fn().mockResolvedValue([]) }mockRedisClient = {- get: jest.fn().mockResolvedValue(null),- set: jest.fn(),+ mget: jest.fn().mockResolvedValue([]),+ pipeline: jest.fn().mockReturnValue(mockPipeline),} as unknown as jest.Mocked<Redis>const mockRedisPool = {@@ -35,13 +45,13 @@ describe('RetentionService', () => {release: jest.fn(),} as unknown as jest.Mocked<RedisPool>- const mockTeamService = {+ mockTeamService = {getRetentionPeriodByTeamId: jest.fn().mockImplementation((teamId: TeamId) => {return {1: '30d', // Valid2: '1y', // Valid3: null, // Missing- 4: 'foobar', //Invalid+ 4: 'foobar', // Invalid}[teamId]}),} as unknown as jest.Mocked<TeamService>@@ -53,85 +63,110 @@ describe('RetentionService', () => {jest.useRealTimers()})- describe('getRetentionByTeamId', () => {- it('should return retention period for valid team id 1', async () => {- const retentionPeriod = await retentionService.getRetentionByTeamId(1)- expect(retentionPeriod).toEqual('30d')- })-- it('should return retention period for valid team id 2', async () => {- const retentionPeriod = await retentionService.getRetentionByTeamId(2)- expect(retentionPeriod).toEqual('1y')+ describe('resolveSessionRetentions', () => {+ it('returns an empty map without touching Redis for an empty set', async () => {+ const results = await retentionService.resolveSessionRetentions(sessionSet())+ expect(results.size).toBe(0)+ expect(mockRedisClient.mget).not.toHaveBeenCalled()})- it('should throw error for unknown team id', async () => {- const retentionPromise = retentionService.getRetentionByTeamId(3)- await expect(retentionPromise).rejects.toThrow('Error during retention period lookup: Unknown team id 3')- })- })+ it('resolves cached hits in one MGET without hitting the team service', async () => {+ mockRedisClient.mget = jest.fn().mockResolvedValue(['30d', '1y'])- describe('getSessionRetention', () => {- it('should return retention period for valid team id 1', async () => {- const retentionPeriod = await retentionService.getSessionRetention(1, '123')- expect(retentionPeriod).toEqual('30d')- })+ const results = await retentionService.resolveSessionRetentions(sessionSet([1, 'a'], [2, 'b']))- it('should return retention period for valid team id 2', async () => {- const retentionPeriod = await retentionService.getSessionRetention(2, '321')- expect(retentionPeriod).toEqual('1y')+ expect(results.get(1, 'a')).toEqual({ resolved: true, retentionPeriod: '30d' })+ expect(results.get(2, 'b')).toEqual({ resolved: true, retentionPeriod: '1y' })+ expect(mockRedisClient.mget).toHaveBeenCalledTimes(1)+ expect(mockRedisClient.mget).toHaveBeenCalledWith([+ '@posthog/replay/session-retention-a',+ '@posthog/replay/session-retention-b',+ ])+ expect(mockTeamService.getRetentionPeriodByTeamId).not.toHaveBeenCalled()+ expect(mockPipeline.set).not.toHaveBeenCalled()})- it('should throw error for unknown team id', async () => {- const retentionPromise = retentionService.getSessionRetention(3, '456')- await expect(retentionPromise).rejects.toThrow('Error during retention period lookup: Unknown team id 3')- })-- it('should throw error for invalid retention period', async () => {- const retentionPromise = retentionService.getSessionRetention(4, '654')- await expect(retentionPromise).rejects.toThrow(- 'Error during retention period lookup: Got invalid value foobar'+ it('falls back to the team service for misses across teams, deduped per team, and caches each result', async () => {+ // sessions a and b share team 1 (→ 30d); session c is team 2 (→ 1y).+ mockRedisClient.mget = jest.fn().mockResolvedValue([null, null, null])++ const results = await retentionService.resolveSessionRetentions(sessionSet([1, 'a'], [1, 'b'], [2, 'c']))++ expect(results.get(1, 'a')).toEqual({ resolved: true, retentionPeriod: '30d' })+ expect(results.get(1, 'b')).toEqual({ resolved: true, retentionPeriod: '30d' })+ expect(results.get(2, 'c')).toEqual({ resolved: true, retentionPeriod: '1y' })+ // Three misses across two distinct teams → one team service lookup per team.+ expect(mockTeamService.getRetentionPeriodByTeamId).toHaveBeenCalledTimes(2)+ expect(mockTeamService.getRetentionPeriodByTeamId).toHaveBeenCalledWith(1)+ expect(mockTeamService.getRetentionPeriodByTeamId).toHaveBeenCalledWith(2)+ // Each resolved value is written back to its own key with a TTL.+ expect(mockPipeline.set).toHaveBeenCalledTimes(3)+ expect(mockPipeline.set).toHaveBeenCalledWith(+ '@posthog/replay/session-retention-a',+ '30d',+ 'EX',+ 24 * 60 * 60)+ expect(mockPipeline.set).toHaveBeenCalledWith(+ '@posthog/replay/session-retention-c',+ '1y',+ 'EX',+ 24 * 60 * 60+ )+ expect(mockPipeline.exec).toHaveBeenCalledTimes(1)})- it('should load retention from Redis if key exists', async () => {- mockRedisClient.get = jest.fn().mockReturnValue('30d')+ it('marks a session unresolvable (not thrown) when its team has no retention', async () => {+ mockRedisClient.mget = jest.fn().mockResolvedValue([null])- const retentionPeriod = await retentionService.getSessionRetention(1, '123')- expect(retentionPeriod).toEqual('30d')+ const results = await retentionService.resolveSessionRetentions(sessionSet([3, 'gone']))- expect(mockRedisClient.get).toHaveBeenCalledTimes(1)- expect(mockRedisClient.get).toHaveBeenCalledWith('@posthog/replay/session-retention-123')+ expect(results.get(3, 'gone')).toEqual({ resolved: false })+ expect(mockTeamService.getRetentionPeriodByTeamId).toHaveBeenCalledWith(3)+ expect(mockPipeline.set).not.toHaveBeenCalled()+ expect(RetentionServiceMetrics.incrementLookupErrors).toHaveBeenCalledTimes(1)})- it('should store retention in Redis if key does not exist', async () => {- mockRedisClient.get = jest.fn().mockReturnValue(null)+ it('throws on a corrupt cached retention value', async () => {+ mockRedisClient.mget = jest.fn().mockResolvedValue(['foobar'])- const retentionPeriod = await retentionService.getSessionRetention(1, '123')- expect(retentionPeriod).toEqual('30d')+ await expect(retentionService.resolveSessionRetentions(sessionSet([1, 'a']))).rejects.toThrow(+ "Invalid cached retention value 'foobar' for team 1 session a"+ )+ expect(mockTeamService.getRetentionPeriodByTeamId).not.toHaveBeenCalled()+ expect(mockPipeline.set).not.toHaveBeenCalled()+ })- expect(mockRedisClient.set).toHaveBeenCalledTimes(1)- expect(mockRedisClient.set).toHaveBeenCalledWith(- '@posthog/replay/session-retention-123',+ it('routes only misses to the team service and keys each result by (teamId, sessionId)', async () => {+ // session 'cached' (team 2) hits Redis; session 'miss' (team 1) misses and falls back.+ mockRedisClient.mget = jest.fn().mockResolvedValue(['1y', null])++ const results = await retentionService.resolveSessionRetentions(sessionSet([2, 'cached'], [1, 'miss']))++ expect(results.get(2, 'cached')).toEqual({ resolved: true, retentionPeriod: '1y' })+ expect(results.get(1, 'miss')).toEqual({ resolved: true, retentionPeriod: '30d' })+ // Only the miss goes to the team service; the hit does not.+ expect(mockTeamService.getRetentionPeriodByTeamId).toHaveBeenCalledWith(1)+ expect(mockTeamService.getRetentionPeriodByTeamId).not.toHaveBeenCalledWith(2)+ // Only the miss is written back to Redis.+ expect(mockPipeline.set).toHaveBeenCalledTimes(1)+ expect(mockPipeline.set).toHaveBeenCalledWith(+ '@posthog/replay/session-retention-miss','30d','EX',24 * 60 * 60)})- })- describe('metrics', () => {- it('should increment lookup errors for unknown team id', async () => {- const retentionPromise = retentionService.getSessionRetention(3, '456')- await expect(retentionPromise).rejects.toThrow('Error during retention period lookup: Unknown team id 3')- expect(RetentionServiceMetrics.incrementLookupErrors).toHaveBeenCalledTimes(1)- })+ it('propagates a Redis read failure (no team-service fallback, so the retry wrapper re-runs)', async () => {+ // Redis holds each session's locked-in retention, so we must not resolve from the+ // (current) team value on a Redis failure — fail fast and let the caller retry/crash.+ mockRedisClient.mget = jest.fn().mockRejectedValue(new Error('Command timed out'))- it('should increment lookup errors for invalid retention period', async () => {- const retentionPromise = retentionService.getSessionRetention(4, '654')- await expect(retentionPromise).rejects.toThrow(- 'Error during retention period lookup: Got invalid value foobar'+ await expect(retentionService.resolveSessionRetentions(sessionSet([1, 'a']))).rejects.toThrow(+ 'Command timed out')- expect(RetentionServiceMetrics.incrementLookupErrors).toHaveBeenCalledTimes(1)+ expect(mockTeamService.getRetentionPeriodByTeamId).not.toHaveBeenCalled()})})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/retention/retention-service.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/retention/retention-service.tsindex a7b10b4c4032..6aee9fa8e513 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/retention/retention-service.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/retention/retention-service.ts@@ -1,17 +1,18 @@import { SessionBatchMetrics } from '~/ingestion/pipelines/sessionreplay/sessions/metrics'-import {- RetentionPeriod,- RetentionPeriodToDaysMap,- ValidRetentionPeriods,-} from '~/ingestion/pipelines/sessionreplay/shared/constants'+import { RetentionPeriod, isValidRetentionPeriod } from '~/ingestion/pipelines/sessionreplay/shared/constants'+import { SessionMap, SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'import { TeamService } from '~/ingestion/pipelines/sessionreplay/shared/teams/team-service'import { RedisPool, TeamId } from '~/types'import { RetentionServiceMetrics } from './metrics'-function isValidRetentionPeriod(retentionPeriod: string): retentionPeriod is RetentionPeriod {- return ValidRetentionPeriods.includes(retentionPeriod as RetentionPeriod)-}+/**+ * Outcome of resolving one session's retention. `resolved: false` is the expected, permanent+ * "can't determine retention" case (deleted/unknown team, invalid stored value) — the caller drops+ * that session. A transient failure (e.g. Redis unavailable) is thrown, not returned, so a retry+ * wrapper can re-run the lookup.+ */+export type RetentionResolution = { resolved: true; retentionPeriod: RetentionPeriod } | { resolved: false }export class RetentionService {constructor(@@ -24,58 +25,77 @@ export class RetentionService {return `${this.keyPrefix}session-retention-${sessionId}`}- public async getRetentionByTeamId(teamId: TeamId): Promise<RetentionPeriod> {- const retentionPeriod = await this.teamService.getRetentionPeriodByTeamId(teamId)-- if (retentionPeriod === null) {- RetentionServiceMetrics.incrementLookupErrors()- throw new Error(`Error during retention period lookup: Unknown team id ${teamId}`)+ /**+ * Resolves retention for a set of sessions (already deduped by `(teamId, sessionId)`). Cache hits+ * come from one Redis MGET; misses fall back to the team service (Postgres-backed) — one lookup+ * per distinct team — and are written back to Redis in a single pipeline. Returns a+ * {@link SessionMap} keyed by `(teamId, sessionId)`. Permanent failures map to `{ resolved: false }`;+ * a transient Redis or team service failure throws so the caller's retry wrapper can re-run the+ * whole lookup.+ */+ public async resolveSessionRetentions(sessions: SessionSet): Promise<SessionMap<RetentionResolution>> {+ const resolutions = new SessionMap<RetentionResolution>()+ if (sessions.size === 0) {+ return resolutions}- return retentionPeriod- }-- public async getSessionRetention(teamId: TeamId, sessionId: string): Promise<RetentionPeriod> {- let retentionPeriod: string | null = null+ const unique = [...sessions]const startTime = performance.now()const client = await this.redisPool.acquire()- const redisKey = this.generateRedisKey(sessionId)-try {- // Attempt to look up the retention period for the session in Redis- retentionPeriod = await client.get(redisKey)+ const redisKeys = unique.map(({ sessionId }) => this.generateRedisKey(sessionId))+ const cached = await client.mget(redisKeys)++ const missIndexes: number[] = []+ for (let i = 0; i < unique.length; i++) {+ const { teamId, sessionId } = unique[i]+ const value = cached[i]+ if (value === null) {+ missIndexes.push(i)+ } else if (isValidRetentionPeriod(value)) {+ resolutions.set(teamId, sessionId, { resolved: true, retentionPeriod: value })+ } else {+ // A retention value the cache should never hold — crash rather than record with a+ // wrong retention. Thrown without isRetriable so it propagates and takes the+ // consumer down (same stance as an invalid value from the team service).+ throw new Error(`Invalid cached retention value '${value}' for team ${teamId} session ${sessionId}`)+ }+ }- // ...if no retention period exists for the session- if (retentionPeriod === null) {- // ...get the value from Postgres- retentionPeriod = await this.getRetentionByTeamId(teamId)+ if (missIndexes.length > 0) {+ // One team service lookup per distinct team, resolved concurrently, not per session.+ const teamRetentions = new Map<TeamId, RetentionPeriod | null>()+ await Promise.all(+ [...new Set(missIndexes.map((i) => unique[i].teamId))].map(async (teamId) => {+ teamRetentions.set(teamId, await this.teamService.getRetentionPeriodByTeamId(teamId))+ })+ )- // ...and then set it in Redis for future batches, with a TTL of 24 hours- await client.set(redisKey, retentionPeriod, 'EX', 24 * 60 * 60)+ const writeBack = client.pipeline()+ let hasWriteBack = false+ for (const i of missIndexes) {+ const { teamId, sessionId } = unique[i]+ const retentionPeriod = teamRetentions.get(teamId) ?? null+ if (retentionPeriod === null) {+ RetentionServiceMetrics.incrementLookupErrors()+ resolutions.set(teamId, sessionId, { resolved: false })+ } else {+ resolutions.set(teamId, sessionId, { resolved: true, retentionPeriod })+ // Cache for future batches, with a TTL of 24 hours.+ writeBack.set(redisKeys[i], retentionPeriod, 'EX', 24 * 60 * 60)+ hasWriteBack = true+ }+ }+ if (hasWriteBack) {+ await writeBack.exec()+ }}++ return resolutions} finally {await this.redisPool.release(client)SessionBatchMetrics.observeRetentionRedisLatency((performance.now() - startTime) / 1000)}-- if (retentionPeriod !== null && isValidRetentionPeriod(retentionPeriod)) {- return retentionPeriod- } else {- RetentionServiceMetrics.incrementLookupErrors()- throw new Error(`Error during retention period lookup: Got invalid value ${retentionPeriod}`)- }- }-- public async getSessionRetentionDays(teamId: TeamId, sessionId: string): Promise<number> {- const retentionPeriod = await this.getSessionRetention(teamId, sessionId)- const retentionPeriodDays = RetentionPeriodToDaysMap[retentionPeriod]-- if (retentionPeriodDays !== null) {- return retentionPeriodDays- } else {- RetentionServiceMetrics.incrementLookupErrors()- throw new Error(`Error during retention period lookup: Got invalid value ${retentionPeriod}`)- }}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/session-map.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/session-map.test.tsnew file mode 100644index 000000000000..7c613f71f352--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/session-map.test.ts@@ -0,0 +1,47 @@+import { SessionMap, SessionSet } from './session-map'++describe('session-map', () => {+ describe('SessionMap', () => {+ it('looks a value up by a freshly-built (teamId, sessionId) pair', () => {+ const map = new SessionMap<string>()+ map.set(1, 'a', 'x')++ // A different call site builds a new pair — a plain Map keyed by object would miss this.+ expect(map.get(1, 'a')).toBe('x')+ })++ it('scopes by team, so the same session id under another team is distinct', () => {+ const map = new SessionMap<string>()+ map.set(1, 'shared', 'one')+ map.set(2, 'shared', 'two')++ expect(map.get(1, 'shared')).toBe('one')+ expect(map.get(2, 'shared')).toBe('two')+ expect(map.size).toBe(2)+ })++ it('returns undefined for an absent pair and supports has/delete', () => {+ const map = new SessionMap<string>()+ map.set(1, 'a', 'x')++ expect(map.get(1, 'b')).toBeUndefined()+ expect(map.has(1, 'a')).toBe(true)+ expect(map.delete(1, 'a')).toBe(true)+ expect(map.has(1, 'a')).toBe(false)+ expect(map.size).toBe(0)+ })+ })++ describe('SessionSet', () => {+ it('dedupes repeated pairs and iterates the distinct ones', () => {+ const set = new SessionSet()+ set.add(1, 'a').add(1, 'a').add(2, 'a')++ expect(set.size).toBe(2)+ expect([...set]).toEqual([+ { teamId: 1, sessionId: 'a' },+ { teamId: 2, sessionId: 'a' },+ ])+ })+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/session-map.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/session-map.tsnew file mode 100644index 000000000000..e2f4587c4652--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/session-map.ts@@ -0,0 +1,62 @@+/**+ * Collections keyed by a `(teamId, sessionId)` pair.+ *+ * A plain `Map`/`Set` keys objects by reference, so it can't look a session up by a freshly-built+ * pair. These wrap a `Map` with a composite string key and keep that encoding private, so callers+ * pass `(teamId, sessionId)` and never depend on the key format. Safe because `teamId` is numeric and+ * `sessionId` is capture-restricted to `[A-Za-z0-9-]`, so the `:` separator can't be ambiguous.+ */++function encode(teamId: number, sessionId: string): string {+ return `${teamId}:${sessionId}`+}++export class SessionMap<V> {+ private readonly byKey = new Map<string, V>()++ get(teamId: number, sessionId: string): V | undefined {+ return this.byKey.get(encode(teamId, sessionId))+ }++ set(teamId: number, sessionId: string, value: V): this {+ this.byKey.set(encode(teamId, sessionId), value)+ return this+ }++ has(teamId: number, sessionId: string): boolean {+ return this.byKey.has(encode(teamId, sessionId))+ }++ delete(teamId: number, sessionId: string): boolean {+ return this.byKey.delete(encode(teamId, sessionId))+ }++ get size(): number {+ return this.byKey.size+ }++ values(): IterableIterator<V> {+ return this.byKey.values()+ }+}++export class SessionSet implements Iterable<{ teamId: number; sessionId: string }> {+ private readonly sessions = new SessionMap<{ teamId: number; sessionId: string }>()++ add(teamId: number, sessionId: string): this {+ this.sessions.set(teamId, sessionId, { teamId, sessionId })+ return this+ }++ has(teamId: number, sessionId: string): boolean {+ return this.sessions.has(teamId, sessionId)+ }++ get size(): number {+ return this.sessions.size+ }++ [Symbol.iterator](): Iterator<{ teamId: number; sessionId: string }> {+ return this.sessions.values()+ }+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.integration.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.integration.test.tsnew file mode 100644index 000000000000..6063adb2390a--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.integration.test.ts@@ -0,0 +1,46 @@+import { defaultConfig } from '~/common/config/config'+import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'+import { ValidRetentionPeriods } from '~/ingestion/pipelines/sessionreplay/shared/constants'+import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'++import { TeamService } from './team-service'++describe('TeamService (integration)', () => {+ let postgres: PostgresRouter+ let teamId: number+ let apiToken: string++ beforeEach(async () => {+ await resetTestDatabase()+ postgres = new PostgresRouter(defaultConfig)+ const team = await getFirstTeam(postgres)+ teamId = team.id+ apiToken = team.api_token+ })++ afterEach(async () => {+ await postgres.end()+ })++ // Driven off the authoritative allowed set: every period Postgres is allowed to hold must store+ // and deserialize, and a newly added period is covered here automatically.+ it.each([...ValidRetentionPeriods])(+ 'stores and deserializes retention period %s from a real Postgres row',+ async (period) => {+ await postgres.query(+ PostgresUse.COMMON_WRITE,+ `UPDATE posthog_team SET session_recording_retention_period = $1 WHERE id = $2`,+ [period, teamId],+ 'test-set-retention'+ )+ const teamService = new TeamService(postgres)++ expect(await teamService.getRetentionPeriodByTeamId(teamId)).toBe(period)+ }+ )++ it('deserializes the team token', async () => {+ const teamService = new TeamService(postgres)+ expect(await teamService.getTeamByToken(apiToken)).toMatchObject({ teamId })+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.test.tsindex 574c6e5c620f..c758cbdd12fb 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.test.ts@@ -165,5 +165,15 @@ describe('TeamService', () => {const retention = await teamService.getRetentionPeriodByTeamId(999)expect(retention).toBeNull()})++ it('should throw when the stored retention value is not a valid period', async () => {+ fetchSpy.mockResolvedValue({+ tokenMap: {},+ retentionMap: { 7: 'forever' },+ })+ await expect(teamService.getRetentionPeriodByTeamId(7)).rejects.toThrow(+ "Invalid session_recording_retention_period 'forever' for team 7"+ )+ })})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.tsindex baf9f6f89556..95c1bc53d7d9 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts@@ -1,7 +1,7 @@import { BackgroundRefresher } from '~/common/utils/background-refresher'import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'import { logger } from '~/common/utils/logger'-import { RetentionPeriod } from '~/ingestion/pipelines/sessionreplay/shared/constants'+import { RetentionPeriod, isValidRetentionPeriod } from '~/ingestion/pipelines/sessionreplay/shared/constants'import { Team, TeamId } from '~/types'import { TeamServiceMetrics } from './metrics'@@ -9,7 +9,8 @@ import { TeamForReplay } from './types'interface TeamServiceData {tokenMap: Record<string, TeamForReplay>- retentionMap: Record<TeamId, RetentionPeriod>+ // The raw DB value; validated to a RetentionPeriod on read in getRetentionPeriodByTeamId.+ retentionMap: Record<TeamId, string>}export class TeamService {@@ -45,6 +46,12 @@ export class TeamService {if (retentionPeriod === undefined) {return null}+ if (!isValidRetentionPeriod(retentionPeriod)) {+ // A retention value the DB should never hold — crash rather than record with a wrong+ // (or silently dropped) retention. Thrown without isRetriable so it is not retried into+ // a DLQ but propagates and takes the consumer down.+ throw new Error(`Invalid session_recording_retention_period '${retentionPeriod}' for team ${teamId}`)+ }return retentionPeriod}@@ -58,7 +65,7 @@ export async function fetchTeamTokensWithRecordings(client: PostgresRouter): Proconst selectResult = await client.query<{capture_console_log_opt_in: boolean- session_recording_retention_period: RetentionPeriod+ session_recording_retention_period: stringis_ai_training_opted_in: boolean} & Pick<Team, 'id' | 'api_token'>>(@@ -95,7 +102,7 @@ export async function fetchTeamTokensWithRecordings(client: PostgresRouter): Proacc[row.id] = row.session_recording_retention_periodreturn acc},- {} as Record<TeamId, RetentionPeriod>+ {} as Record<TeamId, string>)TeamServiceMetrics.incrementRefreshCount()diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/types.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/types.tsindex 8eb3e5fb5d35..7315c9ce2ca2 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/types.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/types.ts@@ -58,7 +58,7 @@ export type DeleteKeyResult =export interface KeyStore {start(): Promise<void>/** Generate and store a new encryption key for a session */- generateKey(sessionId: string, teamId: number): Promise<SessionKey>+ generateKey(sessionId: string, teamId: number, retentionDays: number): Promise<SessionKey>/** Retrieve the encryption key for a session */getKey(sessionId: string, teamId: number): Promise<SessionKey>/** Delete a session's key (crypto-shredding) */diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.test.tsindex 9c24c8fbc1ef..d9a243e248b1 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.test.ts@@ -1,12 +1,12 @@import { PipelineResultType } from '~/ingestion/framework/results'import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'-import { createTestEventHeaders } from '~/tests/helpers/event-headers'import { TeamFilterStepInput, TeamTokenResolver, createTeamFilterStep } from './team-filter-step'describe('createTeamFilterStep', () => {- const createInput = (token?: string): TeamFilterStepInput => ({- headers: createTestEventHeaders({ token }),+ // Headers are guaranteed by the upstream validate step, so they're always present here.+ const createInput = (token: string): TeamFilterStepInput => ({+ headers: { token, session_id: 'session-1', distinct_id: 'distinct-1' },})const defaultTeam: TeamForReplay = {@@ -32,24 +32,6 @@ describe('createTeamFilterStep', () => {}})- it('should DLQ message when token is missing', async () => {- const mockTeamService: TeamTokenResolver = {- getTeamByToken: jest.fn(),- getRetentionPeriodByTeamId: jest.fn(),- }-- const step = createTeamFilterStep(mockTeamService)- const input = createInput(undefined)-- const result = await step(input)-- expect(result.type).toBe(PipelineResultType.DLQ)- if (result.type === PipelineResultType.DLQ) {- expect(result.reason).toBe('no_token_in_header')- }- expect(mockTeamService.getTeamByToken).not.toHaveBeenCalled()- })-it('should drop message when team is not found', async () => {const mockTeamService: TeamTokenResolver = {getTeamByToken: jest.fn().mockResolvedValue(null),diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.tsindex 4d297d613ec3..e6c0158d7eec 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.ts@@ -1,13 +1,14 @@-import { dlq, drop, ok } from '~/ingestion/framework/results'+import { drop, ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'import { TeamService } from '~/ingestion/pipelines/sessionreplay/shared/teams/team-service'import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'-import { EventHeaders } from '~/types'++import { SessionReplayHeaders } from './validate-headers-step'export type TeamTokenResolver = Pick<TeamService, 'getTeamByToken' | 'getRetentionPeriodByTeamId'>export interface TeamFilterStepInput {- headers: EventHeaders+ headers: SessionReplayHeaders}export interface TeamFilterStepOutput {@@ -19,7 +20,6 @@ export interface TeamFilterStepOutput {* This step is additive - it preserves all input properties and adds team context.** Error handling:- * - DLQ: Missing token (capture should always add this, indicates a bug)* - DROP: Team not found or disabled (intentional business logic)* - DROP: Missing retention period (team configuration issue)*/@@ -29,13 +29,7 @@ export function createTeamFilterStep<T extends TeamFilterStepInput>(return async function teamFilterStep(input) {const { headers } = input- const token = headers.token- if (!token) {- // DLQ: Capture should always add a token header. Missing token indicates a bug.- return dlq('no_token_in_header')- }-- const team = await teamService.getTeamByToken(token)+ const team = await teamService.getTeamByToken(headers.token)if (!team) {// DROP: Team doesn't exist or has session recording disabledreturn drop('header_token_present_team_missing_or_disabled')diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/validate-headers-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/validate-headers-step.test.tsnew file mode 100644index 000000000000..8e7ea0959157--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/validate-headers-step.test.ts@@ -0,0 +1,55 @@+import { PipelineResultType, isOkResult } from '~/ingestion/framework/results'+import { createTestEventHeaders } from '~/tests/helpers/event-headers'+import { EventHeaders } from '~/types'++import { createValidateSessionReplayHeadersStep } from './validate-headers-step'++describe('createValidateSessionReplayHeadersStep', () => {+ const step = createValidateSessionReplayHeadersStep()++ it('narrows headers to the guaranteed fields and drops the rest, preserving other input', async () => {+ const step = createValidateSessionReplayHeadersStep<{ marker: string; headers: EventHeaders }>()+ const input = {+ marker: 'preserved',+ headers: createTestEventHeaders({ token: 'tok', session_id: 'sess-1', distinct_id: 'user-1' }),+ }++ const result = await step(input)++ expect(isOkResult(result)).toBe(true)+ if (isOkResult(result)) {+ expect(result.value.marker).toBe('preserved')+ // Only the guaranteed replay headers survive — the wide EventHeaders fields are dropped.+ expect(result.value.headers).toEqual({ token: 'tok', session_id: 'sess-1', distinct_id: 'user-1' })+ }+ })++ it('normalizes a UUID session_id to its canonical (lowercase) form', async () => {+ const result = await step({+ headers: createTestEventHeaders({+ token: 'tok',+ session_id: '0192E72A-1DD2-7714-8000-8B3E4C123456',+ distinct_id: 'user-1',+ }),+ })++ expect(isOkResult(result)).toBe(true)+ if (isOkResult(result)) {+ expect(result.value.headers.session_id).toBe('0192e72a-1dd2-7714-8000-8b3e4c123456')+ }+ })++ // Capture guarantees all three headers, so a missing one is an upstream bug → DLQ.+ it.each([+ { missing: 'token', headers: { session_id: 'sess-1', distinct_id: 'user-1' }, reason: 'no_token_in_header' },+ { missing: 'session_id', headers: { token: 'tok', distinct_id: 'user-1' }, reason: 'no_session_id_in_header' },+ { missing: 'distinct_id', headers: { token: 'tok', session_id: 'sess-1' }, reason: 'no_distinct_id_in_header' },+ ])('DLQs when the $missing header is missing', async ({ headers, reason }) => {+ const result = await step({ headers: createTestEventHeaders(headers) })++ expect(result.type).toBe(PipelineResultType.DLQ)+ if (result.type === PipelineResultType.DLQ) {+ expect(result.reason).toBe(reason)+ }+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/validate-headers-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/validate-headers-step.tsnew file mode 100644index 000000000000..9cd31fc0aab3--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/validate-headers-step.ts@@ -0,0 +1,52 @@+import { normalizeSessionId } from '~/common/utils/utils'+import { dlq, ok } from '~/ingestion/framework/results'+import { ProcessingStep } from '~/ingestion/framework/steps'+import { EventHeaders } from '~/types'++/**+ * The message headers a session replay message is guaranteed to carry and that the pipeline consumes.+ * These are exactly the fields capture sets for the replay path (see `rust/capture/src/events/recordings.rs`),+ * narrowed to their required, non-optional form — downstream steps take this instead of the wide,+ * all-optional {@link EventHeaders} so they can read them without re-checking. `session_id` is+ * normalized here so every downstream step (retention keys, batch lookup, parse) keys on the same+ * canonical form the record path uses.+ */+export interface SessionReplayHeaders {+ token: string+ session_id: string+ distinct_id: string+}++export interface ValidateSessionReplayHeadersStepInput {+ headers: EventHeaders+}++/**+ * Validates that a session replay message carries the headers capture guarantees, and replaces the+ * wide header object with the narrowed {@link SessionReplayHeaders} so downstream steps can trust them.+ *+ * Capture's recordings handler rejects a snapshot before it reaches Kafka unless it has a token, a+ * valid `session_id`, and a `distinct_id` (see `rust/capture/src/events/recordings.rs`), so their+ * absence here indicates a bug upstream rather than bad user input — such messages are sent to the DLQ.+ */+export function createValidateSessionReplayHeadersStep<+ T extends ValidateSessionReplayHeadersStepInput,+>(): ProcessingStep<T, Omit<T, 'headers'> & { headers: SessionReplayHeaders }> {+ return async function validateReplayHeadersStep(input) {+ const { token, session_id, distinct_id } = input.headers++ if (!token) {+ return dlq('no_token_in_header')+ }+ if (!session_id) {+ return dlq('no_session_id_in_header')+ }+ if (!distinct_id) {+ return dlq('no_distinct_id_in_header')+ }++ return Promise.resolve(+ ok({ ...input, headers: { token, session_id: normalizeSessionId(session_id), distinct_id } })+ )+ }+}diff --git a/nodejs/src/servers/ingestion-session-replay-server.ts b/nodejs/src/servers/ingestion-session-replay-server.tsindex a18e175a52fe..0602d185745d 100644--- a/nodejs/src/servers/ingestion-session-replay-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-server.ts@@ -63,10 +63,17 @@ export function buildSessionReplayRedisPools(config: IngestionSessionReplayServeconnection: config.POSTHOG_SESSION_RECORDING_REDIS_HOST? {url: config.POSTHOG_SESSION_RECORDING_REDIS_HOST,- options: { port: config.POSTHOG_SESSION_RECORDING_REDIS_PORT ?? 6379 },+ options: {+ port: config.POSTHOG_SESSION_RECORDING_REDIS_PORT ?? 6379,+ commandTimeout: config.SESSION_RECORDING_REDIS_TIMEOUT_MS,+ },name: 'session-recording-redis',}- : { url: config.REDIS_URL, name: 'session-recording-redis-fallback' },+ : {+ url: config.REDIS_URL,+ options: { commandTimeout: config.SESSION_RECORDING_REDIS_TIMEOUT_MS },+ name: 'session-recording-redis-fallback',+ },poolMinSize: config.REDIS_POOL_MIN_SIZE,poolMaxSize: config.REDIS_POOL_MAX_SIZE,})diff --git a/nodejs/src/session-replay/recording-api/recording-api.test.ts b/nodejs/src/session-replay/recording-api/recording-api.test.tsindex ca1b09d5189e..747eab56e968 100644--- a/nodejs/src/session-replay/recording-api/recording-api.test.ts+++ b/nodejs/src/session-replay/recording-api/recording-api.test.ts@@ -8,7 +8,6 @@ import { PostgresRouter } from '~/common/utils/db/postgres'import { getBlockDecryptor } from '~/ingestion/pipelines/sessionreplay/shared/crypto'import { getKeyStore } from '~/ingestion/pipelines/sessionreplay/shared/keystore'import { ReplayEventsOutput, SessionFeaturesOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'-import { RetentionService } from '~/ingestion/pipelines/sessionreplay/shared/retention/retention-service'import { RecordingApi } from './recording-api'import { RecordingService } from './recording-service'@@ -130,7 +129,7 @@ describe('RecordingApi', () => {endpoint: undefined,forcePathStyle: undefined,})- expect(getKeyStore).toHaveBeenCalledWith(expect.any(RetentionService), 'us-west-2', {+ expect(getKeyStore).toHaveBeenCalledWith('us-west-2', {kmsEndpoint: undefined,dynamoDBEndpoint: undefined,})diff --git a/nodejs/src/session-replay/recording-api/recording-api.ts b/nodejs/src/session-replay/recording-api/recording-api.tsindex 8836900638f7..a147cf27e144 100644--- a/nodejs/src/session-replay/recording-api/recording-api.ts+++ b/nodejs/src/session-replay/recording-api/recording-api.ts@@ -14,8 +14,6 @@ import { getKeyStore } from '~/ingestion/pipelines/sessionreplay/shared/keystoreimport { RedisCachedKeyStore } from '~/ingestion/pipelines/sessionreplay/shared/keystore/cache'import { SessionMetadataStore } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-metadata-store'import { ReplayEventsOutput, SessionFeaturesOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'-import { RetentionService } from '~/ingestion/pipelines/sessionreplay/shared/retention/retention-service'-import { TeamService } from '~/ingestion/pipelines/sessionreplay/shared/teams/team-service'import { HealthCheckResult, HealthCheckResultError, HealthCheckResultOk, PluginServerService, RedisPool } from '~/types'import { RecordingService } from './recording-service'@@ -85,7 +83,6 @@ export class RecordingApi {this.s3Client = new S3Client(s3Config)- const teamService = new TeamService(this.postgres)this.redisPool = createRedisPoolFromConfig({connection: {url: this.config.SESSION_RECORDING_API_REDIS_HOST,@@ -95,9 +92,8 @@ export class RecordingApi {poolMinSize: this.config.REDIS_POOL_MIN_SIZE,poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,})- const retentionService = new RetentionService(this.redisPool, teamService)- const keyStore: KeyStore = getKeyStore(retentionService, s3Region, {+ const keyStore: KeyStore = getKeyStore(s3Region, {kmsEndpoint: this.config.SESSION_RECORDING_KMS_ENDPOINT,dynamoDBEndpoint: this.config.SESSION_RECORDING_DYNAMODB_ENDPOINT,})diff --git a/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-batch-file-format.integration.test.ts b/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-batch-file-format.integration.test.tsindex b80ac24a18b5..b9ae11c5a680 100644--- a/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-batch-file-format.integration.test.ts+++ b/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-batch-file-format.integration.test.ts@@ -260,7 +260,7 @@ describe('session recording integration', () => {// Record all messagesfor (const message of messages) {- await recorder.record(message)+ await recorder.record(message, '30d')}// Flush and get metadatadiff --git a/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-encryption.integration.test.ts b/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-encryption.integration.test.tsindex bcfdbef92eaa..d066f9850b48 100644--- a/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-encryption.integration.test.ts+++ b/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-encryption.integration.test.ts@@ -231,7 +231,7 @@ describe('session recording encryption integration', () => {]const message = createMessage(sessionId, teamId, originalEvents)- await recorder.record(message)+ await recorder.record(message, '30d')const metadata = await recorder.flush()expect(metadata).toHaveLength(1)@@ -269,7 +269,7 @@ describe('session recording encryption integration', () => {const message1 = createMessage(sessionId, teamId, [{ type: EventType.FullSnapshot, data: { source: 1, snapshot: { html: '<div>Block 1</div>' } } },])- await recorder.record(message1)+ await recorder.record(message1, '30d')const metadata1 = await recorder.flush()const encryptedBlock1 = readEncryptedBlockFromBatch(metadata1[0])@@ -294,7 +294,7 @@ describe('session recording encryption integration', () => {const message2 = createMessage(sessionId, teamId, [{ type: EventType.IncrementalSnapshot, data: { source: 2, mutations: [{ id: 2 }] } },])- await recorder.record(message2)+ await recorder.record(message2, '30d')const metadata2 = await recorder.flush()const encryptedBlock2 = readEncryptedBlockFromBatch(metadata2[0])@@ -319,7 +319,7 @@ describe('session recording encryption integration', () => {const message = createMessage(sessionId, teamId, [{ type: EventType.FullSnapshot, data: { source: 1, snapshot: { html: '<div>Secret</div>' } } },])- await recorder.record(message)+ await recorder.record(message, '30d')const metadata = await recorder.flush()const encryptedBlock = readEncryptedBlockFromBatch(metadata[0])@@ -344,7 +344,7 @@ describe('session recording encryption integration', () => {const message = createMessage(sessionId, teamId, [{ type: EventType.FullSnapshot, data: { source: 1, snapshot: { html: `<div>${sessionId}</div>` } } },])- await recorder.record(message)+ await recorder.record(message, '30d')}const metadata = await recorder.flush()diff --git a/nodejs/tests/session-replay/recording-api/recording-api.integration.test.ts b/nodejs/tests/session-replay/recording-api/recording-api.integration.test.tsindex dba79bdd377f..8e641fec592e 100644--- a/nodejs/tests/session-replay/recording-api/recording-api.integration.test.ts+++ b/nodejs/tests/session-replay/recording-api/recording-api.integration.test.ts@@ -118,7 +118,7 @@ describe('Recording API encryption integration', () => {]// Generate key first (simulates ingestion creating the key)- const sessionKey = await keyStore.generateKey(sessionId, teamId)+ const sessionKey = await keyStore.generateKey(sessionId, teamId, 30)const blockData = await createBlockData(originalEvents)const { data: encrypted } = encryptor.encryptBlockWithKey(sessionId, teamId, blockData, sessionKey)@@ -153,7 +153,7 @@ describe('Recording API encryption integration', () => {const blockData = await createBlockData([{ type: 2, data: { content: 'same content' } }])// Generate key first- const sessionKey = await keyStore.generateKey(sessionId, teamId)+ const sessionKey = await keyStore.generateKey(sessionId, teamId, 30)const { data: encrypted1 } = encryptor.encryptBlockWithKey(sessionId, teamId, blockData, sessionKey)const { data: encrypted2 } = encryptor.encryptBlockWithKey(sessionId, teamId, blockData, sessionKey)@@ -180,8 +180,8 @@ describe('Recording API encryption integration', () => {const timestamp = Date.now()// Generate keys for both sessions- const keyA = await keyStore.generateKey(`session-a-${timestamp}`, 42)- const keyB = await keyStore.generateKey(`session-b-${timestamp}`, 42)+ const keyA = await keyStore.generateKey(`session-a-${timestamp}`, 42, 30)+ const keyB = await keyStore.generateKey(`session-b-${timestamp}`, 42, 30)const { data: encrypted1 } = encryptor.encryptBlockWithKey(`session-a-${timestamp}`,@@ -218,8 +218,8 @@ describe('Recording API encryption integration', () => {const blockData = await createBlockData([{ type: 2, data: { content: 'content' } }])// Generate keys for both teams- const key1 = await keyStore.generateKey(sessionId, 1)- const key2 = await keyStore.generateKey(sessionId, 2)+ const key1 = await keyStore.generateKey(sessionId, 1, 30)+ const key2 = await keyStore.generateKey(sessionId, 2, 30)const { data: encryptedTeam1 } = encryptor.encryptBlockWithKey(sessionId, 1, blockData, key1)const { data: encryptedTeam2 } = encryptor.encryptBlockWithKey(sessionId, 2, blockData, key2)@@ -249,7 +249,7 @@ describe('Recording API encryption integration', () => {const blockData = await createBlockData([{ type: 2, data: { secret: 'sensitive data' } }])// Generate key first- const sessionKey = await keyStore.generateKey(sessionId, teamId)+ const sessionKey = await keyStore.generateKey(sessionId, teamId, 30)// Encryptconst { data: encrypted } = encryptor.encryptBlockWithKey(sessionId, teamId, blockData, sessionKey)@@ -279,7 +279,7 @@ describe('Recording API encryption integration', () => {const teamId = 42// Generate key first- await keyStore.generateKey(sessionId, teamId)+ await keyStore.generateKey(sessionId, teamId, 30)// Delete and capture time (timestamps are in seconds)const beforeDelete = Math.floor(Date.now() / 1000)@@ -302,7 +302,7 @@ describe('Recording API encryption integration', () => {const blockData = await createBlockData([{ type: 2, data: { content: 'content' } }])// Generate and delete key- await keyStore.generateKey(sessionId, teamId)+ await keyStore.generateKey(sessionId, teamId, 30)await keyStore.deleteKey(sessionId, teamId, '[email protected]')// Encryption should fail@@ -336,7 +336,7 @@ describe('Recording API encryption integration', () => {// Generate keys and encrypt all sessionsfor (const sessionId of sessions) {- const sessionKey = await keyStore.generateKey(sessionId, teamId)+ const sessionKey = await keyStore.generateKey(sessionId, teamId, 30)const blockData = await createBlockData([{ type: 2, data: { session: sessionId } }])encrypted[sessionId] = encryptor.encryptBlockWithKey(sessionId, teamId, blockData, sessionKey).data}@@ -371,7 +371,7 @@ describe('Recording API encryption integration', () => {const teamId = 42// Generate key first- const sessionKey = await keyStore.generateKey(sessionId, teamId)+ const sessionKey = await keyStore.generateKey(sessionId, teamId, 30)// Create large events (100 events with substantial data)const largeEvents = Array.from({ length: 100 }, (_, i) => ({@@ -458,10 +458,6 @@ describe('Recording API encryption integration', () => {let encryptor: SodiumRecordingEncryptorlet decryptor: SodiumRecordingDecryptor- const mockRetentionService = {- getSessionRetentionDays: jest.fn().mockResolvedValue(30),- }-async function setupKmsKey(): Promise<void> {try {const describeResult = await kmsClient.send(new DescribeKeyCommand({ KeyId: KMS_KEY_ALIAS }))@@ -580,7 +576,7 @@ describe('Recording API encryption integration', () => {})beforeEach(async () => {- keyStore = new DynamoDBKeyStore(dynamoDBClient, kmsClient, mockRetentionService as any)+ keyStore = new DynamoDBKeyStore(dynamoDBClient, kmsClient)await keyStore.start()encryptor = new SodiumRecordingEncryptor(keyStore)@@ -601,7 +597,7 @@ describe('Recording API encryption integration', () => {const sessionId = `kms-test-${Date.now()}`const teamId = 1- const generatedKey = await keyStore.generateKey(sessionId, teamId)+ const generatedKey = await keyStore.generateKey(sessionId, teamId, 30)expect(generatedKey.sessionState).toBe('ciphertext')expect(generatedKey.plaintextKey.length).toBe(sodium.crypto_secretbox_KEYBYTES)@@ -618,7 +614,7 @@ describe('Recording API encryption integration', () => {const sessionId = `double-delete-${Date.now()}`const teamId = 4- await keyStore.generateKey(sessionId, teamId)+ await keyStore.generateKey(sessionId, teamId, 30)await keyStore.deleteKey(sessionId, teamId, '[email protected]')const result = await keyStore.deleteKey(sessionId, teamId, '[email protected]')@@ -631,8 +627,8 @@ describe('Recording API encryption integration', () => {const team1 = 10const team2 = 20- const key1 = await keyStore.generateKey(sessionId, team1)- const key2 = await keyStore.generateKey(sessionId, team2)+ const key1 = await keyStore.generateKey(sessionId, team1, 30)+ const key2 = await keyStore.generateKey(sessionId, team2, 30)expect(key1.plaintextKey.equals(key2.plaintextKey)).toBe(false)@@ -648,8 +644,8 @@ describe('Recording API encryption integration', () => {const team1 = 30const team2 = 40- await keyStore.generateKey(sessionId, team1)- await keyStore.generateKey(sessionId, team2)+ await keyStore.generateKey(sessionId, team1, 30)+ await keyStore.generateKey(sessionId, team2, 30)await keyStore.deleteKey(sessionId, team1, '[email protected]')@@ -707,7 +703,7 @@ describe('Recording API encryption integration', () => {{ type: 3, data: { source: 2, mutations: [{ id: 1 }] } },]- const sessionKey = await keyStore.generateKey(sessionId, teamId)+ const sessionKey = await keyStore.generateKey(sessionId, teamId, 30)const blockData = await createBlockData(originalEvents)const { data: encrypted } = encryptor.encryptBlockWithKey(sessionId, teamId, blockData, sessionKey)@@ -735,7 +731,7 @@ describe('Recording API encryption integration', () => {const sessionId = `s3-deleted-${Date.now()}`const teamId = 1- const sessionKey = await keyStore.generateKey(sessionId, teamId)+ const sessionKey = await keyStore.generateKey(sessionId, teamId, 30)const blockData = await createBlockData([{ type: 2, data: { content: 'secret' } }])const { data: encrypted } = encryptor.encryptBlockWithKey(sessionId, teamId, blockData, sessionKey)@@ -807,7 +803,7 @@ describe('Recording API encryption integration', () => {const teamId = 1const originalEvents = [{ type: 2, data: { content: 'hello' } }]- const sessionKey = await keyStore.generateKey(sessionId, teamId)+ const sessionKey = await keyStore.generateKey(sessionId, teamId, 30)const blockData = await createBlockData(originalEvents)const { data: encrypted } = encryptor.encryptBlockWithKey(sessionId, teamId, blockData, sessionKey)@@ -833,7 +829,7 @@ describe('Recording API encryption integration', () => {const sessionId = 'http-deleted-session'const teamId = 1- const sessionKey = await keyStore.generateKey(sessionId, teamId)+ const sessionKey = await keyStore.generateKey(sessionId, teamId, 30)const blockData = await createBlockData([{ type: 2, data: { content: 'secret' } }])const { data: encrypted } = encryptor.encryptBlockWithKey(sessionId, teamId, blockData, sessionKey)@@ -878,7 +874,7 @@ describe('Recording API encryption integration', () => {{ type: 3, data: { content: 'world' } },]- const sessionKey = await keyStore.generateKey(sessionId, teamId)+ const sessionKey = await keyStore.generateKey(sessionId, teamId, 30)const blockData = await createBlockData(originalEvents)const { data: encrypted } = encryptor.encryptBlockWithKey(sessionId, teamId, blockData, sessionKey)@@ -910,7 +906,7 @@ describe('Recording API encryption integration', () => {const teamId = 1const originalEvents = [{ type: 2, data: { content: 'compressed' } }]- const sessionKey = await keyStore.generateKey(sessionId, teamId)+ const sessionKey = await keyStore.generateKey(sessionId, teamId, 30)const blockData = await createBlockData(originalEvents)const { data: encrypted } = encryptor.encryptBlockWithKey(sessionId, teamId, blockData, sessionKey)@@ -943,7 +939,7 @@ describe('Recording API encryption integration', () => {const sessionId = `cache-invalidation-${Date.now()}`const teamId = 1- await cachedKeyStore.generateKey(sessionId, teamId)+ await cachedKeyStore.generateKey(sessionId, teamId, 30)// Populate cacheconst cachedKey = await cachedKeyStore.getKey(sessionId, teamId)@@ -972,7 +968,7 @@ describe('Recording API encryption integration', () => {const sessionId = `cache-decrypt-${Date.now()}`const teamId = 1- const sessionKey = await cachedKeyStore.generateKey(sessionId, teamId)+ const sessionKey = await cachedKeyStore.generateKey(sessionId, teamId, 30)const blockData = await createBlockData([{ type: 2, data: { content: 'cached' } }])const { data: encrypted } = encryptor.encryptBlockWithKey(sessionId, teamId, blockData, sessionKey)@@ -998,7 +994,7 @@ describe('Recording API encryption integration', () => {const sessionId = `nested-cache-${Date.now()}`const teamId = 1- await outerCache.generateKey(sessionId, teamId)+ await outerCache.generateKey(sessionId, teamId, 30)// Populate both cache layersconst key = await outerCache.getKey(sessionId, teamId)