Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(replay): resolve session keys before recording, off the S3 path (#67671)

Paweł Ledwońbd97253f5d7f
diff --git a/nodejs/src/ingestion/framework/builders/batch-pipeline-builders.ts b/nodejs/src/ingestion/framework/builders/batch-pipeline-builders.ts
index 4286003d4efe..3b58dbcb6c9e 100644
--- a/nodejs/src/ingestion/framework/builders/batch-pipeline-builders.ts
+++ b/nodejs/src/ingestion/framework/builders/batch-pipeline-builders.ts
@@ -43,7 +43,8 @@ export class GroupProcessingBuilder<
> {
constructor(
private previousPipeline: BatchPipeline<TInput, TOutput, CInput, COutput, R>,
- private groupingFn: GroupingFunction<TOutput, TKey>
+ private groupingFn: GroupingFunction<TOutput, TKey>,
+ private maxConcurrency?: number
) {}
/**
@@ -54,7 +55,12 @@ export class GroupProcessingBuilder<
): BatchPipelineBuilder<TInput, U, CInput, COutput, R | R2> {
const processor = callback(new StartPipelineBuilder<TOutput, COutput>()).build()
return new BatchPipelineBuilder(
- new ConcurrentlyGroupingBatchPipeline(this.groupingFn, processor, this.previousPipeline)
+ new ConcurrentlyGroupingBatchPipeline(
+ this.groupingFn,
+ processor,
+ this.previousPipeline,
+ this.maxConcurrency
+ )
)
}
}
@@ -71,13 +77,16 @@ export class GroupingBatchPipelineBuilder<TInput, TOutput, CInput, COutput, TKey
/**
* Process groups concurrently. Returns a builder to configure how items within each group are processed.
* Results are returned unordered as each group completes.
+ *
+ * @param options.maxConcurrency - Cap on how many groups process at once. Omitted means unbounded.
*/
concurrently<U, ROut extends string = never>(
callback: (
builder: GroupProcessingBuilder<TInput, TOutput, CInput, COutput, TKey, R>
- ) => BatchPipelineBuilder<TInput, U, CInput, COutput, ROut>
+ ) => BatchPipelineBuilder<TInput, U, CInput, COutput, ROut>,
+ options?: { maxConcurrency?: number }
): BatchPipelineBuilder<TInput, U, CInput, COutput, R | ROut> {
- return callback(new GroupProcessingBuilder(this.previousPipeline, this.groupingFn))
+ return callback(new GroupProcessingBuilder(this.previousPipeline, this.groupingFn, options?.maxConcurrency))
}
}
@@ -104,17 +113,28 @@ export class BatchPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R e
return this.pipeBatch(withBatchRetry(step, options))
}
+ /**
+ * Process each item of the batch concurrently, emitting results in input (FIFO) order.
+ *
+ * @param options.maxConcurrency - Cap on how many items process at once. Omitted means unbounded.
+ */
concurrently<U, R2 extends string = never>(
- callback: (builder: StartPipelineBuilder<TOutput, COutput>) => PipelineBuilder<TOutput, U, COutput, R2>
+ callback: (builder: StartPipelineBuilder<TOutput, COutput>) => PipelineBuilder<TOutput, U, COutput, R2>,
+ options?: { maxConcurrency?: number }
): BatchPipelineBuilder<TInput, U, CInput, COutput, R | R2> {
const processor = callback(new StartPipelineBuilder<TOutput, COutput>()).build()
- return new BatchPipelineBuilder(new ConcurrentBatchProcessingPipeline(processor, this.pipeline))
+ return new BatchPipelineBuilder(
+ new ConcurrentBatchProcessingPipeline(processor, this.pipeline, options?.maxConcurrency)
+ )
}
pipeConcurrently<U, R2 extends string = never>(
- processor: Pipeline<TOutput, U, COutput, R2>
+ processor: Pipeline<TOutput, U, COutput, R2>,
+ options?: { maxConcurrency?: number }
): BatchPipelineBuilder<TInput, U, CInput, COutput, R | R2> {
- return new BatchPipelineBuilder(new ConcurrentBatchProcessingPipeline(processor, this.pipeline))
+ return new BatchPipelineBuilder(
+ new ConcurrentBatchProcessingPipeline(processor, this.pipeline, options?.maxConcurrency)
+ )
}
sequentially<U, R2 extends string = never>(
diff --git a/nodejs/src/ingestion/framework/concurrent-batch-pipeline.test.ts b/nodejs/src/ingestion/framework/concurrent-batch-pipeline.test.ts
index 710535089d50..8a0e2f8c0c3f 100644
--- a/nodejs/src/ingestion/framework/concurrent-batch-pipeline.test.ts
+++ b/nodejs/src/ingestion/framework/concurrent-batch-pipeline.test.ts
@@ -292,6 +292,64 @@ describe('ConcurrentBatchProcessingPipeline', () => {
'end-slow',
])
})
+
+ it('caps how many items process at once when maxConcurrency is set', async () => {
+ const itemCount = 6
+ const maxConcurrency = 2
+ let active = 0
+ let peak = 0
+
+ const processor = createNewPipeline<string>().pipe(async (input: string) => {
+ active++
+ peak = Math.max(peak, active)
+ await new Promise((resolve) => setTimeout(resolve, 5))
+ active--
+ return ok(input.toUpperCase())
+ })
+ const previousPipeline = createNewBatchPipeline<string>().build()
+ const testBatch = Array.from({ length: itemCount }, (_, i) => createOkContext(`item-${i}`, context1))
+ previousPipeline.feed(testBatch)
+
+ const pipeline = new ConcurrentBatchProcessingPipeline(processor, previousPipeline, maxConcurrency)
+
+ const results = []
+ let result = await pipeline.next()
+ while (result !== null) {
+ results.push(...result)
+ result = await pipeline.next()
+ }
+
+ expect(results).toHaveLength(itemCount)
+ // Reached the cap (proves it's concurrent) but never exceeded it.
+ expect(peak).toBe(maxConcurrency)
+ })
+
+ it('emits in FIFO order under a cap even when a slow head finishes last', async () => {
+ // More items than permits (cap 2, 4 items) so later items must park for a
+ // permit, and the head is the slowest so completion order (1,2,3,0) diverges
+ // from input order. p-limit's FIFO wait queue must still hand the head its
+ // permit first; emission then stays in input order regardless of durations.
+ const delaysByIndex = [30, 5, 5, 5]
+ const processor = createNewPipeline<string>().pipe(async (input: string) => {
+ const index = Number(input.split('-')[1])
+ await new Promise((resolve) => setTimeout(resolve, delaysByIndex[index]))
+ return ok(input.toUpperCase())
+ })
+ const previousPipeline = createNewBatchPipeline<string>().build()
+ const testBatch = delaysByIndex.map((_, i) => createOkContext(`item-${i}`, context1))
+ previousPipeline.feed(testBatch)
+
+ const pipeline = new ConcurrentBatchProcessingPipeline(processor, previousPipeline, 2)
+
+ const emitted = []
+ let result = await pipeline.next()
+ while (result !== null) {
+ emitted.push(...result.map((r) => r.result))
+ result = await pipeline.next()
+ }
+
+ expect(emitted).toEqual([ok('ITEM-0'), ok('ITEM-1'), ok('ITEM-2'), ok('ITEM-3')])
+ })
})
describe('error poisoning', () => {
diff --git a/nodejs/src/ingestion/framework/concurrent-batch-pipeline.ts b/nodejs/src/ingestion/framework/concurrent-batch-pipeline.ts
index 8e5d4d13083c..f60fcda24a06 100644
--- a/nodejs/src/ingestion/framework/concurrent-batch-pipeline.ts
+++ b/nodejs/src/ingestion/framework/concurrent-batch-pipeline.ts
@@ -1,3 +1,5 @@
+import pLimit from 'p-limit'
+
import { BatchPipeline, BatchPipelineResultWithContext, OkResultWithContext } from './batch-pipeline.interface'
import { InterleavingBatchPipeline, PullOutcome } from './interleaving-batch-pipeline'
import { Pipeline, PipelineContext, PipelineResultWithContext } from './pipeline.interface'
@@ -30,10 +32,15 @@ export class ConcurrentBatchProcessingPipeline<
private promiseQueue: Promise<PipelineResultWithContext<TOutput, COutput, RPrev | RStep>>[] = []
private inner: InterleavingBatchPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>
+ // Caps how many items process at once. Null means unbounded (start every item as it's pulled).
+ private readonly limit: ReturnType<typeof pLimit> | null
+
constructor(
private processor: Pipeline<TIntermediate, TOutput, COutput, RStep>,
- private previousPipeline: BatchPipeline<TInput, TIntermediate, CInput, COutput, RPrev>
+ private previousPipeline: BatchPipeline<TInput, TIntermediate, CInput, COutput, RPrev>,
+ maxConcurrency?: number
) {
+ this.limit = maxConcurrency !== undefined ? pLimit(maxConcurrency) : null
this.inner = new InterleavingBatchPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>({
onFeed: (elements) => this.previousPipeline.feed(elements),
onSourcePull: () => this.enqueueFromPrevious(),
@@ -58,9 +65,13 @@ export class ConcurrentBatchProcessingPipeline<
for (const resultWithContext of previousResults) {
if (isOkResult(resultWithContext.result)) {
- this.promiseQueue.push(
- this.processor.process({ result: resultWithContext.result, context: resultWithContext.context })
- )
+ // Capture the narrowed ok result before the closure, which wouldn't re-narrow it.
+ const okResult = resultWithContext.result
+ const context = resultWithContext.context
+ const process = () => this.processor.process({ result: okResult, context })
+ // p-limit is FIFO, so the head of promiseQueue (pushed first) always acquires a permit
+ // first — it can never park behind a later item, keeping emission order intact.
+ this.promiseQueue.push(this.limit ? this.limit(process) : process())
} else {
this.promiseQueue.push(
Promise.resolve({ result: resultWithContext.result, context: resultWithContext.context })
diff --git a/nodejs/src/ingestion/framework/concurrently-grouping-batch-pipeline.test.ts b/nodejs/src/ingestion/framework/concurrently-grouping-batch-pipeline.test.ts
index 36178efc43b2..24137e03a750 100644
--- a/nodejs/src/ingestion/framework/concurrently-grouping-batch-pipeline.test.ts
+++ b/nodejs/src/ingestion/framework/concurrently-grouping-batch-pipeline.test.ts
@@ -315,6 +315,144 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {
})
})
+ describe('bounded concurrency', () => {
+ it('caps how many groups (not items) process at once when maxConcurrency is set', async () => {
+ // Real timers so a full drain naturally lets each item's delay elapse; peak concurrency
+ // is observed across the whole run.
+ jest.useRealTimers()
+
+ const groupCount = 6
+ const itemsPerGroup = 3
+ const maxConcurrency = 2
+ // Track concurrent groups: a group is active from its first item's start to its last item's
+ // end. Items within a group run sequentially under one slot, so items-in-flight would peak
+ // higher than groups-in-flight if the cap counted items.
+ const activeItemsByGroup = new Map<string, number>()
+ let peakGroups = 0
+ let peakItems = 0
+
+ const processor = createNewPipeline<{ index: number; group: string }>().pipe(async (input) => {
+ activeItemsByGroup.set(input.group, (activeItemsByGroup.get(input.group) ?? 0) + 1)
+ peakGroups = Math.max(peakGroups, activeItemsByGroup.size)
+ peakItems = Math.max(
+ peakItems,
+ [...activeItemsByGroup.values()].reduce((a, b) => a + b, 0)
+ )
+ await new Promise((resolve) => setTimeout(resolve, 5))
+ const remaining = (activeItemsByGroup.get(input.group) ?? 1) - 1
+ if (remaining === 0) {
+ activeItemsByGroup.delete(input.group)
+ } else {
+ activeItemsByGroup.set(input.group, remaining)
+ }
+ return ok({ ...input, processed: true })
+ })
+ const previousPipeline = createNewBatchPipeline<{ index: number; group: string }>().build()
+
+ const testBatch = []
+ let index = 0
+ for (let g = 0; g < groupCount; g++) {
+ for (let i = 0; i < itemsPerGroup; i++) {
+ testBatch.push(createOkContext({ index: index++, group: `group-${g}` }, context1))
+ }
+ }
+ previousPipeline.feed(testBatch)
+
+ const pipeline = new ConcurrentlyGroupingBatchPipeline(
+ (input) => input.group,
+ processor,
+ previousPipeline,
+ maxConcurrency
+ )
+
+ const results: PipelineResultWithContext<any, any>[] = []
+ let result = await pipeline.next()
+ while (result !== null) {
+ results.push(...result)
+ result = await pipeline.next()
+ }
+
+ expect(results).toHaveLength(groupCount * itemsPerGroup)
+ // The cap is on groups: at most `maxConcurrency` groups run at once...
+ expect(peakGroups).toBe(maxConcurrency)
+ // ...and a group's items run sequentially under its single slot, so items-in-flight never
+ // exceeds the group cap either (one active item per active group).
+ expect(peakItems).toBe(maxConcurrency)
+ })
+
+ it('preserves per-key ordering when a group parks for a permit and more same-key items arrive', async () => {
+ // The key is claimed in activeProcessing synchronously when a group is started, so a
+ // same-key item fed while that group is still parked waiting for a permit must queue
+ // behind it rather than spawn a second concurrent runner. Two slow occupants (Y, Z) hold
+ // both permits so A genuinely parks; if the claim regressed to happen only once the permit
+ // is granted, a1 and a2 would run concurrently and A's peak concurrency would be 2.
+ const processingOrder: string[] = []
+ const activeByGroup = new Map<string, number>()
+ const peakByGroup = new Map<string, number>()
+ const processor = createNewPipeline<{ value: string; group: string }>().pipe(async (input) => {
+ const active = (activeByGroup.get(input.group) ?? 0) + 1
+ activeByGroup.set(input.group, active)
+ peakByGroup.set(input.group, Math.max(peakByGroup.get(input.group) ?? 0, active))
+ processingOrder.push(`start-${input.value}`)
+ await new Promise((resolve) => setTimeout(resolve, input.group === 'A' ? 10 : 100))
+ processingOrder.push(`end-${input.value}`)
+ activeByGroup.set(input.group, (activeByGroup.get(input.group) ?? 1) - 1)
+ return ok({ ...input, processed: true })
+ })
+ const previousPipeline = createNewBatchPipeline<{ value: string; group: string }>().build()
+ const pipeline = new ConcurrentlyGroupingBatchPipeline(
+ (input) => input.group,
+ processor,
+ previousPipeline,
+ 2
+ )
+
+ // Two slow groups fill both permits. Fed before the drain parks so they start on the
+ // first next(); later same-key feeds go through the pipeline to wake the parked drain.
+ previousPipeline.feed([
+ createOkContext({ value: 'y1', group: 'Y' }, context1),
+ createOkContext({ value: 'z1', group: 'Z' }, context2),
+ ])
+
+ const drained: PipelineResultWithContext<any, any>[] = []
+ const run = (async () => {
+ let result = await pipeline.next()
+ while (result !== null) {
+ drained.push(...result)
+ result = await pipeline.next()
+ }
+ })()
+
+ await jest.advanceTimersByTimeAsync(0)
+ expect(processingOrder).toEqual(['start-y1', 'start-z1'])
+
+ // A's first item parks (no permit free) and claims key A. Fed through the pipeline so the
+ // wake-up reaches the parked drain.
+ pipeline.feed([createOkContext({ value: 'a1', group: 'A' }, context3)])
+ await jest.advanceTimersByTimeAsync(0)
+ expect(processingOrder).toEqual(['start-y1', 'start-z1'])
+
+ // A's second item, fed while A is still parked, must queue — not start a second A runner.
+ pipeline.feed([createOkContext({ value: 'a2', group: 'A' }, context4)])
+ await jest.advanceTimersByTimeAsync(0)
+ expect(processingOrder).toEqual(['start-y1', 'start-z1'])
+
+ // Free both permits and let everything drain.
+ await jest.advanceTimersByTimeAsync(1000)
+ await run
+
+ expect(drained).toHaveLength(4)
+ // A never ran two items at once, and a1 fully preceded a2.
+ expect(peakByGroup.get('A')).toBe(1)
+ expect(processingOrder.filter((s) => s.endsWith('a1') || s.endsWith('a2'))).toEqual([
+ 'start-a1',
+ 'end-a1',
+ 'start-a2',
+ 'end-a2',
+ ])
+ })
+ })
+
describe('non-success results', () => {
it('should preserve non-success results without processing', async () => {
let processorCallCount = 0
diff --git a/nodejs/src/ingestion/framework/concurrently-grouping-batch-pipeline.ts b/nodejs/src/ingestion/framework/concurrently-grouping-batch-pipeline.ts
index 114f580fe738..9c5fefc65bf1 100644
--- a/nodejs/src/ingestion/framework/concurrently-grouping-batch-pipeline.ts
+++ b/nodejs/src/ingestion/framework/concurrently-grouping-batch-pipeline.ts
@@ -1,3 +1,5 @@
+import pLimit from 'p-limit'
+
import { BatchPipeline, BatchPipelineResultWithContext, OkResultWithContext } from './batch-pipeline.interface'
import { InterleavingBatchPipeline, PullOutcome } from './interleaving-batch-pipeline'
import { Pipeline, PipelineResultWithContext } from './pipeline.interface'
@@ -61,11 +63,16 @@ export class ConcurrentlyGroupingBatchPipeline<
private inner: InterleavingBatchPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>
+ // Caps how many groups process at once. Null means unbounded (start every ready group).
+ private readonly limit: ReturnType<typeof pLimit> | null
+
constructor(
private groupingFn: GroupingFunction<TIntermediate, TKey>,
private processor: Pipeline<TIntermediate, TOutput, COutput, RStep>,
- private previousPipeline: BatchPipeline<TInput, TIntermediate, CInput, COutput, RPrev>
+ private previousPipeline: BatchPipeline<TInput, TIntermediate, CInput, COutput, RPrev>,
+ maxConcurrency?: number
) {
+ this.limit = maxConcurrency !== undefined ? pLimit(maxConcurrency) : null
this.inner = new InterleavingBatchPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>({
onFeed: (elements) => this.previousPipeline.feed(elements),
onSourcePull: () => this.routeFromPrevious(),
@@ -150,7 +157,12 @@ export class ConcurrentlyGroupingBatchPipeline<
}
this.groupQueues.delete(key)
- const processingPromise = this.processGroupSequentially(queue).then(
+ // The key is claimed in activeProcessing synchronously below, so per-key ordering holds even
+ // when a group parks waiting for a concurrency permit.
+ const run = this.limit
+ ? this.limit(() => this.processGroupSequentially(queue))
+ : this.processGroupSequentially(queue)
+ const processingPromise = run.then(
(results) => {
this.completedResults.push(results)
this.activeProcessing.delete(key)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/config.ts
index 4d304b206434..416d709f659d 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/config.ts
@@ -83,6 +83,8 @@ export type SessionRecordingConfig = {
SESSION_RECORDING_FEATURES_ENABLED: boolean
SESSION_RECORDING_FEATURES_ROLLOUT_PERCENTAGE: number
SESSION_RECORDING_CRYPTO_INTEGRITY_CHECK_RATE: number
+ /** Caps how many sessions resolve their encryption key concurrently, bounding KMS/DynamoDB fan-out. */
+ SESSION_RECORDING_KEY_RESOLUTION_MAX_CONCURRENCY: number
// Kafka consumer config
INGESTION_SESSION_REPLAY_CONSUMER_CONSUME_TOPIC: string
@@ -143,6 +145,7 @@ export function getDefaultSessionRecordingConfig(): SessionRecordingConfig {
SESSION_RECORDING_FEATURES_ENABLED: true,
SESSION_RECORDING_FEATURES_ROLLOUT_PERCENTAGE: 10,
SESSION_RECORDING_CRYPTO_INTEGRITY_CHECK_RATE: 0,
+ SESSION_RECORDING_KEY_RESOLUTION_MAX_CONCURRENCY: 20,
// Kafka consumer config
INGESTION_SESSION_REPLAY_CONSUMER_CONSUME_TOPIC: KAFKA_SESSION_RECORDING_SNAPSHOT_ITEM_EVENTS,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts
index 1e82bef18de0..0d311eb4b39d 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts
@@ -83,6 +83,12 @@ export interface SessionRecordingIngesterCollaborators {
keyStore?: KeyStore
encryptor?: RecordingEncryptor
createPipeline?: SessionReplayPipelineFactory
+ /**
+ * Namespaces this ingester's session tracker/filter Redis keys. Leave unset for the main lane; a
+ * secondary lane (the ML mirror) must set it so it doesn't share seen/block state with the main lane
+ * (which would let it mark a session seen without the main key and cause a cleartext recording).
+ */
+ redisKeyNamespace?: string
}
export class SessionRecordingIngester {
@@ -120,6 +126,8 @@ export class SessionRecordingIngester {
| SessionFeaturesOutput
>
private readonly topHog: TopHog
+ private readonly sessionTracker: SessionTracker
+ private readonly sessionFilter: SessionFilter
private readonly keyStore: KeyStore
private readonly encryptor: RecordingEncryptor
private readonly createPipeline: SessionReplayPipelineFactory
@@ -198,17 +206,20 @@ export class SessionRecordingIngester {
)
: new BlackholeSessionBatchFileStorage())
- const sessionTracker = new SessionTracker(
+ this.sessionTracker = new SessionTracker(
this.redisPool,
- this.config.SESSION_RECORDING_SESSION_TRACKER_CACHE_TTL_MS
+ this.config.SESSION_RECORDING_SESSION_TRACKER_CACHE_TTL_MS,
+ undefined,
+ collaborators.redisKeyNamespace
)
- const sessionFilter = new SessionFilter({
+ this.sessionFilter = new SessionFilter({
redisPool: this.redisPool,
bucketCapacity: this.config.SESSION_RECORDING_NEW_SESSION_BUCKET_CAPACITY,
bucketReplenishRate: this.config.SESSION_RECORDING_NEW_SESSION_BUCKET_REPLENISH_RATE,
blockingEnabled: this.config.SESSION_RECORDING_NEW_SESSION_BLOCKING_ENABLED,
filterEnabled: this.config.SESSION_RECORDING_SESSION_FILTER_ENABLED,
localCacheTtlMs: this.config.SESSION_RECORDING_SESSION_FILTER_CACHE_TTL_MS,
+ keyNamespace: collaborators.redisKeyNamespace,
})
const region = config.SESSION_RECORDING_V2_S3_REGION ?? 'us-east-1'
@@ -232,9 +243,6 @@ export class SessionRecordingIngester {
metadataStore,
consoleLogStore,
featureStore,
- sessionTracker,
- sessionFilter,
- keyStore: this.keyStore,
encryptor: this.encryptor,
})
}
@@ -318,6 +326,10 @@ export class SessionRecordingIngester {
promiseScheduler: this.promiseScheduler,
teamService: this.teamService,
retentionService: this.retentionService,
+ sessionTracker: this.sessionTracker,
+ sessionFilter: this.sessionFilter,
+ keyStore: this.keyStore,
+ sessionKeyResolutionMaxConcurrency: this.config.SESSION_RECORDING_KEY_RESOLUTION_MAX_CONCURRENCY,
topHog: this.topHog,
sessionBatchManager: this.sessionBatchManager,
isDebugLoggingEnabled: this.isDebugLoggingEnabled,
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.ts
index 733adb0126d6..112376c3a64e 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,12 +12,15 @@ 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 { SessionFilter } from '~/ingestion/pipelines/sessionreplay/sessions/session-filter'
+import { SessionTracker } from '~/ingestion/pipelines/sessionreplay/sessions/session-tracker'
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 { createMockKeyStore } from '~/ingestion/pipelines/sessionreplay/shared/test-helpers'
import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'
@@ -61,6 +64,23 @@ describe('ml-mirror-pipeline', () => {
return Promise.resolve(resolutions)
}),
} as unknown as RetentionService
+ // Every session resolves as already-seen, unblocked, and with a cleartext key so messages flow
+ // through to recording.
+ const sessionTracker = {
+ hasSeen: jest.fn().mockImplementation((sessions: SessionSet) => {
+ const map = new SessionMap<boolean>()
+ for (const { teamId, sessionId } of sessions) {
+ map.set(teamId, sessionId, true)
+ }
+ return Promise.resolve(map)
+ }),
+ markSeen: jest.fn().mockResolvedValue(undefined),
+ } as unknown as SessionTracker
+ const sessionFilter = {
+ handleNewSessions: jest.fn().mockResolvedValue(new SessionSet()),
+ isBlocked: jest.fn().mockResolvedValue(new SessionSet()),
+ } as unknown as SessionFilter
+ const keyStore = createMockKeyStore()
const now = DateTime.now()
const team = (aiTrainingOptedIn: boolean): TeamForReplay => ({
@@ -109,6 +129,10 @@ describe('ml-mirror-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled: () => false,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts
index e2eda3170579..dece71432d22 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts
@@ -1,6 +1,4 @@
/** The primary session replay pipeline plus an AI-training opt-in filter and an anonymize step. */
-import { Message } from 'node-rdkafka'
-
import { OverflowOutput } from '~/common/outputs'
import { createApplyEventRestrictionsStep, createParseHeadersStep } from '~/ingestion/common/steps/event-preprocessing'
import { BatchPipeline } from '~/ingestion/framework/batch-pipeline.interface'
@@ -17,8 +15,12 @@ import { createAnonymizeStep } from '~/ingestion/pipelines/sessionreplay/anonymi
import { ScrubContext } from '~/ingestion/pipelines/sessionreplay/anonymize/config'
import { createParseAndAnonymizeMessageStep } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'
import { createParseMessageStep } from '~/ingestion/pipelines/sessionreplay/parse-message-step'
+import { MessageContext } from '~/ingestion/pipelines/sessionreplay/pipeline-types'
import { createRecordSessionEventStep } from '~/ingestion/pipelines/sessionreplay/record-session-event-step'
+import { createMarkSeenStep } from '~/ingestion/pipelines/sessionreplay/session-batch-mark-seen-step'
import { createResolveRetentionStep } from '~/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step'
+import { createTrackAndGateStep } from '~/ingestion/pipelines/sessionreplay/session-batch-track-and-gate-step'
+import { createResolveKeyStep } from '~/ingestion/pipelines/sessionreplay/session-resolve-key-step'
import { createTeamFilterStep } from '~/ingestion/pipelines/sessionreplay/team-filter-step'
import { createValidateSessionReplayHeadersStep } from '~/ingestion/pipelines/sessionreplay/validate-headers-step'
@@ -32,8 +34,8 @@ export function createMlMirrorReplayPipeline(
): BatchPipeline<
SessionReplayPipelineInput,
SessionReplayPipelineOutput,
- { message: Message },
- { message: Message },
+ MessageContext,
+ MessageContext,
OverflowOutput
> {
const {
@@ -43,6 +45,10 @@ export function createMlMirrorReplayPipeline(
promiseScheduler,
teamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency,
topHog,
sessionBatchManager,
isDebugLoggingEnabled,
@@ -52,7 +58,7 @@ export function createMlMirrorReplayPipeline(
const pipelineConfig: PipelineConfig<OverflowOutput> = { outputs, promiseScheduler }
const topHogWrapper = createTopHogWrapper(topHog)
- const pipeline = newBatchPipelineBuilder<SessionReplayPipelineInput, { message: Message }>()
+ const pipeline = newBatchPipelineBuilder<SessionReplayPipelineInput, MessageContext>()
.messageAware((b) =>
b
.sequentially((b) =>
@@ -76,6 +82,32 @@ export function createMlMirrorReplayPipeline(
tries: 3,
sleepMs: 100,
})
+ // Track sessions and rate-limit new ones for the whole batch, tagging each with
+ // isNewSession and a gate verdict; blocked sessions are carried (not dropped) to the
+ // mark-seen step, all in this step's own retry scope.
+ .pipeBatchWithRetry(createTrackAndGateStep(sessionTracker, sessionFilter), {
+ tries: 3,
+ sleepMs: 100,
+ })
+ // Resolve each session's encryption key once per session (grouped), concurrently across
+ // sessions with a bounded fan-out and per-session retry. Deleted sessions drop here.
+ .groupBy((element) => `${element.team.teamId}:${element.headers.session_id}`)
+ .concurrently(
+ (group) =>
+ group.sequentially((b) =>
+ b.retry((rb) => rb.pipe(createResolveKeyStep(keyStore)), {
+ name: 'resolve_session_key',
+ tries: 3,
+ sleepMs: 100,
+ })
+ ),
+ { maxConcurrency: sessionKeyResolutionMaxConcurrency }
+ )
+ // Re-collect the per-session groups into one batch — both to mark the whole batch seen
+ // in a single Redis write and as the barrier that guarantees every key is resolved first.
+ .gather()
+ // Mark the surviving new sessions seen, now that every key is durably resolved.
+ .pipeBatch(createMarkSeenStep(sessionTracker))
.filterMap(
(element) => ({
result: element.result,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts
index fe305eae8267..16e36b37a777 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts
@@ -5,7 +5,7 @@ import { gzip } from 'zlib'
import { PipelineResultType } from '~/ingestion/framework/results'
import { createParseAndAnonymizeMessageStep } from './parse-and-anonymize-step'
-import { SessionReplayHeaders } from './validate-headers-step'
+import { SessionReplayHeaders } from './pipeline-types'
const compressWithGzip = promisify(gzip)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.test.ts
index 2c77f3a8a9d7..e1540b128881 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.test.ts
@@ -5,7 +5,7 @@ import { gzip } from 'zlib'
import { PipelineResultType } from '~/ingestion/framework/results'
import { ParseMessageStepInput, createParseMessageStep, decompressMessageValue } from './parse-message-step'
-import { SessionReplayHeaders } from './validate-headers-step'
+import { SessionReplayHeaders } from './pipeline-types'
const compressWithGzip = promisify(gzip)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.ts
index 9a5447709147..b5971ac254da 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.ts
@@ -15,7 +15,7 @@ import {
} from '~/ingestion/pipelines/sessionreplay/kafka/types'
import { SessionRecordingIngesterMetrics } from '~/ingestion/pipelines/sessionreplay/metrics'
-import { SessionReplayHeaders } from './validate-headers-step'
+import { SessionReplayHeaders } from './pipeline-types'
const lz4: { decodeBlock(input: Buffer, output: Buffer): number } = require('lz4')
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/pipeline-types.ts b/nodejs/src/ingestion/pipelines/sessionreplay/pipeline-types.ts
new file mode 100644
index 000000000000..4d0e181e795b
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/pipeline-types.ts
@@ -0,0 +1,50 @@
+/** Types carried across the session replay pipeline steps (step-to-step data contracts). */
+import { Message } from 'node-rdkafka'
+
+import { SessionKey } from './shared/types'
+
+/** The per-message context threaded through every stage of the session replay pipeline. */
+export interface MessageContext {
+ message: Message
+}
+
+/**
+ * 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 `EventHeaders` so they can read them without re-checking. `session_id` is normalized in
+ * the validate step 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
+}
+
+/** Tags an element with whether its session is being seen for the first time in this batch. */
+export interface NewSessionFlag {
+ isNewSession: boolean
+}
+
+/**
+ * The gate's verdict for a session that survives rate limiting: `allowed`, on its way to key resolution.
+ * Blocked (rate-limited) sessions are dropped at the gate itself, so they never flow downstream — a
+ * blocked session is kept out of its team's new-session budget by its block key, not by riding the
+ * pipeline to be marked seen, so the seen flag stays reserved for sessions that actually hold a key.
+ */
+export type Allowed<T> = T & { status: 'allowed' }
+
+/**
+ * An {@link Allowed} element after key resolution. `allowed` now carries its key; `deleted` (key
+ * crypto-shredded) carries none. A `deleted` session is dropped at the mark-seen step but IS marked seen
+ * first — safe because its keystore tombstone outlives the seen flag, so while seen it always resolves as
+ * deleted, never cleartext — which also keeps it out of the budget without re-counting.
+ */
+export type Resolved<T> = Recordable<T> | (T & { status: 'deleted' })
+
+/**
+ * The one branch of {@link Resolved} that reaches recording: an `allowed` session carrying its resolved
+ * key. This is what the mark-seen step emits after dropping the deleted sessions.
+ */
+export type Recordable<T> = Allowed<T> & { sessionKey: SessionKey }
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.ts
index a9956a299c66..fbc08e5b3493 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
@@ -5,6 +5,7 @@ import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/typ
import { SessionRecordingIngesterMetrics } from '~/ingestion/pipelines/sessionreplay/metrics'
import { SessionBatchManager } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-manager'
import { SessionBatchRecorder } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder'
+import { createMockSessionKey } from '~/ingestion/pipelines/sessionreplay/shared/test-helpers'
import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
import { RecordSessionEventStepInput, createRecordSessionEventStep } from './record-session-event-step'
@@ -52,6 +53,7 @@ describe('createRecordSessionEventStep', () => {
team,
parsedMessage: createParsedMessage(overrides),
retentionPeriod: '30d',
+ sessionKey: createMockSessionKey(),
})
beforeEach(() => {
@@ -82,7 +84,8 @@ describe('createRecordSessionEventStep', () => {
team: defaultTeam,
message: input.parsedMessage,
},
- '30d'
+ '30d',
+ input.sessionKey
)
})
@@ -127,12 +130,11 @@ describe('createRecordSessionEventStep', () => {
})
it('should preserve additional input properties', async () => {
- const step = createRecordSessionEventStep({
+ const step = createRecordSessionEventStep<RecordSessionEventStepInput & { extraProperty: string }>({
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled: () => false,
})
- // Input with extra properties
const input = {
...createInput(),
extraProperty: 'should be preserved',
@@ -142,7 +144,7 @@ describe('createRecordSessionEventStep', () => {
expect(result.type).toBe(PipelineResultType.OK)
if (result.type === PipelineResultType.OK) {
- expect((result.value as any).extraProperty).toBe('should be preserved')
+ expect(result.value.extraProperty).toBe('should be preserved')
}
})
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.ts
index 05abfd824761..52ad5162e995 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.ts
@@ -5,6 +5,7 @@ import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/typ
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 { SessionKey } from '~/ingestion/pipelines/sessionreplay/shared/types'
import { MessageWithTeam, TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
import { ValueMatcher } from '~/types'
@@ -12,6 +13,7 @@ export interface RecordSessionEventStepInput {
team: TeamForReplay
parsedMessage: ParsedMessageData
retentionPeriod: RetentionPeriod
+ sessionKey: SessionKey
}
export interface RecordSessionEventStepConfig {
@@ -33,7 +35,7 @@ export function createRecordSessionEventStep<T extends RecordSessionEventStepInp
const { sessionBatchManager, isDebugLoggingEnabled } = config
return async function recordSessionEventStep(input) {
- const { team, parsedMessage, retentionPeriod } = input
+ const { team, parsedMessage, retentionPeriod, sessionKey } = input
// Reset revoked sessions counter once we're consuming
SessionRecordingIngesterMetrics.resetSessionsRevoked()
@@ -59,7 +61,7 @@ export function createRecordSessionEventStep<T extends RecordSessionEventStepInp
// Record to the session batch
const batch = sessionBatchManager.getCurrentBatch()
const messageWithTeam: MessageWithTeam = { team, message: parsedMessage }
- await batch.record(messageWithTeam, retentionPeriod)
+ await batch.record(messageWithTeam, retentionPeriod, sessionKey)
return ok(input)
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-mark-seen-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-mark-seen-step.test.ts
new file mode 100644
index 000000000000..7e5c4c543043
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-mark-seen-step.test.ts
@@ -0,0 +1,80 @@
+import { PipelineResultType, isOkResult } from '~/ingestion/framework/results'
+import { SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'
+import { createMockSessionKey } from '~/ingestion/pipelines/sessionreplay/shared/test-helpers'
+import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
+
+import { NewSessionFlag, Resolved, SessionReplayHeaders } from './pipeline-types'
+import { createMarkSeenStep } from './session-batch-mark-seen-step'
+import { SessionTracker } from './sessions/session-tracker'
+
+jest.mock('~/common/utils/logger', () => ({ logger: { debug: jest.fn() } }))
+
+type Base = { team: TeamForReplay; headers: SessionReplayHeaders } & NewSessionFlag
+
+describe('createMarkSeenStep', () => {
+ let mockSessionTracker: jest.Mocked<Pick<SessionTracker, 'markSeen'>>
+
+ // Only allowed and deleted sessions reach this step — blocked ones are dropped at the gate upstream.
+ const element = (
+ teamId: number,
+ sessionId: string,
+ isNewSession: boolean,
+ status: 'allowed' | 'deleted'
+ ): Resolved<Base> => {
+ const base = {
+ team: { teamId, consoleLogIngestionEnabled: false, aiTrainingOptedIn: true },
+ headers: { token: 'token', session_id: sessionId, distinct_id: 'distinct-1' },
+ isNewSession,
+ }
+ const resolved =
+ status === 'allowed' ? { ...base, status, sessionKey: createMockSessionKey() } : { ...base, status }
+ return resolved as unknown as Resolved<Base>
+ }
+
+ const createStep = () => createMarkSeenStep(mockSessionTracker as unknown as SessionTracker)
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ mockSessionTracker = { markSeen: jest.fn().mockResolvedValue(undefined) }
+ })
+
+ it('marks new allowed and deleted sessions seen, deduped, and drops only the deleted ones', async () => {
+ const values = [
+ element(1, 'allowed-new', true, 'allowed'),
+ element(1, 'allowed-new', true, 'allowed'),
+ element(1, 'deleted-new', true, 'deleted'),
+ element(1, 'existing', false, 'allowed'),
+ ]
+
+ const results = await createStep()(values)
+
+ // One markSeen for the whole batch (deduped). Allowed has a key and deleted has a tombstone, so
+ // both are safe to mark — a later getKey resolves to the key or to 'deleted', never cleartext. The
+ // existing one is already seen.
+ expect(mockSessionTracker.markSeen).toHaveBeenCalledTimes(1)
+ expect(mockSessionTracker.markSeen).toHaveBeenCalledWith(
+ new SessionSet().add(1, 'allowed-new').add(1, 'deleted-new')
+ )
+ // Deleted sessions are dropped; the allowed ones pass through.
+ expect(results.map((r) => r.type)).toEqual([
+ PipelineResultType.OK,
+ PipelineResultType.OK,
+ PipelineResultType.DROP,
+ PipelineResultType.OK,
+ ])
+ })
+
+ it('marks an empty set when the batch has no new sessions', async () => {
+ await createStep()([element(1, 'a', false, 'allowed'), element(2, 'b', false, 'deleted')])
+
+ expect(mockSessionTracker.markSeen).toHaveBeenCalledWith(new SessionSet())
+ })
+
+ it('preserves the resolved key on the passed-through allowed sessions', async () => {
+ const results = await createStep()([element(1, 'a', true, 'allowed')])
+
+ expect(
+ isOkResult(results[0]) && results[0].value.status === 'allowed' ? results[0].value.sessionKey : null
+ ).not.toBeNull()
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-mark-seen-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-mark-seen-step.ts
new file mode 100644
index 000000000000..1c2259dfd069
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-mark-seen-step.ts
@@ -0,0 +1,53 @@
+import { logger } from '~/common/utils/logger'
+import { BatchProcessingStep } from '~/ingestion/framework/base-batch-pipeline'
+import { drop, ok } from '~/ingestion/framework/results'
+import { SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'
+import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
+
+import { NewSessionFlag, Recordable, Resolved, SessionReplayHeaders } from './pipeline-types'
+import { SessionTracker } from './sessions/session-tracker'
+
+/** The minimal per-element shape this step needs to mark a session seen. */
+type MarkSeenStepInput = { team: TeamForReplay; headers: SessionReplayHeaders } & NewSessionFlag
+
+/**
+ * Record-phase batch step: mark new sessions as seen, in one Redis pipeline, now that key resolution has
+ * run upstream — then drop the deleted sessions, so only recordable (allowed, keyed) sessions pass on.
+ *
+ * Only allowed and deleted sessions reach this step (blocked ones are dropped at the gate). This is the
+ * single place sessions are marked seen, and a session is marked only once the keystore holds a durable
+ * entry for it — so the seen flag means strictly "a later `getKey` for this session resolves to something
+ * other than cleartext." That holds for both statuses here: `allowed` has a real key generated/fetched,
+ * and `deleted` has a tombstone whose 30-day TTL outlives the seen flag, so while seen it always resolves
+ * as deleted. (A `blocked` session — keyless and tombstone-less — would break this, which is exactly why
+ * it's dropped upstream and never reaches here.) Marking earlier, before resolution, would risk a keyless
+ * cleartext recording on a key-resolution retry.
+ */
+export function createMarkSeenStep<T extends MarkSeenStepInput>(
+ sessionTracker: SessionTracker
+): BatchProcessingStep<Resolved<T>, Recordable<T>> {
+ return async function markSeenStep(values) {
+ const newlySeen = new SessionSet()
+ for (const value of values) {
+ // Allowed has a key, deleted has a tombstone — both are safe to mark seen (a later getKey
+ // resolves to the key or to 'deleted', never cleartext).
+ if (value.isNewSession) {
+ newlySeen.add(value.team.teamId, value.headers.session_id)
+ }
+ }
+
+ await sessionTracker.markSeen(newlySeen)
+
+ return values.map((value) => {
+ if (value.status === 'allowed') {
+ return ok(value)
+ }
+ logger.debug('🔁', 'session_replay_session_dropped_before_record', {
+ sessionId: value.headers.session_id,
+ teamId: value.team.teamId,
+ reason: 'session_deleted',
+ })
+ return drop<Recordable<T>>('session_deleted')
+ })
+ }
+}
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.ts
index 0d41d4e023f3..2f7d454de12b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.test.ts
@@ -6,11 +6,11 @@ import {
import { SessionMap, SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'
import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
+import { SessionReplayHeaders } from './pipeline-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', () => ({
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.ts
index e812510b41a9..d564a4a7b829 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.ts
@@ -8,9 +8,9 @@ import { RetentionService } from '~/ingestion/pipelines/sessionreplay/shared/ret
import { SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'
import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
+import { SessionReplayHeaders } from './pipeline-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
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-track-and-gate-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-track-and-gate-step.test.ts
new file mode 100644
index 000000000000..567114cdb101
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-track-and-gate-step.test.ts
@@ -0,0 +1,154 @@
+import { PipelineResult, isDropResult, isOkResult } from '~/ingestion/framework/results'
+import { RetentionPeriod } from '~/ingestion/pipelines/sessionreplay/shared/constants'
+import { SessionMap, SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'
+import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
+
+import { SessionReplayHeaders } from './pipeline-types'
+import { createTrackAndGateStep } from './session-batch-track-and-gate-step'
+import { SessionFilter } from './sessions/session-filter'
+import { SessionTracker } from './sessions/session-tracker'
+
+// A hasSeen() implementation that answers every queried session with the same value.
+const mapAll =
+ (value: boolean) =>
+ (sessions: SessionSet): Promise<SessionMap<boolean>> => {
+ const map = new SessionMap<boolean>()
+ for (const { teamId, sessionId } of sessions) {
+ map.set(teamId, sessionId, value)
+ }
+ return Promise.resolve(map)
+ }
+
+// An isBlocked() implementation: none blocked, or all queried sessions blocked.
+const blockAll =
+ (blocked: boolean) =>
+ (sessions: SessionSet): Promise<SessionSet> => {
+ const result = new SessionSet()
+ if (blocked) {
+ for (const { teamId, sessionId } of sessions) {
+ result.add(teamId, sessionId)
+ }
+ }
+ return Promise.resolve(result)
+ }
+
+// Reads (isNewSession, status) off an ok result, or null if it isn't ok. Only allowed sessions survive
+// the gate — blocked ones are dropped — so an ok result is always allowed.
+const flags = (
+ result: PipelineResult<{ isNewSession: boolean; status: 'allowed' }, 'session_blocked'>
+): { isNewSession: boolean; status: 'allowed' } | null =>
+ isOkResult(result) ? { isNewSession: result.value.isNewSession, status: result.value.status } : null
+
+describe('createTrackAndGateStep', () => {
+ let mockSessionTracker: jest.Mocked<Pick<SessionTracker, 'hasSeen'>>
+ let mockSessionFilter: jest.Mocked<Pick<SessionFilter, 'handleNewSessions' | 'isBlocked'>>
+
+ const element = (
+ teamId: number,
+ sessionId: string,
+ retentionPeriod: RetentionPeriod = '30d'
+ ): {
+ message: { partition: number; offset: number }
+ team: TeamForReplay
+ headers: SessionReplayHeaders
+ retentionPeriod: RetentionPeriod
+ } =>
+ ({
+ message: { partition: 0, offset: 0 },
+ team: { teamId, consoleLogIngestionEnabled: false, aiTrainingOptedIn: true },
+ headers: { token: 'token', session_id: sessionId, distinct_id: 'distinct-1' },
+ retentionPeriod,
+ }) as unknown as {
+ message: { partition: number; offset: number }
+ team: TeamForReplay
+ headers: SessionReplayHeaders
+ retentionPeriod: RetentionPeriod
+ }
+
+ const createStep = () =>
+ createTrackAndGateStep(
+ mockSessionTracker as unknown as SessionTracker,
+ mockSessionFilter as unknown as SessionFilter
+ )
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ mockSessionTracker = { hasSeen: jest.fn(mapAll(true)) }
+ mockSessionFilter = {
+ handleNewSessions: jest.fn().mockResolvedValue(new SessionSet()),
+ isBlocked: jest.fn(blockAll(false)),
+ }
+ })
+
+ it('charges a new, unblocked session a rate-limit token and tags it new/allowed', async () => {
+ mockSessionTracker.hasSeen.mockImplementation(mapAll(false))
+
+ const results = await createStep()([element(1, 'a')])
+
+ expect(mockSessionFilter.handleNewSessions).toHaveBeenCalledWith(new SessionSet().add(1, 'a'))
+ expect(flags(results[0])).toEqual({ isNewSession: true, status: 'allowed' })
+ })
+
+ it('tags a seen session as existing and does not charge it a token', async () => {
+ // Default hasSeen: already seen.
+ const results = await createStep()([element(1, 'a')])
+
+ expect(mockSessionFilter.handleNewSessions).toHaveBeenCalledWith(new SessionSet())
+ expect(flags(results[0])).toEqual({ isNewSession: false, status: 'allowed' })
+ })
+
+ it('drops an already-blocked session without re-charging its team budget', async () => {
+ mockSessionTracker.hasSeen.mockImplementation(mapAll(false))
+ mockSessionFilter.isBlocked.mockImplementation(blockAll(true))
+
+ const results = await createStep()([element(1, 'a')])
+
+ // Already on the blocklist, so it is NOT passed to handleNewSessions — a session dropped for its
+ // whole life must not drain a token from its team's budget every batch.
+ expect(mockSessionFilter.handleNewSessions).toHaveBeenCalledWith(new SessionSet())
+ // Dropped right at the gate: it carries no key, so nothing downstream needs it.
+ expect(isDropResult(results[0]) && results[0].reason).toBe('session_blocked')
+ })
+
+ it('drops a session blocked in this batch from the set handleNewSessions returns, without a second isBlocked read', async () => {
+ mockSessionTracker.hasSeen.mockImplementation(mapAll(false))
+ // Not on the blocklist yet, but this batch's rate-limit trips and blocks it.
+ mockSessionFilter.handleNewSessions.mockResolvedValue(new SessionSet().add(1, 'a'))
+
+ const results = await createStep()([element(1, 'a')])
+
+ expect(mockSessionFilter.isBlocked).toHaveBeenCalledTimes(1)
+ expect(isDropResult(results[0]) && results[0].reason).toBe('session_blocked')
+ })
+
+ it('runs each Redis bootstrap once per batch and fans the flags to every message of a session', async () => {
+ mockSessionTracker.hasSeen.mockImplementation(mapAll(false))
+
+ const results = await createStep()([element(1, 'a'), element(1, 'a'), element(1, 'a')])
+
+ expect(mockSessionTracker.hasSeen).toHaveBeenCalledTimes(1)
+ expect(mockSessionFilter.handleNewSessions).toHaveBeenCalledTimes(1)
+ expect(mockSessionFilter.isBlocked).toHaveBeenCalledTimes(1)
+ expect(mockSessionFilter.handleNewSessions).toHaveBeenCalledWith(new SessionSet().add(1, 'a'))
+ expect(results.map(flags)).toEqual([
+ { isNewSession: true, status: 'allowed' },
+ { isNewSession: true, status: 'allowed' },
+ { isNewSession: true, status: 'allowed' },
+ ])
+ })
+
+ it('keys new/blocked state by (teamId, sessionId) so identical ids on different teams do not collide', async () => {
+ mockSessionTracker.hasSeen.mockImplementation((sessions: SessionSet) => {
+ const map = new SessionMap<boolean>()
+ for (const { teamId, sessionId } of sessions) {
+ map.set(teamId, sessionId, teamId === 2) // team 2's session is seen, team 1's is new
+ }
+ return Promise.resolve(map)
+ })
+
+ const results = await createStep()([element(1, 'shared'), element(2, 'shared')])
+
+ expect(results.map((r) => flags(r)?.isNewSession)).toEqual([true, false])
+ expect(mockSessionFilter.handleNewSessions).toHaveBeenCalledWith(new SessionSet().add(1, 'shared'))
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-track-and-gate-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-track-and-gate-step.ts
new file mode 100644
index 000000000000..4ca4666b16e3
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-track-and-gate-step.ts
@@ -0,0 +1,91 @@
+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 { SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'
+import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
+
+import { Allowed, NewSessionFlag, SessionReplayHeaders } from './pipeline-types'
+import { SessionFilter } from './sessions/session-filter'
+import { SessionTracker } from './sessions/session-tracker'
+
+/** The minimal per-element shape this step needs to track and rate-limit a session. */
+type TrackAndGateStepInput = {
+ message: Pick<Message, 'partition' | 'offset'>
+ team: TeamForReplay
+ headers: SessionReplayHeaders
+ retentionPeriod: RetentionPeriod
+}
+
+/**
+ * Record-phase batch step: for the whole batch, learn which sessions are new, rate-limit the new ones
+ * against their team's budget, and either tag each surviving element with `isNewSession` (allowed, on to
+ * key resolution) or drop it as blocked — all off the S3 write path, in a few batched Redis round-trips.
+ *
+ * Ordering matters: the block check runs BEFORE rate-limiting, and only sessions that are neither seen
+ * nor already blocked are charged a token ({@link SessionFilter.handleNewSessions} consumes one per
+ * genuinely-new session). An already-blocked session is kept out of the budget by its own block key, not
+ * by charging it again — so a session dropped for the rest of its life doesn't drain its team's budget
+ * every batch. A session that trips its own budget in this batch is caught by unioning the newly-blocked
+ * set that handleNewSessions returns with the earlier block read.
+ *
+ * Blocked sessions are dropped right here. They carry no key, so nothing downstream acts on them — key
+ * resolution would skip them and the mark-seen step would only drop them — and, crucially, a blocked
+ * session is never marked seen: the block key alone keeps it out of the budget and out of recording, so
+ * the seen flag stays strictly "a key exists". That decoupling makes a lost block key degrade to an extra
+ * token charge next batch (tolerable) rather than a keyless, cleartext recording.
+ *
+ * Redis failure policy (see {@link SessionTracker} and {@link SessionFilter} class docs): the two rules
+ * split this step's Redis calls. {@link SessionTracker.hasSeen} decides generate-vs-fetch of the
+ * encryption key, so it FAILS HARD — a Redis error throws and this whole step is retried by its wrapper
+ * (which is safe: hasSeen runs first, before any token is consumed, so a retry can't double-charge). The
+ * filter calls ({@link SessionFilter.handleNewSessions}/{@link SessionFilter.isBlocked}) are pure rate
+ * limiting and fail open, so a Redis blip there under-limits rather than halting.
+ */
+export function createTrackAndGateStep<T extends TrackAndGateStepInput>(
+ sessionTracker: SessionTracker,
+ sessionFilter: SessionFilter
+): BatchProcessingStep<T, Allowed<T & NewSessionFlag>> {
+ return async function trackAndGateStep(values) {
+ // Dedupe repeated sessions so each one's Redis bootstrap runs exactly once per batch.
+ const toResolve = new SessionSet()
+ for (const value of values) {
+ toResolve.add(value.team.teamId, value.headers.session_id)
+ }
+
+ // One batched Redis read tells us which sessions are new.
+ const seen = await sessionTracker.hasSeen(toResolve)
+
+ // And one tells us which are already blocked — read before charging, so a session already on the
+ // blocklist isn't re-counted against its team's budget.
+ const alreadyBlocked = await sessionFilter.isBlocked(toResolve)
+
+ // Charge a token only for genuinely-new sessions: neither seen nor already blocked. This may
+ // block some more; handleNewSessions returns exactly the set it just blocked.
+ const newSessions = new SessionSet()
+ for (const { teamId, sessionId } of toResolve) {
+ if (!seen.get(teamId, sessionId) && !alreadyBlocked.has(teamId, sessionId)) {
+ newSessions.add(teamId, sessionId)
+ }
+ }
+ const newlyBlocked = await sessionFilter.handleNewSessions(newSessions)
+
+ return values.map((value) => {
+ const teamId = value.team.teamId
+ const sessionId = value.headers.session_id
+ const isNewSession = !seen.get(teamId, sessionId)
+
+ if (alreadyBlocked.has(teamId, sessionId) || newlyBlocked.has(teamId, sessionId)) {
+ logger.debug('🔁', 'session_replay_session_dropped_before_record', {
+ sessionId,
+ teamId,
+ reason: 'session_blocked',
+ })
+ return drop<Allowed<T & NewSessionFlag>>('session_blocked')
+ }
+ return ok({ ...value, isNewSession, status: 'allowed' as const })
+ })
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-rate-limiter.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-rate-limiter.test.ts
new file mode 100644
index 000000000000..dab57f1be882
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-rate-limiter.test.ts
@@ -0,0 +1,524 @@
+/**
+ * Executable spec for how the session rate limiter behaves under Redis failures.
+ *
+ * ## The two principles this suite enforces
+ *
+ * 1. RATE LIMITING IS BEST-EFFORT. On a failure it may UNDER-count a session (let it through
+ * un-limited) but must NEVER OVER-count (charge the same session twice). Rate-limiting ops fail
+ * open.
+ * 2. ENCRYPTION KEY INTEGRITY IS NON-NEGOTIABLE. Anything that could record without a key (cleartext)
+ * or switch a session's key mid-stream must FAIL HARD — throw and let the retry re-run — never
+ * guess.
+ *
+ * These pull in opposite directions on the one signal that serves both — "has this session been seen?"
+ * — which decides both whether to rate-limit AND whether to generate vs fetch the encryption key. Rule 2
+ * is stricter, so it wins there. That gives the per-op policy this suite locks in:
+ *
+ * | Redis op | drives | policy |
+ * |------------------------------|---------------------------------|-------------------------------|
+ * | tracker hasSeen (MGET) | key generate-vs-fetch + count | FAIL HARD (throw → retry) |
+ * | tracker markSeen (pipeline) | seen persistence (count only) | fail open (under-count) |
+ * | filter isBlocked (MGET) | drop-if-blocked + skip-recharge | fail open (under-block) |
+ * | filter blockSessions (pipe) | block persistence (count only) | fail open (under-block) |
+ *
+ * ## What the tests do
+ *
+ * Unlike session-replay-pipeline.test.ts (which mocks the tracker/filter), this builds the REAL
+ * SessionTracker and SessionFilter over an in-memory fake Redis we can fault-inject per operation, so it
+ * exercises the actual fail-open / fail-hard logic. "Counted as new" means the session was passed to
+ * SessionFilter.handleNewSessions (which consumes a rate-limit token). An allowed or deleted session is
+ * counted exactly once — both are marked seen, so the next batch reads them as existing. A session
+ * already on the blocklist is counted ZERO times: it's held out of the budget by its block key, not by
+ * being marked seen, so it's excluded from the charge before handleNewSessions rather than re-charged
+ * every batch. (A session freshly rate-limited in a batch is still counted the once, when it's blocked.)
+ *
+ * - baseline: every session type counted once.
+ * - transient failure (fails once, recovers): counting is unaffected — a fail-open op is masked, a
+ * fail-hard op (hasSeen) is retried and recovers. Each test also asserts the fault actually fired.
+ * - sustained outage (fails every batch): documents the degradation direction — hasSeen throws (fail
+ * hard, reprocess on recovery) while the fail-open ops keep flowing but under-enforce and don't persist.
+ */
+import { Redis } from 'ioredis'
+import { DateTime } from 'luxon'
+import { Message } from 'node-rdkafka'
+
+import { DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT, OVERFLOW_OUTPUT } from '~/common/outputs'
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'
+import { PromiseScheduler } from '~/common/utils/promise-scheduler'
+import { createApplyEventRestrictionsStep, createParseHeadersStep } from '~/ingestion/common/steps/event-preprocessing'
+import { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'
+import { ok } 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 { SessionFilter } from '~/ingestion/pipelines/sessionreplay/sessions/session-filter'
+import { SessionTracker } from '~/ingestion/pipelines/sessionreplay/sessions/session-tracker'
+import { 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 { createMockSessionKey } from '~/ingestion/pipelines/sessionreplay/shared/test-helpers'
+import { KeyStore } from '~/ingestion/pipelines/sessionreplay/shared/types'
+import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
+import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'
+import { RedisPool } from '~/types'
+
+import { createSessionReplayPipeline, runSessionReplayPipeline } from './session-replay-pipeline'
+
+jest.mock('~/ingestion/common/steps/event-preprocessing', () => ({
+ createParseHeadersStep: jest.fn(),
+ createApplyEventRestrictionsStep: jest.fn(),
+}))
+
+const SEEN_PREFIX = '@posthog/replay/session-seen'
+const BLOCK_PREFIX = '@posthog/replay/session-blocked'
+
+type FakeRedisOp = 'mget' | 'exec'
+
+type FaultSpec = { op: FakeRedisOp; keyPrefix: string } | null
+
+/** Minimal in-memory Redis supporting the tracker/filter access patterns, with per-op fault injection. */
+class FakeRedis {
+ public store = new Map<string, string>()
+ private failOnce: FaultSpec = null
+ private failEvery: FaultSpec = null
+
+ /** Make the next matching operation (touching a key with the given prefix) throw exactly once. */
+ failNext(op: FakeRedisOp, keyPrefix: string): void {
+ this.failOnce = { op, keyPrefix }
+ }
+
+ /** Make every matching operation throw — a sustained outage of that op, until cleared. */
+ failAlways(op: FakeRedisOp, keyPrefix: string): void {
+ this.failEvery = { op, keyPrefix }
+ }
+
+ /** True while an armed one-shot fault hasn't fired yet — lets tests assert the failure was exercised. */
+ hasPendingFailure(): boolean {
+ return this.failOnce !== null
+ }
+
+ private matches(spec: FaultSpec, op: FakeRedisOp, keys: string[]): boolean {
+ return spec !== null && spec.op === op && keys.some((k) => k.startsWith(spec.keyPrefix))
+ }
+
+ private maybeFail(op: FakeRedisOp, keys: string[]): void {
+ if (this.matches(this.failOnce, op, keys)) {
+ this.failOnce = null
+ throw new Error(`fake redis ${op} failed`)
+ }
+ if (this.matches(this.failEvery, op, keys)) {
+ throw new Error(`fake redis ${op} failed`)
+ }
+ }
+
+ mget(keys: string[]): Promise<(string | null)[]> {
+ this.maybeFail('mget', keys)
+ return Promise.resolve(keys.map((k) => this.store.get(k) ?? null))
+ }
+
+ pipeline(): FakePipeline {
+ return new FakePipeline(this)
+ }
+
+ commit(sets: Array<[string, string]>): void {
+ this.maybeFail(
+ 'exec',
+ sets.map(([k]) => k)
+ )
+ for (const [k, v] of sets) {
+ this.store.set(k, v)
+ }
+ }
+}
+
+class FakePipeline {
+ private sets: Array<[string, string]> = []
+ constructor(private redis: FakeRedis) {}
+ set(key: string, val: string, ..._args: unknown[]): this {
+ this.sets.push([key, val])
+ return this
+ }
+ exec(): Promise<unknown> {
+ this.redis.commit(this.sets)
+ return Promise.resolve(this.sets.map(() => [null, 'OK']))
+ }
+}
+
+function createMockSessionBatchManager(): jest.Mocked<SessionBatchManager> {
+ const mockBatchRecorder = {
+ record: jest.fn().mockResolvedValue(undefined),
+ getRetention: jest.fn().mockReturnValue(undefined),
+ } as unknown as jest.Mocked<SessionBatchRecorder>
+ return {
+ getCurrentBatch: jest.fn().mockReturnValue(mockBatchRecorder),
+ shouldFlush: jest.fn().mockReturnValue(false),
+ flush: jest.fn().mockResolvedValue(undefined),
+ discardPartitions: jest.fn(),
+ } as unknown as jest.Mocked<SessionBatchManager>
+}
+
+const mockCreateParseHeadersStep = createParseHeadersStep as jest.Mock
+const mockCreateApplyEventRestrictionsStep = createApplyEventRestrictionsStep as jest.Mock
+
+type SessionType = 'allowed' | 'blocked' | 'deleted'
+
+describe('session-replay-pipeline rate limiter failure modes', () => {
+ const TEAM_ID = 1
+ const team: TeamForReplay = {
+ teamId: TEAM_ID,
+ consoleLogIngestionEnabled: false,
+ aiTrainingOptedIn: true,
+ firstPartyHosts: [],
+ }
+ const now = DateTime.fromMillis(1_700_000_000_000)
+
+ let redis: FakeRedis
+ let pool: RedisPool
+ let sessionTracker: SessionTracker
+ let sessionFilter: SessionFilter
+ let keyStore: jest.Mocked<KeyStore>
+ let sessionBatchManager: jest.Mocked<SessionBatchManager>
+ let outputs: jest.Mocked<
+ IngestionOutputs<typeof DLQ_OUTPUT | typeof OVERFLOW_OUTPUT | typeof INGESTION_WARNINGS_OUTPUT>
+ >
+ let countedSessions: string[]
+
+ // Rebuilds the real SessionFilter with a given bucket capacity (capacity 0 forces new sessions to be
+ // rate-limited, which is the only way blockSessions is exercised), re-applying the counting spy.
+ function useBucketCapacity(bucketCapacity: number): void {
+ sessionFilter = new SessionFilter({
+ redisPool: pool,
+ bucketCapacity,
+ bucketReplenishRate: bucketCapacity,
+ blockingEnabled: true,
+ filterEnabled: true,
+ localCacheTtlMs: 5 * 60 * 1000,
+ })
+ applyCountingSpy()
+ }
+
+ function applyCountingSpy(): void {
+ jest.spyOn(sessionFilter, 'handleNewSessions').mockImplementation((sessions: SessionSet) => {
+ for (const { sessionId } of sessions) {
+ countedSessions.push(sessionId)
+ }
+ // Call through to the real limiter so blocking still happens.
+ return SessionFilter.prototype.handleNewSessions.call(sessionFilter, sessions)
+ })
+ }
+
+ function buildPipeline() {
+ const retentionService = {
+ resolveSessionRetentions: jest.fn().mockImplementation((sessions: SessionSet) => {
+ const resolutions = new SessionMap<{ resolved: true; retentionPeriod: '30d' }>()
+ for (const { teamId, sessionId } of sessions) {
+ resolutions.set(teamId, sessionId, { resolved: true, retentionPeriod: '30d' })
+ }
+ return Promise.resolve(resolutions)
+ }),
+ } as unknown as RetentionService
+
+ return createSessionReplayPipeline({
+ outputs,
+ eventIngestionRestrictionManager: {} as unknown as EventIngestionRestrictionManager,
+ overflowEnabled: false,
+ promiseScheduler: new PromiseScheduler(),
+ teamService: {
+ getTeamByToken: jest.fn().mockResolvedValue(team),
+ getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),
+ } as unknown as TeamService,
+ retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
+ topHog: createMockTopHog(),
+ sessionBatchManager,
+ isDebugLoggingEnabled: () => false,
+ })
+ }
+
+ function createMessage(sessionId: string, offset: number): Message {
+ const event = {
+ event: '$snapshot_items',
+ properties: {
+ $session_id: sessionId,
+ $window_id: 'window-1',
+ $snapshot_items: [
+ { type: 2, timestamp: now.toMillis(), data: {} },
+ { type: 3, timestamp: now.plus({ seconds: 1 }).toMillis(), data: {} },
+ ],
+ },
+ }
+ const payload = JSON.stringify({ distinct_id: 'user-123', data: JSON.stringify(event) })
+ const headers = { token: 'test-token', session_id: sessionId, distinct_id: 'user-123' }
+ return {
+ partition: 0,
+ offset,
+ topic: 'test-topic',
+ value: Buffer.from(payload),
+ key: Buffer.from('test-key'),
+ timestamp: now.toMillis(),
+ headers: Object.entries(headers).map(([k, v]) => ({ [k]: Buffer.from(v) })),
+ size: payload.length,
+ } as Message
+ }
+
+ async function runBatch(sessionId: string, offset: number): Promise<void> {
+ await runSessionReplayPipeline(buildPipeline(), [createMessage(sessionId, offset)])
+ }
+
+ // Assert a one-shot fault armed with failNext() actually fired — guards against a silently-inert fault
+ // (wrong op/prefix) that would make a test pass without exercising the failure it claims to.
+ const expectFaultFired = (): void => expect(redis.hasPendingFailure()).toBe(false)
+
+ function setUpSessionType(type: SessionType, sessionId: string): void {
+ if (type === 'blocked') {
+ // Pre-seed the persisted block flag so the session reads as already blocked.
+ redis.store.set(`${BLOCK_PREFIX}:${TEAM_ID}:${sessionId}`, '1')
+ }
+ if (type === 'deleted') {
+ keyStore.generateKey.mockResolvedValue(createMockSessionKey({ sessionState: 'deleted', deletedAt: 1 }))
+ keyStore.getKey.mockResolvedValue(createMockSessionKey({ sessionState: 'deleted', deletedAt: 1 }))
+ }
+ }
+
+ const timesCountedAsNew = (sessionId: string): number => countedSessions.filter((s) => s === sessionId).length
+
+ // A key is resolved only for sessions that pass the block check; a dropped (blocked) session skips it.
+ const keyWasResolvedFor = (sessionId: string): boolean =>
+ keyStore.generateKey.mock.calls.some((c) => c[0] === sessionId) ||
+ keyStore.getKey.mock.calls.some((c) => c[0] === sessionId)
+
+ const blockKey = (sessionId: string): string => `${BLOCK_PREFIX}:${TEAM_ID}:${sessionId}`
+ const seenKey = (sessionId: string): string => `${SEEN_PREFIX}:${TEAM_ID}:${sessionId}`
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ redis = new FakeRedis()
+ pool = {
+ acquire: () => Promise.resolve(redis as unknown as Redis),
+ release: () => Promise.resolve(),
+ } as unknown as RedisPool
+ sessionTracker = new SessionTracker(pool, 5 * 60 * 1000)
+ sessionFilter = new SessionFilter({
+ redisPool: pool,
+ bucketCapacity: 1000,
+ bucketReplenishRate: 1000,
+ blockingEnabled: true,
+ filterEnabled: true,
+ localCacheTtlMs: 5 * 60 * 1000,
+ })
+ keyStore = {
+ start: jest.fn().mockResolvedValue(undefined),
+ generateKey: jest.fn().mockResolvedValue(createMockSessionKey()),
+ getKey: jest.fn().mockResolvedValue(createMockSessionKey()),
+ deleteKey: jest.fn(),
+ stop: jest.fn(),
+ } as unknown as jest.Mocked<KeyStore>
+ sessionBatchManager = createMockSessionBatchManager()
+ outputs = createMockIngestionOutputs()
+
+ countedSessions = []
+ applyCountingSpy()
+
+ mockCreateParseHeadersStep.mockReturnValue((input: { message: Message; headers?: Record<string, string> }) => {
+ const headers: Record<string, string> = {}
+ for (const header of input.message.headers || []) {
+ for (const [key, value] of Object.entries(header)) {
+ headers[key] = Buffer.isBuffer(value) ? value.toString() : (value as string)
+ }
+ }
+ return Promise.resolve(ok({ ...input, headers }))
+ })
+ mockCreateApplyEventRestrictionsStep.mockReturnValue((input: unknown) => Promise.resolve(ok(input)))
+ })
+
+ // Establishes the baseline (no Redis failures): allowed and deleted are counted once (both marked
+ // seen at the mark-seen step, so batch two reads them as existing), while an already-blocklisted
+ // session is counted zero times — its block key, not a seen flag, keeps it out of the budget.
+ describe('baseline (no failures)', () => {
+ it.each<[SessionType, number]>([
+ ['allowed', 1],
+ ['blocked', 0],
+ ['deleted', 1],
+ ])('%s session is counted as new %i time(s) over two batches', async (type, expected) => {
+ setUpSessionType(type, type)
+
+ await runBatch(type, 1)
+ await runBatch(type, 2)
+
+ expect(timesCountedAsNew(type)).toBe(expected)
+ })
+ })
+
+ // hasSeen fails hard (throws), so the step's retry wrapper re-runs it — a transient blip recovers on
+ // the retry and counting is unaffected (rather than guessing "seen" and risking a keyless recording).
+ // Blocked stays 0 as in the baseline: recovery restores the block read, which excludes it from the charge.
+ describe('when the hasSeen read (tracker MGET) fails once then recovers on retry', () => {
+ it.each<[SessionType, number]>([
+ ['allowed', 1],
+ ['blocked', 0],
+ ['deleted', 1],
+ ])('%s session is counted as new %i time(s)', async (type, expected) => {
+ setUpSessionType(type, type)
+
+ // hasSeen is the MGET on the seen keys; make it throw once on the first batch.
+ redis.failNext('mget', SEEN_PREFIX)
+ await runBatch(type, 1)
+ expectFaultFired()
+ await runBatch(type, 2)
+
+ expect(timesCountedAsNew(type)).toBe(expected)
+ })
+ })
+
+ // markSeen fails open: the mark isn't persisted to Redis, but the local cache still records it, so
+ // the SAME consumer doesn't re-count the session next batch (the failure is masked locally). Only
+ // allowed and deleted are marked seen (a blocked session never is), so only those exercise this fault.
+ describe('when the markSeen write (tracker pipeline) fails on the first batch', () => {
+ it.each<[SessionType, number]>([
+ ['allowed', 1],
+ ['deleted', 1],
+ ])('%s session is counted as new %i time(s)', async (type, expected) => {
+ setUpSessionType(type, type)
+
+ // markSeen is the pipeline EXEC on the seen keys; make it throw once on the first batch.
+ redis.failNext('exec', SEEN_PREFIX)
+ await runBatch(type, 1)
+ expectFaultFired()
+ await runBatch(type, 2)
+
+ expect(timesCountedAsNew(type)).toBe(expected)
+ })
+ })
+
+ // isBlocked fails open (assume not blocked). The block read now gates the charge, but failing open
+ // means the already-blocked session is treated as unblocked: it leaks past the block for that batch,
+ // so it's counted the once (then marked seen) instead of being excluded — the same single count the
+ // other types get. Recovery on batch two reads it as existing, so it isn't re-counted.
+ describe('when the isBlocked read (filter MGET) fails on the first batch', () => {
+ it.each<[SessionType, number]>([
+ ['allowed', 1],
+ ['blocked', 1],
+ ['deleted', 1],
+ ])('%s session is counted as new %i time(s)', async (type, expected) => {
+ setUpSessionType(type, type)
+
+ // isBlocked is the MGET on the block keys; make it throw once on the first batch.
+ redis.failNext('mget', BLOCK_PREFIX)
+ await runBatch(type, 1)
+ expectFaultFired()
+ await runBatch(type, 2)
+
+ expect(timesCountedAsNew(type)).toBe(expected)
+ })
+ })
+
+ // blockSessions only runs when a new session is rate-limited (empty bucket). It fails open: the block
+ // isn't persisted to Redis, but the local cache records it, so the session is still dropped and
+ // marked seen on this consumer — counted once.
+ describe('when the blockSessions write (filter pipeline) fails on the first batch', () => {
+ it('a newly rate-limited session is counted once, dropped locally, but the block is not persisted', async () => {
+ useBucketCapacity(0) // force the session to be rate-limited so blockSessions runs
+
+ // blockSessions is the pipeline EXEC on the block keys; make it throw once on the first batch.
+ redis.failNext('exec', BLOCK_PREFIX)
+ await runBatch('rate-limited', 1)
+ expectFaultFired()
+ await runBatch('rate-limited', 2)
+
+ expect(timesCountedAsNew('rate-limited')).toBe(1)
+ // Fail-open write path: still blocked on this consumer (local cache → key never resolved) but
+ // not durable in Redis.
+ expect(keyWasResolvedFor('rate-limited')).toBe(false)
+ expect(redis.store.has(blockKey('rate-limited'))).toBe(false)
+ })
+ })
+
+ // Sustained outages: the op fails on EVERY batch, across many batches. Documents how the fail-open /
+ // fail-safe defaults behave when Redis stays down — the direction each degrades in, and that it
+ // doesn't drift over time.
+ describe('sustained outage (op fails on every batch)', () => {
+ const BATCHES = 6
+ const runBatches = async (sessionId: string): Promise<void> => {
+ for (let offset = 1; offset <= BATCHES; offset++) {
+ await runBatch(sessionId, offset)
+ }
+ }
+
+ it('hasSeen down: the batch fails hard (throws) rather than guessing — nothing is counted', async () => {
+ redis.failAlways('mget', SEEN_PREFIX)
+ setUpSessionType('allowed', 'a')
+
+ // Fail-hard: retries exhaust and the batch throws. The error propagates out, so the offset is
+ // never committed and the consumer crashes; Kafka reassigns the partition to another consumer
+ // that hits the same failure — a crash/rebalance loop that keeps the batch uncommitted until
+ // Redis recovers and it finally succeeds, rather than ever committing a keyless recording.
+ // hasSeen runs before counting, so nothing is counted.
+ await expect(runBatch('a', 1)).rejects.toThrow()
+ expect(timesCountedAsNew('a')).toBe(0)
+ })
+
+ it('markSeen down: the mark never reaches Redis, but the local cache keeps counting at once', async () => {
+ redis.failAlways('exec', SEEN_PREFIX)
+ setUpSessionType('allowed', 'a')
+
+ await runBatches('a')
+
+ expect(timesCountedAsNew('a')).toBe(1)
+ // Seen state is masked in the local cache only — nothing persisted for other consumers.
+ expect(redis.store.has(seenKey('a'))).toBe(false)
+ })
+
+ it('isBlocked down: an already-blocked session leaks past the block every batch; counting once', async () => {
+ redis.failAlways('mget', BLOCK_PREFIX)
+ setUpSessionType('blocked', 'a') // pre-seeded block flag that isBlocked can no longer read
+
+ await runBatches('a')
+
+ // Assumed not-blocked → key resolved (heads to recording) instead of dropped; counted once.
+ expect(keyWasResolvedFor('a')).toBe(true)
+ expect(timesCountedAsNew('a')).toBe(1)
+ })
+
+ it('blockSessions down: rate-limited sessions are counted once but never durably blocked', async () => {
+ useBucketCapacity(0)
+ redis.failAlways('exec', BLOCK_PREFIX)
+
+ await runBatches('rate-limited')
+
+ expect(timesCountedAsNew('rate-limited')).toBe(1)
+ expect(keyWasResolvedFor('rate-limited')).toBe(false)
+ expect(redis.store.has(blockKey('rate-limited'))).toBe(false)
+ })
+ })
+})
+
+interface MockRecorder {
+ record: jest.Mock
+}
+
+function createMockTopHog(): TopHogRegistry {
+ const make = () => new Map<string, MockRecorder>()
+ const sumRecorders = make()
+ const maxRecorders = make()
+ const averageRecorders = make()
+ return {
+ registerSum: jest.fn().mockImplementation((name: string) => {
+ const recorder = { record: jest.fn() }
+ sumRecorders.set(name, recorder)
+ return recorder
+ }),
+ registerMax: jest.fn().mockImplementation((name: string) => {
+ const recorder = { record: jest.fn() }
+ maxRecorders.set(name, recorder)
+ return recorder
+ }),
+ registerAverage: jest.fn().mockImplementation((name: string) => {
+ const recorder = { record: jest.fn() }
+ averageRecorders.set(name, recorder)
+ return recorder
+ }),
+ } as unknown as TopHogRegistry
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts
index 509d0e15275d..c7493c4924c5 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts
@@ -11,12 +11,15 @@ 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 { SessionFilter } from '~/ingestion/pipelines/sessionreplay/sessions/session-filter'
+import { SessionTracker } from '~/ingestion/pipelines/sessionreplay/sessions/session-tracker'
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 { createMockKeyStore, createMockSessionKey } from '~/ingestion/pipelines/sessionreplay/shared/test-helpers'
import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'
@@ -105,6 +108,24 @@ describe('session-replay-pipeline', () => {
}),
} as unknown as RetentionService
+ // Every session resolves as already-seen, unblocked, and with a cleartext key so messages flow
+ // through to recording.
+ const sessionTracker = {
+ hasSeen: jest.fn().mockImplementation((sessions: SessionSet) => {
+ const map = new SessionMap<boolean>()
+ for (const { teamId, sessionId } of sessions) {
+ map.set(teamId, sessionId, true)
+ }
+ return Promise.resolve(map)
+ }),
+ markSeen: jest.fn().mockResolvedValue(undefined),
+ } as unknown as SessionTracker
+ const sessionFilter = {
+ handleNewSessions: jest.fn().mockResolvedValue(new SessionSet()),
+ isBlocked: jest.fn().mockResolvedValue(new SessionSet()),
+ } as unknown as SessionFilter
+ const keyStore = createMockKeyStore()
+
const defaultTeam: TeamForReplay = {
teamId: 1,
consoleLogIngestionEnabled: false,
@@ -275,6 +296,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -306,6 +331,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -342,6 +371,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -361,6 +394,130 @@ describe('session-replay-pipeline', () => {
expect(offsets).toEqual(new Map([[0, 3]]))
})
+ it('tracks the offset of a rate-limited session even when it is the highest in the partition', async () => {
+ // Block session-3 — the highest offset — at the rate limiter, so nothing recorded advances the
+ // partition past it. That's what forces the blocked drop's own offset tracking to be exercised:
+ // if a lower-offset session were blocked, a later recorded message would move the offset anyway
+ // and mask a regression. Unlike the restriction/parse drops above, this drop happens on the
+ // session-key path (gate blocks it, mark-seen drops it), so it verifies that path is wired in too.
+ ;(sessionFilter.isBlocked as jest.Mock).mockImplementationOnce((sessions: SessionSet) => {
+ const blocked = new SessionSet()
+ for (const { teamId, sessionId } of sessions) {
+ if (sessionId === 'session-3') {
+ blocked.add(teamId, sessionId)
+ }
+ }
+ return Promise.resolve(blocked)
+ })
+
+ const pipeline = createSessionReplayPipeline({
+ outputs,
+ eventIngestionRestrictionManager: mockRestrictionManager,
+ overflowEnabled: true,
+ promiseScheduler,
+ teamService: mockTeamService,
+ retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
+ topHog,
+ sessionBatchManager: mockSessionBatchManager,
+ isDebugLoggingEnabled,
+ })
+
+ const messages = [
+ createMessage(0, 1, 'session-1'),
+ createMessage(0, 2, 'session-2'),
+ createMessage(0, 3, 'session-3'),
+ ]
+
+ const offsets = await runSessionReplayPipeline(pipeline, messages)
+
+ expect(recordedSessionIds()).toEqual(['session-1', 'session-2'])
+ // The highest offset on the partition belongs to the blocked session; it must still be tracked
+ // or that partition would never commit past offset 2.
+ expect(offsets).toEqual(new Map([[0, 3]]))
+ })
+
+ // Offsets are tracked per partition. Each case drops the highest-offset message on partition 0 via
+ // a different mechanism while partition 1 records a higher offset. Every case must advance
+ // partition 0 to its dropped message's offset (3) AND partition 1 to 5 — proving the partitions
+ // are tracked independently and a dropped, highest message isn't masked by, or bled into, another
+ // partition's activity.
+ it.each<{ name: string; configure: () => void }>([
+ {
+ name: 'a rate-limited session blocked at the gate',
+ configure: () => {
+ ;(sessionFilter.isBlocked as jest.Mock).mockResolvedValueOnce(new SessionSet().add(1, 'session-3'))
+ },
+ },
+ {
+ name: 'a session whose key was deleted, dropped at mark-seen',
+ configure: () => {
+ ;(keyStore.getKey as jest.Mock).mockImplementation((sessionId: string) =>
+ Promise.resolve(
+ sessionId === 'session-3'
+ ? createMockSessionKey({ sessionState: 'deleted', deletedAt: 1 })
+ : createMockSessionKey()
+ )
+ )
+ },
+ },
+ {
+ name: 'a session dropped by an event restriction before parse',
+ configure: () => {
+ mockCreateApplyEventRestrictionsStep.mockReturnValue(
+ (input: { message: Message; headers: Record<string, string> }) =>
+ Promise.resolve(
+ input.message.partition === 0 && input.message.offset === 3
+ ? drop('blocked')
+ : ok(input)
+ )
+ )
+ },
+ },
+ ])('tracks the dropped highest offset per partition when it is $name', async ({ configure }) => {
+ // Re-establish the pass-throughs these cases override — getKey/isBlocked are shared across the
+ // describe and survive clearAllMocks, so without this a case could leak into the next.
+ ;(sessionFilter.isBlocked as jest.Mock).mockResolvedValue(new SessionSet())
+ ;(keyStore.getKey as jest.Mock).mockResolvedValue(createMockSessionKey())
+ configure()
+
+ const pipeline = createSessionReplayPipeline({
+ outputs,
+ eventIngestionRestrictionManager: mockRestrictionManager,
+ overflowEnabled: true,
+ promiseScheduler,
+ teamService: mockTeamService,
+ retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
+ topHog,
+ sessionBatchManager: mockSessionBatchManager,
+ isDebugLoggingEnabled,
+ })
+
+ const messages = [
+ createMessage(0, 1, 'session-1'),
+ createMessage(0, 2, 'session-2'),
+ createMessage(0, 3, 'session-3'), // dropped, highest offset on partition 0
+ createMessage(1, 5, 'session-4'), // recorded on partition 1 at a higher offset
+ ]
+
+ const offsets = await runSessionReplayPipeline(pipeline, messages)
+
+ expect(recordedSessionIds().sort()).toEqual(['session-1', 'session-2', 'session-4'])
+ expect(offsets).toEqual(
+ new Map([
+ [0, 3],
+ [1, 5],
+ ])
+ )
+ })
+
it('filters out messages that fail to parse', async () => {
const pipeline = createSessionReplayPipeline({
outputs,
@@ -369,6 +526,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -403,6 +564,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -453,6 +618,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -485,6 +654,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -513,6 +686,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -557,6 +734,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -593,6 +774,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -632,6 +817,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: teamServiceThatDropsSecond,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -658,6 +847,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -681,6 +874,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -719,6 +916,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -740,6 +941,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -761,6 +966,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -798,6 +1007,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -817,7 +1030,8 @@ describe('session-replay-pipeline', () => {
session_id: 'session-1',
}),
}),
- '30d'
+ '30d',
+ expect.objectContaining({ sessionState: 'cleartext' })
)
})
@@ -829,6 +1043,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -857,6 +1075,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -884,6 +1106,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: teamServiceThatReturnsNull,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -907,6 +1133,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -934,6 +1164,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -961,6 +1195,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -988,6 +1226,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -1036,6 +1278,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled,
@@ -1083,6 +1329,10 @@ describe('session-replay-pipeline', () => {
promiseScheduler,
teamService: mockTeamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
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.ts
index bb7951450c6d..27db04a05c60 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts
@@ -12,15 +12,22 @@ 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 { SessionFilter } from '~/ingestion/pipelines/sessionreplay/sessions/session-filter'
+import { SessionTracker } from '~/ingestion/pipelines/sessionreplay/sessions/session-tracker'
import { RetentionService } from '~/ingestion/pipelines/sessionreplay/shared/retention/retention-service'
import { TeamService } from '~/ingestion/pipelines/sessionreplay/shared/teams/team-service'
+import { KeyStore } from '~/ingestion/pipelines/sessionreplay/shared/types'
import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
import { ValueMatcher } from '~/types'
import { createLibVersionMonitorStep } from './lib-version-monitor-step'
import { createParseMessageStep } from './parse-message-step'
+import { MessageContext } from './pipeline-types'
import { createRecordSessionEventStep } from './record-session-event-step'
+import { createMarkSeenStep } from './session-batch-mark-seen-step'
import { createResolveRetentionStep } from './session-batch-resolve-retention-step'
+import { createTrackAndGateStep } from './session-batch-track-and-gate-step'
+import { createResolveKeyStep } from './session-resolve-key-step'
import { createTeamFilterStep } from './team-filter-step'
import { createValidateSessionReplayHeadersStep } from './validate-headers-step'
@@ -41,6 +48,14 @@ export interface SessionReplayPipelineConfig {
teamService: TeamService
/** Resolves per-session retention before recording, so keys and storage route correctly */
retentionService: RetentionService
+ /** Detects newly-seen sessions during the pre-record session-key resolution. */
+ sessionTracker: SessionTracker
+ /** Blocks and rate-limits new sessions during the pre-record session-key resolution. */
+ sessionFilter: SessionFilter
+ /** Resolves per-session encryption keys before recording. */
+ keyStore: KeyStore
+ /** Caps how many sessions resolve their encryption key concurrently, bounding KMS/DynamoDB fan-out. */
+ sessionKeyResolutionMaxConcurrency: number
/** TopHog registry for tracking metrics. */
topHog: TopHogRegistry
/** Session batch manager for recording sessions. */
@@ -64,8 +79,8 @@ export function createSessionReplayPipeline(
): BatchPipeline<
SessionReplayPipelineInput,
SessionReplayPipelineOutput,
- { message: Message },
- { message: Message },
+ MessageContext,
+ MessageContext,
OverflowOutput
> {
const {
@@ -75,6 +90,10 @@ export function createSessionReplayPipeline(
promiseScheduler,
teamService,
retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency,
topHog,
sessionBatchManager,
isDebugLoggingEnabled,
@@ -87,7 +106,7 @@ export function createSessionReplayPipeline(
const topHogWrapper = createTopHogWrapper(topHog)
- const pipeline = newBatchPipelineBuilder<SessionReplayPipelineInput, { message: Message }>()
+ const pipeline = newBatchPipelineBuilder<SessionReplayPipelineInput, MessageContext>()
.messageAware((b) =>
b
.sequentially((b) =>
@@ -113,6 +132,35 @@ export function createSessionReplayPipeline(
tries: 3,
sleepMs: 100,
})
+ // Track sessions and rate-limit new ones for the whole batch, tagging the survivors with
+ // isNewSession and dropping the blocked ones right here (they carry no key, so nothing
+ // downstream acts on them). Its own retry scope means a later key-resolution failure never
+ // re-runs the rate limiter and double-charges the budget.
+ .pipeBatchWithRetry(createTrackAndGateStep(sessionTracker, sessionFilter), {
+ tries: 3,
+ sleepMs: 100,
+ })
+ // Resolve each session's encryption key. Grouped by session so it runs once per session
+ // (the cached keystore fans the key to its other messages) and concurrently across
+ // sessions, capped to bound KMS/DynamoDB fan-out. Per-session retry isolates a transient
+ // keystore blip to that one session. Deleted sessions are dropped here.
+ .groupBy((element) => `${element.team.teamId}:${element.headers.session_id}`)
+ .concurrently(
+ (group) =>
+ group.sequentially((b) =>
+ b.retry((rb) => rb.pipe(createResolveKeyStep(keyStore)), {
+ name: 'resolve_session_key',
+ tries: 3,
+ sleepMs: 100,
+ })
+ ),
+ { maxConcurrency: sessionKeyResolutionMaxConcurrency }
+ )
+ // Re-collect the per-session groups into one batch — both to mark the whole batch seen
+ // in a single Redis write and as the barrier that guarantees every key is resolved first.
+ .gather()
+ // Mark the surviving new sessions seen, now that every key is durably resolved.
+ .pipeBatch(createMarkSeenStep(sessionTracker))
// Map TeamForReplay.teamId to context.team.id for handleIngestionWarnings
.filterMap(
(element) => ({
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-resolve-key-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-resolve-key-step.test.ts
new file mode 100644
index 000000000000..d207c6399bce
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-resolve-key-step.test.ts
@@ -0,0 +1,89 @@
+import { PipelineResult, isOkResult } from '~/ingestion/framework/results'
+import { RetentionPeriod, RetentionPeriodToDaysMap } from '~/ingestion/pipelines/sessionreplay/shared/constants'
+import { createMockSessionKey } from '~/ingestion/pipelines/sessionreplay/shared/test-helpers'
+import { KeyStore, SessionKey } from '~/ingestion/pipelines/sessionreplay/shared/types'
+import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
+
+import { Allowed, NewSessionFlag, Resolved, SessionReplayHeaders } from './pipeline-types'
+import { createResolveKeyStep } from './session-resolve-key-step'
+
+type Base = {
+ team: TeamForReplay
+ headers: SessionReplayHeaders
+ retentionPeriod: RetentionPeriod
+} & NewSessionFlag
+
+describe('createResolveKeyStep', () => {
+ let mockKeyStore: jest.Mocked<Pick<KeyStore, 'generateKey' | 'getKey'>>
+
+ // Only allowed sessions reach this step — blocked ones are dropped at the gate upstream.
+ const element = (
+ teamId: number,
+ sessionId: string,
+ isNewSession: boolean,
+ retentionPeriod: RetentionPeriod = '30d'
+ ): Allowed<Base> =>
+ ({
+ team: { teamId, consoleLogIngestionEnabled: false, aiTrainingOptedIn: true },
+ headers: { token: 'token', session_id: sessionId, distinct_id: 'distinct-1' },
+ retentionPeriod,
+ isNewSession,
+ status: 'allowed',
+ }) as unknown as Allowed<Base>
+
+ // Reads the resolved key off an ok, allowed result (blocked/deleted results carry no key).
+ const keyOf = (result: PipelineResult<Resolved<Base>>): SessionKey | null =>
+ isOkResult(result) && result.value.status === 'allowed' ? result.value.sessionKey : null
+
+ // Reads the verdict status off an ok result.
+ const statusOf = (result: PipelineResult<Resolved<Base>>): string | null =>
+ isOkResult(result) ? result.value.status : null
+
+ const createStep = () => createResolveKeyStep(mockKeyStore as unknown as KeyStore)
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ mockKeyStore = {
+ generateKey: jest.fn().mockResolvedValue(createMockSessionKey()),
+ getKey: jest.fn().mockResolvedValue(createMockSessionKey()),
+ }
+ })
+
+ it('generates a key for a new allowed session using the resolved retention', async () => {
+ const generated = createMockSessionKey({ encryptedKey: Buffer.from('new-key') })
+ mockKeyStore.generateKey.mockResolvedValue(generated)
+
+ const result = await createStep()(element(1, 'a', true, '90d'))
+
+ expect(mockKeyStore.generateKey).toHaveBeenCalledWith('a', 1, RetentionPeriodToDaysMap['90d'])
+ expect(mockKeyStore.getKey).not.toHaveBeenCalled()
+ expect(keyOf(result)).toBe(generated)
+ })
+
+ it('fetches the existing key for a seen allowed session', async () => {
+ const existing = createMockSessionKey({ encryptedKey: Buffer.from('existing-key') })
+ mockKeyStore.getKey.mockResolvedValue(existing)
+
+ const result = await createStep()(element(1, 'a', false))
+
+ expect(mockKeyStore.getKey).toHaveBeenCalledWith('a', 1)
+ expect(mockKeyStore.generateKey).not.toHaveBeenCalled()
+ expect(keyOf(result)).toBe(existing)
+ })
+
+ it('carries a session whose key has been deleted through, tagged deleted (dropped later)', async () => {
+ mockKeyStore.getKey.mockResolvedValue(createMockSessionKey({ sessionState: 'deleted', deletedAt: 1 }))
+
+ const result = await createStep()(element(1, 'gone', false))
+
+ // Not dropped here — the mark-seen step marks it seen (so it isn't re-counted) then drops it.
+ expect(statusOf(result)).toBe('deleted')
+ expect(keyOf(result)).toBeNull()
+ })
+
+ it('propagates a keystore failure so the retry regenerates rather than recording keyless', async () => {
+ mockKeyStore.generateKey.mockRejectedValue(new Error('KMS unavailable'))
+
+ await expect(createStep()(element(1, 'a', true))).rejects.toThrow('KMS unavailable')
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-resolve-key-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-resolve-key-step.ts
new file mode 100644
index 000000000000..c94e10851b03
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-resolve-key-step.ts
@@ -0,0 +1,53 @@
+import { ok } from '~/ingestion/framework/results'
+import { ProcessingStep } from '~/ingestion/framework/steps'
+import { RetentionPeriod, RetentionPeriodToDaysMap } from '~/ingestion/pipelines/sessionreplay/shared/constants'
+import { KeyStore } from '~/ingestion/pipelines/sessionreplay/shared/types'
+import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
+
+import { Allowed, NewSessionFlag, Resolved, SessionReplayHeaders } from './pipeline-types'
+
+/** The minimal per-element shape this step needs to resolve a session's key. */
+type ResolveKeyStepInput = {
+ team: TeamForReplay
+ headers: SessionReplayHeaders
+ retentionPeriod: RetentionPeriod
+} & NewSessionFlag
+
+/**
+ * Record-phase per-session step: resolve a session's encryption key, off the S3 write path. Wired under
+ * a `groupBy(session)` so it runs once per distinct session and the memory-cached keystore fans the key
+ * out to the session's other messages, and under a per-session retry so a transient keystore blip
+ * re-runs just that session rather than its batch-siblings.
+ *
+ * Only allowed sessions reach this step — blocked ones are dropped at the gate. An allowed new session
+ * generates a key (using the retention resolved upstream to set the key's expiry); an allowed existing
+ * one fetches it. A session whose key has been deleted is re-tagged `deleted` and carried through — the
+ * mark-seen step marks it seen (safe: its tombstone outlives the seen flag) and then drops it, so a
+ * deleted session isn't re-counted against the rate limit every batch.
+ *
+ * This step is the encryption boundary, so it obeys the integrity rule (rule 2 — see {@link SessionTracker}
+ * class doc): it FAILS HARD rather than ever producing a keyless recording. A transient keystore failure
+ * (KMS/DynamoDB) throws so the retry wrapper re-runs it. And because the session is never marked seen
+ * before its key is durably generated (see {@link createMarkSeenStep}), a retry regenerates the key
+ * rather than fetching one that was never created — which would record cleartext. The upstream
+ * {@link createTrackAndGateStep} guarantees the new-vs-existing input here is correct or absent (its
+ * hasSeen also fails hard), so this step never fetches a key for a genuinely-new session.
+ */
+export function createResolveKeyStep<T extends ResolveKeyStepInput>(
+ keyStore: KeyStore
+): ProcessingStep<Allowed<T>, Resolved<T>> {
+ return async function resolveKeyStep(value) {
+ const teamId = value.team.teamId
+ const sessionId = value.headers.session_id
+
+ const sessionKey = value.isNewSession
+ ? await keyStore.generateKey(sessionId, teamId, RetentionPeriodToDaysMap[value.retentionPeriod])
+ : await keyStore.getKey(sessionId, teamId)
+
+ if (sessionKey.sessionState === 'deleted') {
+ return ok({ ...value, status: 'deleted' as const })
+ }
+
+ return ok({ ...value, sessionKey })
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.test.ts
index 7a55264177c9..1b13a3dce324 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.test.ts
@@ -1,15 +1,13 @@
import { KafkaOffsetManager } from '~/ingestion/pipelines/sessionreplay/kafka/offset-manager'
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'
-import { KeyStore, RecordingEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/types'
+import { createMockEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/test-helpers'
+import { RecordingEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/types'
import { SessionBatchFileStorage, SessionBatchFileWriter } from './session-batch-file-storage'
import { SessionBatchManager } from './session-batch-manager'
import { SessionBatchRecorder } from './session-batch-recorder'
import { SessionConsoleLogStore } from './session-console-log-store'
-import { SessionFilter } from './session-filter'
-import { SessionTracker } from './session-tracker'
jest.setTimeout(1000)
jest.mock('./session-batch-recorder')
@@ -23,9 +21,6 @@ describe('SessionBatchManager', () => {
let mockMetadataStore: jest.Mocked<SessionMetadataStore>
let mockConsoleLogStore: jest.Mocked<SessionConsoleLogStore>
let mockFeatureStore: jest.Mocked<SessionFeatureStore>
- let mockSessionTracker: jest.Mocked<SessionTracker>
- let mockSessionFilter: jest.Mocked<SessionFilter>
- let mockKeyStore: jest.Mocked<KeyStore>
let mockEncryptor: jest.Mocked<RecordingEncryptor>
const createMockBatch = (): jest.Mocked<SessionBatchRecorder> =>
@@ -71,16 +66,6 @@ describe('SessionBatchManager', () => {
storeSessionFeatures: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<SessionFeatureStore>
- mockSessionTracker = {
- trackSession: jest.fn().mockResolvedValue(false),
- } as unknown as jest.Mocked<SessionTracker>
-
- mockSessionFilter = {
- isBlocked: jest.fn().mockResolvedValue(false),
- handleNewSession: jest.fn().mockResolvedValue(undefined),
- } as unknown as jest.Mocked<SessionFilter>
-
- mockKeyStore = createMockKeyStore()
mockEncryptor = createMockEncryptor()
manager = new SessionBatchManager({
@@ -92,9 +77,6 @@ describe('SessionBatchManager', () => {
metadataStore: mockMetadataStore,
consoleLogStore: mockConsoleLogStore,
featureStore: mockFeatureStore,
- sessionTracker: mockSessionTracker,
- sessionFilter: mockSessionFilter,
- keyStore: mockKeyStore,
encryptor: mockEncryptor,
})
})
@@ -114,9 +96,6 @@ describe('SessionBatchManager', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor,
Number.MAX_SAFE_INTEGER,
100
@@ -198,9 +177,6 @@ describe('SessionBatchManager', () => {
metadataStore: mockMetadataStore,
consoleLogStore: mockConsoleLogStore,
featureStore: mockFeatureStore,
- sessionTracker: mockSessionTracker,
- sessionFilter: mockSessionFilter,
- keyStore: mockKeyStore,
encryptor: mockEncryptor,
})
@@ -210,9 +186,6 @@ describe('SessionBatchManager', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor,
500,
100
@@ -229,9 +202,6 @@ describe('SessionBatchManager', () => {
metadataStore: mockMetadataStore,
consoleLogStore: mockConsoleLogStore,
featureStore: mockFeatureStore,
- sessionTracker: mockSessionTracker,
- sessionFilter: mockSessionFilter,
- keyStore: mockKeyStore,
encryptor: mockEncryptor,
})
@@ -243,9 +213,6 @@ describe('SessionBatchManager', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor,
250,
100
@@ -262,9 +229,6 @@ describe('SessionBatchManager', () => {
metadataStore: mockMetadataStore,
consoleLogStore: mockConsoleLogStore,
featureStore: mockFeatureStore,
- sessionTracker: mockSessionTracker,
- sessionFilter: mockSessionFilter,
- keyStore: mockKeyStore,
encryptor: mockEncryptor,
})
@@ -274,9 +238,6 @@ describe('SessionBatchManager', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor,
0,
100
@@ -293,9 +254,6 @@ describe('SessionBatchManager', () => {
metadataStore: mockMetadataStore,
consoleLogStore: mockConsoleLogStore,
featureStore: mockFeatureStore,
- sessionTracker: mockSessionTracker,
- sessionFilter: mockSessionFilter,
- keyStore: mockKeyStore,
encryptor: mockEncryptor,
})
@@ -305,9 +263,6 @@ describe('SessionBatchManager', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor,
Number.MAX_SAFE_INTEGER,
100
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.ts
index 3a90c0ee5ad0..357db7d363c7 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.ts
@@ -2,13 +2,11 @@ import { logger } from '~/common/utils/logger'
import { KafkaOffsetManager } from '~/ingestion/pipelines/sessionreplay/kafka/offset-manager'
import { SessionFeatureStore } from '~/ingestion/pipelines/sessionreplay/shared/features/session-feature-store'
import { SessionMetadataSink } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-metadata-store'
-import { KeyStore, RecordingEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/types'
+import { RecordingEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/types'
import { SessionBatchFileStorage } from './session-batch-file-storage'
import { SessionBatchRecorder } from './session-batch-recorder'
import { SessionConsoleLogStore } from './session-console-log-store'
-import { SessionFilter } from './session-filter'
-import { SessionTracker } from './session-tracker'
export interface SessionBatchManagerConfig {
/** Maximum raw size (before compression) of a batch in bytes before it should be flushed */
@@ -29,12 +27,6 @@ export interface SessionBatchManagerConfig {
consoleLogStore: SessionConsoleLogStore
/** Manages storing session features for ML scoring */
featureStore: SessionFeatureStore
- /** Session tracker for new session detection */
- sessionTracker: SessionTracker
- /** Session filter for blocking and rate-limiting sessions */
- sessionFilter: SessionFilter
- /** Key store for session encryption keys */
- keyStore: KeyStore
/** Encryptor for session recording data */
encryptor: RecordingEncryptor
}
@@ -85,9 +77,6 @@ export class SessionBatchManager {
private readonly consoleLogStore: SessionConsoleLogStore
private readonly featureStore: SessionFeatureStore
private lastFlushTime: number
- private readonly sessionTracker: SessionTracker
- private readonly sessionFilter: SessionFilter
- private readonly keyStore: KeyStore
private readonly encryptor: RecordingEncryptor
constructor(config: SessionBatchManagerConfig) {
@@ -100,9 +89,6 @@ export class SessionBatchManager {
this.metadataStore = config.metadataStore
this.consoleLogStore = config.consoleLogStore
this.featureStore = config.featureStore
- this.sessionTracker = config.sessionTracker
- this.sessionFilter = config.sessionFilter
- this.keyStore = config.keyStore
this.encryptor = config.encryptor
this.currentBatch = new SessionBatchRecorder(
@@ -111,9 +97,6 @@ export class SessionBatchManager {
this.metadataStore,
this.consoleLogStore,
this.featureStore,
- this.sessionTracker,
- this.sessionFilter,
- this.keyStore,
this.encryptor,
this.maxEventsPerSessionPerBatch,
this.featuresRolloutPercentage
@@ -154,9 +137,6 @@ export class SessionBatchManager {
this.metadataStore,
this.consoleLogStore,
this.featureStore,
- this.sessionTracker,
- this.sessionFilter,
- this.keyStore,
this.encryptor,
this.maxEventsPerSessionPerBatch,
this.featuresRolloutPercentage
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts
index c5a57db51110..ed42fc5ad9f4 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
@@ -7,8 +7,8 @@ import { ParsedMessageData, SnapshotEvent } from '~/ingestion/pipelines/sessionr
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'
-import { KeyStore, RecordingEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/types'
+import { createMockEncryptor, createMockSessionKey } from '~/ingestion/pipelines/sessionreplay/shared/test-helpers'
+import { RecordingEncryptor, SessionKey } from '~/ingestion/pipelines/sessionreplay/shared/types'
import { MessageWithTeam } from '~/ingestion/pipelines/sessionreplay/teams/types'
import { SessionBatchMetrics } from './metrics'
@@ -17,8 +17,6 @@ import { SessionBatchRecorder } from './session-batch-recorder'
import { SessionConsoleLogRecorder } from './session-console-log-recorder'
import { SessionConsoleLogStore } from './session-console-log-store'
import { SessionFeatureRecorder } from './session-feature-recorder'
-import { SessionFilter } from './session-filter'
-import { SessionTracker } from './session-tracker'
import { EndResult, SnappySessionRecorder } from './snappy-session-recorder'
// RRWeb event type constants
@@ -205,14 +203,15 @@ describe('SessionBatchRecorder', () => {
let mockMetadataStore: jest.Mocked<SessionMetadataStore>
let mockConsoleLogStore: jest.Mocked<SessionConsoleLogStore>
let mockFeatureStore: jest.Mocked<SessionFeatureStore>
- let mockSessionTracker: jest.Mocked<SessionTracker>
- let mockSessionFilter: jest.Mocked<SessionFilter>
- 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)
+ // Records a message with its resolved retention and encryption key (both resolved upstream in
+ // production). Defaults to 30d and a fresh cleartext key — most tests don't vary either.
+ const record = (
+ message: MessageWithTeam,
+ retentionPeriod: RetentionPeriod = '30d',
+ sessionKey: SessionKey = createMockSessionKey()
+ ): Promise<number> => recorder.record(message, retentionPeriod, sessionKey)
beforeEach(() => {
jest.clearAllMocks()
@@ -253,16 +252,6 @@ describe('SessionBatchRecorder', () => {
newBatch: jest.fn().mockReturnValue(mockWriter),
} as unknown as jest.Mocked<SessionBatchFileStorage>
- mockSessionTracker = {
- trackSession: jest.fn().mockResolvedValue(false),
- } as unknown as jest.Mocked<SessionTracker>
-
- mockSessionFilter = {
- isBlocked: jest.fn().mockResolvedValue(false),
- handleNewSession: jest.fn().mockResolvedValue(undefined),
- } as unknown as jest.Mocked<SessionFilter>
-
- mockKeyStore = createMockKeyStore()
mockEncryptor = createMockEncryptor()
recorder = new SessionBatchRecorder(
@@ -271,9 +260,6 @@ describe('SessionBatchRecorder', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor,
Number.MAX_SAFE_INTEGER
)
@@ -1518,9 +1504,6 @@ describe('SessionBatchRecorder', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor,
Number.MAX_SAFE_INTEGER
)
@@ -1721,9 +1704,6 @@ describe('SessionBatchRecorder', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor,
3
)
@@ -1751,9 +1731,6 @@ describe('SessionBatchRecorder', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor,
2
)
@@ -1784,9 +1761,6 @@ describe('SessionBatchRecorder', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor,
1
)
@@ -1810,9 +1784,6 @@ describe('SessionBatchRecorder', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor,
2
)
@@ -1849,9 +1820,6 @@ describe('SessionBatchRecorder', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor,
2
)
@@ -1888,9 +1856,6 @@ describe('SessionBatchRecorder', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor,
1
)
@@ -1921,9 +1886,6 @@ describe('SessionBatchRecorder', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor,
1
)
@@ -1956,9 +1918,6 @@ describe('SessionBatchRecorder', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor,
2
)
@@ -1988,9 +1947,6 @@ describe('SessionBatchRecorder', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor,
1
)
@@ -2019,9 +1975,6 @@ describe('SessionBatchRecorder', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor,
1
)
@@ -2051,9 +2004,6 @@ describe('SessionBatchRecorder', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor,
1
)
@@ -2086,42 +2036,12 @@ describe('SessionBatchRecorder', () => {
})
describe('encryption key handling', () => {
- it('should drop messages for sessions with deleted encryption keys', async () => {
- mockSessionTracker.trackSession.mockResolvedValue(false)
- mockKeyStore.getKey.mockResolvedValue({
- plaintextKey: Buffer.alloc(0),
- encryptedKey: Buffer.alloc(0),
- sessionState: 'deleted',
- deletedAt: 1700000000,
- })
-
- const message = createMessage(
- 'session1',
- [{ type: EventType.FullSnapshot, timestamp: 1000, data: { source: 1 } }],
- { partition: 1, offset: 42 }
- )
-
- const bytesWritten = await record(message)
-
- expect(bytesWritten).toBe(0)
- })
-
- it('should drop messages when session key changes between calls', async () => {
- const keyA = Buffer.from('key-a')
- const keyB = Buffer.from('key-b')
-
- mockSessionTracker.trackSession.mockResolvedValueOnce(true).mockResolvedValueOnce(false)
-
- mockKeyStore.generateKey.mockResolvedValue({
- plaintextKey: Buffer.alloc(0),
- encryptedKey: keyA,
- sessionState: 'cleartext',
- })
- mockKeyStore.getKey.mockResolvedValue({
- plaintextKey: Buffer.alloc(0),
- encryptedKey: keyB,
- sessionState: 'cleartext',
- })
+ it('should drop messages when the session key changes between calls for the same session', async () => {
+ // The key is resolved upstream; the recorder must reject a second message that arrives
+ // with a different key for a session already in the batch, so a block isn't corrupted by
+ // events encrypted for two different keys.
+ const keyA = createMockSessionKey({ encryptedKey: Buffer.from('key-a') })
+ const keyB = createMockSessionKey({ encryptedKey: Buffer.from('key-b') })
const message1 = createMessage(
'session1',
@@ -2134,66 +2054,11 @@ describe('SessionBatchRecorder', () => {
{ partition: 1, offset: 1 }
)
- const bytes1 = await record(message1)
- const bytes2 = await record(message2)
+ const bytes1 = await record(message1, '30d', keyA)
+ const bytes2 = await record(message2, '30d', keyB)
expect(bytes1).toBeGreaterThan(0)
expect(bytes2).toBe(0)
})
})
-
- describe('new session rate limiting', () => {
- it('should call handleNewSession for new sessions', async () => {
- mockSessionTracker.trackSession.mockResolvedValue(true)
-
- const message = createMessage('session1', [
- { type: EventType.FullSnapshot, timestamp: 1000, data: { source: 1 } },
- ])
-
- await record(message)
-
- expect(mockSessionFilter.handleNewSession).toHaveBeenCalledWith(1, 'session1')
- })
-
- it('should not call handleNewSession for existing sessions', async () => {
- mockSessionTracker.trackSession.mockResolvedValue(false)
-
- const message = createMessage('session1', [
- { type: EventType.FullSnapshot, timestamp: 1000, data: { source: 1 } },
- ])
-
- await record(message)
-
- expect(mockSessionFilter.handleNewSession).not.toHaveBeenCalled()
- })
-
- it('should drop message when session is blocked after handleNewSession', async () => {
- mockSessionTracker.trackSession.mockResolvedValue(true)
- // Simulate handleNewSession blocking the session by having isBlocked return true
- mockSessionFilter.isBlocked.mockResolvedValue(true)
-
- const message = createMessage('session1', [
- { type: EventType.FullSnapshot, timestamp: 1000, data: { source: 1 } },
- ])
-
- const bytesWritten = await record(message)
-
- expect(bytesWritten).toBe(0)
- expect(mockSessionFilter.handleNewSession).toHaveBeenCalledWith(1, 'session1')
- expect(mockSessionFilter.isBlocked).toHaveBeenCalledWith(1, 'session1')
- })
-
- it('should allow new session when not blocked', async () => {
- mockSessionTracker.trackSession.mockResolvedValue(true)
- mockSessionFilter.isBlocked.mockResolvedValue(false)
-
- const message = createMessage('session1', [
- { type: EventType.FullSnapshot, timestamp: 1000, data: { source: 1 } },
- ])
-
- 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.ts
index d834cdab7466..f0bffdecfc63 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts
@@ -3,7 +3,7 @@ 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 { RetentionPeriod } from '~/ingestion/pipelines/sessionreplay/shared/constants'
import {
SessionFeatureBlock,
SessionFeatureStore,
@@ -11,7 +11,7 @@ import {
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 { RecordingEncryptor, SessionKey } from '~/ingestion/pipelines/sessionreplay/shared/types'
import { MessageWithTeam } from '~/ingestion/pipelines/sessionreplay/teams/types'
import { SessionBatchMetrics } from './metrics'
@@ -19,9 +19,7 @@ import { SessionBatchFileStorage } from './session-batch-file-storage'
import { SessionConsoleLogRecorder } from './session-console-log-recorder'
import { SessionConsoleLogStore } from './session-console-log-store'
import { SessionFeatureRecorder } from './session-feature-recorder'
-import { SessionFilter } from './session-filter'
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)`. */
@@ -94,9 +92,6 @@ export class SessionBatchRecorder {
private readonly metadataStore: SessionMetadataSink,
private readonly consoleLogStore: SessionConsoleLogStore,
private readonly featureStore: SessionFeatureStore,
- private readonly sessionTracker: SessionTracker,
- private readonly sessionFilter: SessionFilter,
- private readonly keyStore: KeyStore,
private readonly encryptor: RecordingEncryptor,
maxEventsPerSessionPerBatch: number = Number.MAX_SAFE_INTEGER,
private readonly featuresRolloutPercentage: number = 100
@@ -112,44 +107,19 @@ export class SessionBatchRecorder {
* @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.
+ * @param sessionKey - The session's encryption key, resolved upstream by the track-and-gate and
+ * resolve-key steps (which also drop blocked/deleted sessions before they reach here).
* @returns Number of raw bytes written (without compression)
*/
- public async record(message: MessageWithTeam, retentionPeriod: RetentionPeriod): Promise<number> {
+ public async record(
+ message: MessageWithTeam,
+ retentionPeriod: RetentionPeriod,
+ sessionKey: SessionKey
+ ): Promise<number> {
const { partition } = message.message.metadata
const sessionId = message.message.session_id
const teamId = message.team.teamId
- // Check if this is a new session and check if we're in breach of the rate limit
- const isNewSession = await this.sessionTracker.trackSession(teamId, sessionId)
- if (isNewSession) {
- await this.sessionFilter.handleNewSession(teamId, sessionId)
- }
-
- // Check if session is blocked
- if (await this.sessionFilter.isBlocked(teamId, sessionId)) {
- logger.debug('🔁', 'session_batch_recorder_session_blocked', {
- partition,
- sessionId,
- teamId,
- batchId: this.batchId,
- })
- return 0
- }
-
- const sessionKey = isNewSession
- ? await this.keyStore.generateKey(sessionId, teamId, RetentionPeriodToDaysMap[retentionPeriod])
- : await this.keyStore.getKey(sessionId, teamId)
-
- if (sessionKey.sessionState === 'deleted') {
- logger.debug('🔁', 'session_batch_recorder_deleted_session_dropped', {
- partition,
- sessionId,
- teamId,
- batchId: this.batchId,
- })
- return 0
- }
-
const isEventAllowed = this.rateLimiter.handleMessage(teamId, sessionId, partition, message.message)
if (!isEventAllowed) {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-filter.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-filter.test.ts
index ec3db3805f1e..2b167c8dfdda 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-filter.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-filter.test.ts
@@ -1,4 +1,5 @@
import { Limiter } from '~/common/utils/token-bucket'
+import { SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'
import { RedisPool } from '~/types'
import { SessionBatchMetrics } from './metrics'
@@ -17,18 +18,31 @@ jest.mock('./metrics', () => ({
jest.mock('~/common/utils/token-bucket')
+const sessionSet = (...pairs: [number, string][]): SessionSet => {
+ const set = new SessionSet()
+ pairs.forEach(([teamId, sessionId]) => set.add(teamId, sessionId))
+ return set
+}
+
describe('SessionFilter', () => {
let sessionFilter: SessionFilter
- let mockRedis: { set: jest.Mock; exists: jest.Mock }
+ let mockPipeline: { set: jest.Mock; exec: jest.Mock }
+ let mockRedis: { set: jest.Mock; mget: jest.Mock; pipeline: jest.Mock }
let mockRedisPool: jest.Mocked<RedisPool>
let mockConsume: jest.Mock
+ // Single-session convenience over the batched isBlocked, so the behavior assertions stay focused.
+ const blocked = (filter: SessionFilter, teamId: number, sessionId: string): Promise<boolean> =>
+ filter.isBlocked(sessionSet([teamId, sessionId])).then((s) => s.has(teamId, sessionId))
+
beforeEach(() => {
jest.clearAllMocks()
+ mockPipeline = { set: jest.fn().mockReturnThis(), exec: jest.fn().mockResolvedValue([]) }
mockRedis = {
set: jest.fn().mockResolvedValue('OK'),
- exists: jest.fn().mockResolvedValue(0),
+ mget: jest.fn().mockResolvedValue([null]),
+ pipeline: jest.fn().mockReturnValue(mockPipeline),
}
mockRedisPool = {
@@ -51,24 +65,47 @@ describe('SessionFilter', () => {
})
})
- describe('blocking via handleNewSession', () => {
+ describe('blocking via handleNewSessions', () => {
it('should set a key in Redis with TTL when rate limited', async () => {
mockConsume.mockReturnValue(false)
- await sessionFilter.handleNewSession(1, 'session-123')
+ await sessionFilter.handleNewSessions(sessionSet([1, 'session-123']))
- expect(mockRedis.set).toHaveBeenCalledWith(
+ expect(mockPipeline.set).toHaveBeenCalledWith(
'@posthog/replay/session-blocked:1:session-123',
'1',
'EX',
48 * 60 * 60
)
+ expect(mockPipeline.exec).toHaveBeenCalledTimes(1)
+ })
+
+ it('namespaces the block key when a key namespace is given, isolating it from the main lane', async () => {
+ mockConsume.mockReturnValue(false)
+ const namespaced = new SessionFilter({
+ redisPool: mockRedisPool,
+ bucketCapacity: 1000,
+ bucketReplenishRate: 1,
+ blockingEnabled: true,
+ filterEnabled: true,
+ localCacheTtlMs: 5 * 60 * 1000,
+ keyNamespace: 'ml-mirror',
+ })
+
+ await namespaced.handleNewSessions(sessionSet([1, 'session-123']))
+
+ expect(mockPipeline.set).toHaveBeenCalledWith(
+ '@posthog/replay/ml-mirror/session-blocked:1:session-123',
+ '1',
+ 'EX',
+ 48 * 60 * 60
+ )
})
it('should increment metrics when blocking a session', async () => {
mockConsume.mockReturnValue(false)
- await sessionFilter.handleNewSession(1, 'session-123')
+ await sessionFilter.handleNewSessions(sessionSet([1, 'session-123']))
expect(SessionBatchMetrics.incrementSessionsBlocked).toHaveBeenCalled()
})
@@ -76,7 +113,7 @@ describe('SessionFilter', () => {
it('should acquire and release Redis connection', async () => {
mockConsume.mockReturnValue(false)
- await sessionFilter.handleNewSession(1, 'session-123')
+ await sessionFilter.handleNewSessions(sessionSet([1, 'session-123']))
expect(mockRedisPool.acquire).toHaveBeenCalled()
expect(mockRedisPool.release).toHaveBeenCalledWith(mockRedis)
@@ -84,105 +121,142 @@ describe('SessionFilter', () => {
it('should fail open on Redis error but still block locally', async () => {
mockConsume.mockReturnValue(false)
- mockRedis.set.mockRejectedValue(new Error('Redis error'))
+ mockPipeline.exec.mockRejectedValue(new Error('Redis error'))
// Should not throw - fails open
- await sessionFilter.handleNewSession(1, 'session-123')
+ await sessionFilter.handleNewSessions(sessionSet([1, 'session-123']))
expect(mockRedisPool.release).toHaveBeenCalledWith(mockRedis)
expect(SessionBatchMetrics.incrementSessionFilterRedisErrors).toHaveBeenCalled()
// Session should still be blocked locally (via cache set before Redis call)
- const isBlocked = await sessionFilter.isBlocked(1, 'session-123')
- expect(isBlocked).toBe(true)
+ expect(await blocked(sessionFilter, 1, 'session-123')).toBe(true)
expect(SessionBatchMetrics.incrementSessionFilterCacheHit).toHaveBeenCalled()
})
})
describe('isBlocked', () => {
- it('should return false for non-blocked session', async () => {
- mockRedis.exists.mockResolvedValue(0)
+ it('resolves a batch in a single MGET, keyed by (teamId, sessionId)', async () => {
+ mockRedis.mget = jest.fn().mockResolvedValue([null, '1'])
+
+ const result = await sessionFilter.isBlocked(sessionSet([1, 'open'], [1, 'blocked']))
+
+ expect(result.has(1, 'open')).toBe(false)
+ expect(result.has(1, 'blocked')).toBe(true)
+ expect(mockRedis.mget).toHaveBeenCalledTimes(1)
+ expect(mockRedis.mget).toHaveBeenCalledWith([
+ '@posthog/replay/session-blocked:1:open',
+ '@posthog/replay/session-blocked:1:blocked',
+ ])
+ })
+
+ it('mgets only the uncached sessions in a batch and merges them with the local cache', async () => {
+ // Seed the local cache with a blocked session (handleNewSessions caches without any read).
+ mockConsume.mockReturnValue(false)
+ await sessionFilter.handleNewSessions(sessionSet([1, 'cached-blocked']))
- const result = await sessionFilter.isBlocked(1, 'session-123')
+ // A later batch mixes the cached session with two it hasn't seen.
+ mockRedis.mget.mockResolvedValue(['1', null])
+ const result = await sessionFilter.isBlocked(
+ sessionSet([1, 'cached-blocked'], [1, 'uncached-blocked'], [1, 'uncached-open'])
+ )
- expect(result).toBe(false)
- expect(mockRedis.exists).toHaveBeenCalledWith('@posthog/replay/session-blocked:1:session-123')
+ expect(result.has(1, 'cached-blocked')).toBe(true) // from the local cache
+ expect(result.has(1, 'uncached-blocked')).toBe(true) // from Redis
+ expect(result.has(1, 'uncached-open')).toBe(false) // from Redis
+ // Only the two uncached keys are read; the cached one is not re-fetched.
+ expect(mockRedis.mget).toHaveBeenCalledTimes(1)
+ expect(mockRedis.mget).toHaveBeenCalledWith([
+ '@posthog/replay/session-blocked:1:uncached-blocked',
+ '@posthog/replay/session-blocked:1:uncached-open',
+ ])
})
- it('should return true for blocked session in Redis', async () => {
- mockRedis.exists.mockResolvedValue(1)
+ it('does not touch Redis when every session in the batch is already cached', async () => {
+ mockRedis.mget.mockResolvedValue([null, '1'])
+ await sessionFilter.isBlocked(sessionSet([1, 'a'], [1, 'b'])) // caches both
+ jest.mocked(mockRedisPool.acquire).mockClear()
+ mockRedis.mget.mockClear()
+
+ const result = await sessionFilter.isBlocked(sessionSet([1, 'a'], [1, 'b']))
- const result = await sessionFilter.isBlocked(1, 'session-123')
+ expect(result.has(1, 'a')).toBe(false)
+ expect(result.has(1, 'b')).toBe(true)
+ expect(mockRedis.mget).not.toHaveBeenCalled()
+ expect(mockRedisPool.acquire).not.toHaveBeenCalled()
+ })
+
+ it('should return false for non-blocked session', async () => {
+ mockRedis.mget.mockResolvedValue([null])
+
+ expect(await blocked(sessionFilter, 1, 'session-123')).toBe(false)
+ expect(mockRedis.mget).toHaveBeenCalledWith(['@posthog/replay/session-blocked:1:session-123'])
+ })
+
+ it('should return true for blocked session in Redis', async () => {
+ mockRedis.mget.mockResolvedValue(['1'])
- expect(result).toBe(true)
+ expect(await blocked(sessionFilter, 1, 'session-123')).toBe(true)
})
it('should return true from cache without Redis call on subsequent checks for blocked sessions', async () => {
- mockRedis.exists.mockResolvedValue(1)
+ mockRedis.mget.mockResolvedValue(['1'])
// First call - hits Redis
- await sessionFilter.isBlocked(1, 'session-123')
- expect(mockRedis.exists).toHaveBeenCalledTimes(1)
+ await blocked(sessionFilter, 1, 'session-123')
+ expect(mockRedis.mget).toHaveBeenCalledTimes(1)
// Second call - should hit cache
- const result = await sessionFilter.isBlocked(1, 'session-123')
-
- expect(result).toBe(true)
- expect(mockRedis.exists).toHaveBeenCalledTimes(1) // Not called again
+ expect(await blocked(sessionFilter, 1, 'session-123')).toBe(true)
+ expect(mockRedis.mget).toHaveBeenCalledTimes(1) // Not called again
expect(SessionBatchMetrics.incrementSessionFilterCacheHit).toHaveBeenCalled()
})
it('should return false from cache without Redis call on subsequent checks for non-blocked sessions', async () => {
- mockRedis.exists.mockResolvedValue(0)
+ mockRedis.mget.mockResolvedValue([null])
// First call - hits Redis
- await sessionFilter.isBlocked(1, 'session-123')
- expect(mockRedis.exists).toHaveBeenCalledTimes(1)
+ await blocked(sessionFilter, 1, 'session-123')
+ expect(mockRedis.mget).toHaveBeenCalledTimes(1)
// Second call - should hit cache
- const result = await sessionFilter.isBlocked(1, 'session-123')
-
- expect(result).toBe(false)
- expect(mockRedis.exists).toHaveBeenCalledTimes(1) // Not called again
+ expect(await blocked(sessionFilter, 1, 'session-123')).toBe(false)
+ expect(mockRedis.mget).toHaveBeenCalledTimes(1) // Not called again
expect(SessionBatchMetrics.incrementSessionFilterCacheHit).toHaveBeenCalled()
})
- it('should cache blocked sessions locally after blocking via handleNewSession', async () => {
+ it('should cache blocked sessions locally after blocking via handleNewSessions', async () => {
mockConsume.mockReturnValue(false)
- await sessionFilter.handleNewSession(1, 'session-123')
+ await sessionFilter.handleNewSessions(sessionSet([1, 'session-123']))
// Now check if blocked - should hit local cache
- const result = await sessionFilter.isBlocked(1, 'session-123')
-
- expect(result).toBe(true)
- expect(mockRedis.exists).not.toHaveBeenCalled() // Used cache instead
+ expect(await blocked(sessionFilter, 1, 'session-123')).toBe(true)
+ expect(mockRedis.mget).not.toHaveBeenCalled() // Used cache instead
expect(SessionBatchMetrics.incrementSessionFilterCacheHit).toHaveBeenCalled()
})
it('should increment cache miss metric when checking Redis', async () => {
- mockRedis.exists.mockResolvedValue(0)
+ mockRedis.mget.mockResolvedValue([null])
- await sessionFilter.isBlocked(1, 'new-session')
+ await blocked(sessionFilter, 1, 'new-session')
expect(SessionBatchMetrics.incrementSessionFilterCacheMiss).toHaveBeenCalled()
})
it('should acquire and release Redis connection', async () => {
- mockRedis.exists.mockResolvedValue(0)
+ mockRedis.mget.mockResolvedValue([null])
- await sessionFilter.isBlocked(1, 'session-123')
+ await blocked(sessionFilter, 1, 'session-123')
expect(mockRedisPool.acquire).toHaveBeenCalled()
expect(mockRedisPool.release).toHaveBeenCalledWith(mockRedis)
})
it('should fail open and return false on Redis error', async () => {
- mockRedis.exists.mockRejectedValue(new Error('Redis error'))
+ mockRedis.mget.mockRejectedValue(new Error('Redis error'))
// Should not throw - fails open and returns false
- const result = await sessionFilter.isBlocked(1, 'session-123')
-
- expect(result).toBe(false)
+ expect(await blocked(sessionFilter, 1, 'session-123')).toBe(false)
expect(mockRedisPool.release).toHaveBeenCalledWith(mockRedis)
expect(SessionBatchMetrics.incrementSessionFilterRedisErrors).toHaveBeenCalled()
})
@@ -190,9 +264,7 @@ describe('SessionFilter', () => {
it('should fail open and return false on Redis acquire error', async () => {
mockRedisPool.acquire.mockRejectedValue(new Error('Pool exhausted'))
- const result = await sessionFilter.isBlocked(1, 'session-123')
-
- expect(result).toBe(false)
+ expect(await blocked(sessionFilter, 1, 'session-123')).toBe(false)
expect(SessionBatchMetrics.incrementSessionFilterRedisErrors).toHaveBeenCalled()
// Release should not be called since acquire failed
expect(mockRedisPool.release).not.toHaveBeenCalled()
@@ -200,14 +272,12 @@ describe('SessionFilter', () => {
it('should not cache result on Redis error so subsequent calls retry', async () => {
// First call fails
- mockRedis.exists.mockRejectedValueOnce(new Error('Redis error'))
- const result1 = await sessionFilter.isBlocked(1, 'session-123')
- expect(result1).toBe(false)
+ mockRedis.mget.mockRejectedValueOnce(new Error('Redis error'))
+ expect(await blocked(sessionFilter, 1, 'session-123')).toBe(false)
// Second call should retry Redis (not use cache)
- mockRedis.exists.mockResolvedValueOnce(1)
- const result2 = await sessionFilter.isBlocked(1, 'session-123')
- expect(result2).toBe(true)
+ mockRedis.mget.mockResolvedValueOnce(['1'])
+ expect(await blocked(sessionFilter, 1, 'session-123')).toBe(true)
// Should have called Redis twice (no caching on error)
expect(mockRedisPool.acquire).toHaveBeenCalledTimes(2)
@@ -218,16 +288,16 @@ describe('SessionFilter', () => {
it('should generate unique keys for different teams', async () => {
mockConsume.mockReturnValue(false)
- await sessionFilter.handleNewSession(1, 'session-123')
- await sessionFilter.handleNewSession(2, 'session-123')
+ await sessionFilter.handleNewSessions(sessionSet([1, 'session-123']))
+ await sessionFilter.handleNewSessions(sessionSet([2, 'session-123']))
- expect(mockRedis.set).toHaveBeenCalledWith(
+ expect(mockPipeline.set).toHaveBeenCalledWith(
'@posthog/replay/session-blocked:1:session-123',
'1',
'EX',
expect.any(Number)
)
- expect(mockRedis.set).toHaveBeenCalledWith(
+ expect(mockPipeline.set).toHaveBeenCalledWith(
'@posthog/replay/session-blocked:2:session-123',
'1',
'EX',
@@ -238,16 +308,16 @@ describe('SessionFilter', () => {
it('should generate unique keys for different sessions', async () => {
mockConsume.mockReturnValue(false)
- await sessionFilter.handleNewSession(1, 'session-123')
- await sessionFilter.handleNewSession(1, 'session-456')
+ await sessionFilter.handleNewSessions(sessionSet([1, 'session-123']))
+ await sessionFilter.handleNewSessions(sessionSet([1, 'session-456']))
- expect(mockRedis.set).toHaveBeenCalledWith(
+ expect(mockPipeline.set).toHaveBeenCalledWith(
'@posthog/replay/session-blocked:1:session-123',
'1',
'EX',
expect.any(Number)
)
- expect(mockRedis.set).toHaveBeenCalledWith(
+ expect(mockPipeline.set).toHaveBeenCalledWith(
'@posthog/replay/session-blocked:1:session-456',
'1',
'EX',
@@ -256,6 +326,39 @@ describe('SessionFilter', () => {
})
})
+ describe('team isolation', () => {
+ it('blocks a session for one team without blocking the same session id for another', async () => {
+ // Block (team 1, shared) via the limiter — cached locally for team 1 only, no read.
+ mockConsume.mockReturnValue(false)
+ await sessionFilter.handleNewSessions(sessionSet([1, 'shared']))
+
+ // The identically-named session for team 2 has no block key.
+ mockRedis.mget.mockResolvedValue([null])
+ const result = await sessionFilter.isBlocked(sessionSet([1, 'shared'], [2, 'shared']))
+
+ expect(result.has(1, 'shared')).toBe(true) // blocked for team 1
+ expect(result.has(2, 'shared')).toBe(false) // not blocked for team 2
+ // Team 1 is served from its own cache entry; only team 2's distinct key reaches Redis.
+ expect(mockRedis.mget).toHaveBeenCalledWith(['@posthog/replay/session-blocked:2:shared'])
+ })
+
+ it('rate-limits one team without blocking another sharing the session id', async () => {
+ // team 1 is over budget (denied), team 2 is within budget (allowed) — same session id.
+ mockConsume.mockImplementation((team: string) => team !== '1')
+
+ await sessionFilter.handleNewSessions(sessionSet([1, 'shared'], [2, 'shared']))
+
+ // Only team 1's session is written to the blocklist.
+ expect(mockPipeline.set).toHaveBeenCalledTimes(1)
+ expect(mockPipeline.set).toHaveBeenCalledWith(
+ '@posthog/replay/session-blocked:1:shared',
+ '1',
+ 'EX',
+ expect.any(Number)
+ )
+ })
+ })
+
describe('local cache', () => {
it('should respect custom cache TTL', async () => {
// LRU cache uses performance.now() for TTL, which Jest doesn't mock by default
@@ -273,43 +376,78 @@ describe('SessionFilter', () => {
localCacheTtlMs: cacheTtlMs,
})
- mockRedis.exists.mockResolvedValue(1)
+ mockRedis.mget.mockResolvedValue(['1'])
// First check - hits Redis
- await shortTtlFilter.isBlocked(1, 'session-123')
- expect(mockRedis.exists).toHaveBeenCalledTimes(1)
+ await blocked(shortTtlFilter, 1, 'session-123')
+ expect(mockRedis.mget).toHaveBeenCalledTimes(1)
// Advance mocked time past cache TTL
currentTime = startTime + cacheTtlMs + 1000
// Second check - cache expired, should hit Redis again
- await shortTtlFilter.isBlocked(1, 'session-123')
- expect(mockRedis.exists).toHaveBeenCalledTimes(2)
+ await blocked(shortTtlFilter, 1, 'session-123')
+ expect(mockRedis.mget).toHaveBeenCalledTimes(2)
jest.restoreAllMocks()
})
})
- describe('handleNewSession', () => {
+ describe('handleNewSessions', () => {
it('should not block when limiter allows the session', async () => {
mockConsume.mockReturnValue(true)
- await sessionFilter.handleNewSession(1, 'session-123')
+ await sessionFilter.handleNewSessions(sessionSet([1, 'session-123']))
expect(mockConsume).toHaveBeenCalledWith('1', 1)
- expect(mockRedis.set).not.toHaveBeenCalled()
+ expect(mockPipeline.set).not.toHaveBeenCalled()
+ // Nothing to block means no Redis round trip at all.
+ expect(mockRedisPool.acquire).not.toHaveBeenCalled()
})
it('should block when limiter denies and rate limiting is enabled', async () => {
mockConsume.mockReturnValue(false)
- await sessionFilter.handleNewSession(1, 'session-123')
+ await sessionFilter.handleNewSessions(sessionSet([1, 'session-123']))
- expect(mockRedis.set).toHaveBeenCalled()
+ expect(mockPipeline.set).toHaveBeenCalled()
expect(SessionBatchMetrics.incrementNewSessionsRateLimited).toHaveBeenCalledWith(1)
expect(SessionBatchMetrics.incrementSessionsBlocked).toHaveBeenCalled()
})
+ it('blocks only the rate-limited sessions in a mixed batch, in one pipeline', async () => {
+ // Two sessions pass the limiter, two are denied, across two teams (iteration is insertion order).
+ mockConsume
+ .mockReturnValueOnce(true) // 1:allowed
+ .mockReturnValueOnce(false) // 1:blocked
+ .mockReturnValueOnce(true) // 2:allowed
+ .mockReturnValueOnce(false) // 2:blocked
+
+ await sessionFilter.handleNewSessions(
+ sessionSet([1, 'allowed'], [1, 'blocked'], [2, 'allowed'], [2, 'blocked'])
+ )
+
+ // Only the two denied sessions are written, and the whole batch is a single pipelined round trip.
+ expect(mockPipeline.set).toHaveBeenCalledTimes(2)
+ expect(mockPipeline.set).toHaveBeenCalledWith(
+ '@posthog/replay/session-blocked:1:blocked',
+ '1',
+ 'EX',
+ expect.any(Number)
+ )
+ expect(mockPipeline.set).toHaveBeenCalledWith(
+ '@posthog/replay/session-blocked:2:blocked',
+ '1',
+ 'EX',
+ expect.any(Number)
+ )
+ expect(mockPipeline.exec).toHaveBeenCalledTimes(1)
+ expect(mockRedisPool.acquire).toHaveBeenCalledTimes(1)
+ // The limiter is consumed per session against its own team's budget.
+ expect(mockConsume).toHaveBeenCalledWith('1', 1)
+ expect(mockConsume).toHaveBeenCalledWith('2', 1)
+ })
+
it('should only increment metric but not block when blocking is disabled (dry run)', async () => {
const disabledFilter = new SessionFilter({
redisPool: mockRedisPool,
@@ -321,9 +459,9 @@ describe('SessionFilter', () => {
})
mockConsume.mockReturnValue(false)
- await disabledFilter.handleNewSession(1, 'session-123')
+ await disabledFilter.handleNewSessions(sessionSet([1, 'session-123']))
- expect(mockRedis.set).not.toHaveBeenCalled()
+ expect(mockPipeline.set).not.toHaveBeenCalled()
expect(SessionBatchMetrics.incrementNewSessionsRateLimited).toHaveBeenCalledWith(1)
})
@@ -338,14 +476,13 @@ describe('SessionFilter', () => {
})
mockConsume.mockReturnValue(false)
- // handleNewSession should not call Redis when filter is disabled
- await disabledFilter.handleNewSession(1, 'session-123')
- expect(mockRedis.set).not.toHaveBeenCalled()
+ // handleNewSessions should not call Redis when filter is disabled
+ await disabledFilter.handleNewSessions(sessionSet([1, 'session-123']))
+ expect(mockPipeline.set).not.toHaveBeenCalled()
// isBlocked should return false immediately without Redis
- const isBlocked = await disabledFilter.isBlocked(1, 'session-123')
- expect(isBlocked).toBe(false)
- expect(mockRedis.exists).not.toHaveBeenCalled()
+ expect(await blocked(disabledFilter, 1, 'session-123')).toBe(false)
+ expect(mockRedis.mget).not.toHaveBeenCalled()
})
it('should fail open on Redis acquire error during blocking', async () => {
@@ -353,30 +490,29 @@ describe('SessionFilter', () => {
mockRedisPool.acquire.mockRejectedValue(new Error('Pool exhausted'))
// Should not throw
- await sessionFilter.handleNewSession(1, 'session-123')
+ await sessionFilter.handleNewSessions(sessionSet([1, 'session-123']))
expect(SessionBatchMetrics.incrementSessionFilterRedisErrors).toHaveBeenCalled()
// Session should still be blocked locally
- const isBlocked = await sessionFilter.isBlocked(1, 'session-123')
- expect(isBlocked).toBe(true)
+ expect(await blocked(sessionFilter, 1, 'session-123')).toBe(true)
})
it('should consume from limiter on each call even for same session', async () => {
mockConsume.mockReturnValue(false)
- await sessionFilter.handleNewSession(1, 'session-123')
- await sessionFilter.handleNewSession(1, 'session-123')
+ await sessionFilter.handleNewSessions(sessionSet([1, 'session-123']))
+ await sessionFilter.handleNewSessions(sessionSet([1, 'session-123']))
// Limiter is consumed each time - the limiter handles deduplication if needed
expect(mockConsume).toHaveBeenCalledTimes(2)
// Redis set is also called twice - this is fine since SET is idempotent at Redis level
- expect(mockRedis.set).toHaveBeenCalledTimes(2)
+ expect(mockPipeline.set).toHaveBeenCalledTimes(2)
})
it('should not increment rate limited metric when limiter allows', async () => {
mockConsume.mockReturnValue(true)
- await sessionFilter.handleNewSession(1, 'session-123')
+ await sessionFilter.handleNewSessions(sessionSet([1, 'session-123']))
expect(SessionBatchMetrics.incrementNewSessionsRateLimited).not.toHaveBeenCalled()
expect(SessionBatchMetrics.incrementSessionsBlocked).not.toHaveBeenCalled()
@@ -395,19 +531,19 @@ describe('SessionFilter', () => {
localCacheMaxSize: 2,
})
- mockRedis.exists.mockResolvedValue(0)
+ mockRedis.mget.mockResolvedValue([null])
// Fill cache with 2 entries
- await smallCacheFilter.isBlocked(1, 'session-1')
- await smallCacheFilter.isBlocked(1, 'session-2')
+ await blocked(smallCacheFilter, 1, 'session-1')
+ await blocked(smallCacheFilter, 1, 'session-2')
// Third entry should evict the first
- await smallCacheFilter.isBlocked(1, 'session-3')
+ await blocked(smallCacheFilter, 1, 'session-3')
jest.clearAllMocks()
// First session should require Redis call again (was evicted)
- await smallCacheFilter.isBlocked(1, 'session-1')
+ await blocked(smallCacheFilter, 1, 'session-1')
expect(mockRedisPool.acquire).toHaveBeenCalled()
})
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-filter.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-filter.ts
index 9196dd5e5a81..0b1515329b49 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-filter.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-filter.ts
@@ -3,6 +3,7 @@ import { LRUCache } from 'lru-cache'
import { logger } from '~/common/utils/logger'
import { Limiter } from '~/common/utils/token-bucket'
import { SESSION_FILTER_REDIS_TTL_SECONDS } from '~/ingestion/pipelines/sessionreplay/constants'
+import { SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'
import { RedisPool } from '~/types'
import { SessionBatchMetrics } from './metrics'
@@ -19,6 +20,12 @@ export interface SessionFilterConfig {
filterEnabled: boolean
localCacheTtlMs: number
localCacheMaxSize?: number
+ /**
+ * Optional Redis key namespace. Omit for the main lane (keeps the prefix exactly
+ * `@posthog/replay/session-blocked`). A secondary pipeline (e.g. the ML mirror) must pass its own
+ * namespace so its blocklist doesn't collide with the main lane's.
+ */
+ keyNamespace?: string
}
/**
@@ -32,9 +39,19 @@ export interface SessionFilterConfig {
*
* The blocklist is persisted in Redis with an in-memory LRU cache
* to minimize Redis round-trips.
+ *
+ * ## Failure policy
+ *
+ * This class only does rate limiting — it never influences the encryption key — so every Redis op here
+ * follows rule 1 (see {@link SessionTracker}'s class doc): fail OPEN. On a Redis error we degrade toward
+ * under-counting / under-blocking (letting sessions through), never toward over-counting or halting the
+ * pipeline. Concretely: {@link isBlocked} assumes not-blocked, {@link blockSessions} keeps the block in
+ * the local cache but doesn't persist it, and the in-memory token bucket in {@link handleNewSessions}
+ * needs no Redis at all. Contrast the tracker's {@link SessionTracker.hasSeen}, which is key-integrity
+ * critical and therefore fails hard.
*/
export class SessionFilter {
- private readonly keyPrefix = '@posthog/replay/session-blocked'
+ private readonly keyPrefix: string
// In-memory cache to avoid hitting Redis for every message
// Since Kafka partitions by session ID, the same session always hits the same consumer
@@ -47,6 +64,9 @@ export class SessionFilter {
private readonly filterEnabled: boolean
constructor(config: SessionFilterConfig) {
+ this.keyPrefix = config.keyNamespace
+ ? `@posthog/replay/${config.keyNamespace}/session-blocked`
+ : '@posthog/replay/session-blocked'
this.redisPool = config.redisPool
this.sessionLimiter = new Limiter(config.bucketCapacity, config.bucketReplenishRate)
this.blockingEnabled = config.blockingEnabled
@@ -59,38 +79,37 @@ export class SessionFilter {
}
/**
- * Block a session so all future messages are dropped.
+ * Block sessions so all their future messages are dropped, persisting the whole set to Redis in
+ * one pipelined round trip.
*
- * Fails open: if Redis is unavailable, the session won't be persisted
- * to the blocklist but will still be blocked locally for this consumer.
+ * Fails open (rate-limiting rule 1): if Redis is unavailable, the sessions aren't persisted to the
+ * blocklist but are still blocked locally for this consumer. The worst case is under-blocking on
+ * other consumers — never over-counting, and never halting.
*
- * @param teamId - The team ID
- * @param sessionId - The session ID to block
+ * @param sessions - The sessions to block
*/
- private async blockSession(teamId: number, sessionId: string): Promise<void> {
- const key = this.generateKey(teamId, sessionId)
-
- // Add to local cache immediately for fast lookups
- // This ensures blocking works even if Redis fails
- this.localCache.set(key, true)
- SessionBatchMetrics.incrementSessionsBlocked()
+ private async blockSessions(sessions: SessionSet): Promise<void> {
+ // Block locally first so it holds even if the Redis write fails.
+ for (const { teamId, sessionId } of sessions) {
+ this.localCache.set(this.generateKey(teamId, sessionId), true)
+ SessionBatchMetrics.incrementSessionsBlocked()
+ }
const startTime = performance.now()
let client
try {
client = await this.redisPool.acquire()
- await client.set(key, '1', 'EX', SESSION_FILTER_REDIS_TTL_SECONDS)
+ const pipeline = client.pipeline()
+ for (const { teamId, sessionId } of sessions) {
+ pipeline.set(this.generateKey(teamId, sessionId), '1', 'EX', SESSION_FILTER_REDIS_TTL_SECONDS)
+ }
+ await pipeline.exec()
- logger.info('session_filter_blocked_session', {
- teamId,
- sessionId,
- })
+ logger.info('session_filter_blocked_sessions', { count: sessions.size })
} catch (error) {
- // Fail open: log the error but don't throw
- // The session is still blocked locally via the cache
- logger.error('session_filter_block_session_redis_error', {
- teamId,
- sessionId,
+ // Fail open: log the error but don't throw. The sessions are still blocked locally.
+ logger.error('session_filter_block_sessions_redis_error', {
+ count: sessions.size,
error: String(error),
})
SessionBatchMetrics.incrementSessionFilterRedisErrors()
@@ -103,52 +122,62 @@ export class SessionFilter {
}
/**
- * Check if a session is blocked.
+ * Return which of the given sessions are blocked. Local-cache hits are answered without Redis; the
+ * remaining sessions are checked in a single MGET.
*
- * Fails open: if Redis is unavailable, assumes the session is not blocked.
+ * Fails open (rate-limiting rule 1): if Redis is unavailable, the unknown sessions are assumed not
+ * blocked, so a rate-limited session may slip through and record — under-enforcement, never halting.
*
- * @param teamId - The team ID
- * @param sessionId - The session ID
- * @returns true if the session is blocked, false otherwise
+ * @returns the subset of `sessions` that are blocked (an unblocked session is simply absent)
*/
- public async isBlocked(teamId: number, sessionId: string): Promise<boolean> {
- // Skip Redis entirely when filter is disabled
+ public async isBlocked(sessions: SessionSet): Promise<SessionSet> {
+ const blocked = new SessionSet()
+
+ // Skip Redis entirely when filter is disabled — nothing is blocked.
if (!this.filterEnabled) {
- return false
+ return blocked
}
- const key = this.generateKey(teamId, sessionId)
-
- // Check local cache first to avoid Redis round-trip
- const cached = this.localCache.get(key)
- if (cached !== undefined) {
- SessionBatchMetrics.incrementSessionFilterCacheHit()
- return cached
+ const misses: { teamId: number; sessionId: string }[] = []
+ for (const { teamId, sessionId } of sessions) {
+ // Check local cache first to avoid a Redis round-trip. Both blocked and not-blocked states
+ // are cached; a later block updates the cache via blockSession.
+ const cached = this.localCache.get(this.generateKey(teamId, sessionId))
+ if (cached !== undefined) {
+ SessionBatchMetrics.incrementSessionFilterCacheHit()
+ if (cached) {
+ blocked.add(teamId, sessionId)
+ }
+ } else {
+ SessionBatchMetrics.incrementSessionFilterCacheMiss()
+ misses.push({ teamId, sessionId })
+ }
}
- SessionBatchMetrics.incrementSessionFilterCacheMiss()
+ if (misses.length === 0) {
+ return blocked
+ }
const startTime = performance.now()
let client
try {
client = await this.redisPool.acquire()
- const exists = await client.exists(key)
- const isBlocked = exists === 1
-
- // Cache the result locally to prevent repeated Redis calls
- // Cache both blocked and not-blocked states
- this.localCache.set(key, isBlocked)
-
- return isBlocked
+ const values = await client.mget(misses.map(({ teamId, sessionId }) => this.generateKey(teamId, sessionId)))
+ for (let i = 0; i < misses.length; i++) {
+ const { teamId, sessionId } = misses[i]
+ const isBlocked = values[i] !== null
+ this.localCache.set(this.generateKey(teamId, sessionId), isBlocked)
+ if (isBlocked) {
+ blocked.add(teamId, sessionId)
+ }
+ }
+ return blocked
} catch (error) {
- // Fail open: if Redis is unavailable, allow the session through
- logger.error('session_filter_is_blocked_redis_error', {
- teamId,
- sessionId,
- error: String(error),
- })
+ // Fail open: if Redis is unavailable, treat the unknown sessions as not blocked by omitting
+ // them from the set (their block state stays unknown rather than halting the pipeline).
+ logger.error('session_filter_is_blocked_redis_error', { error: String(error) })
SessionBatchMetrics.incrementSessionFilterRedisErrors()
- return false
+ return blocked
} finally {
if (client) {
await this.redisPool.release(client)
@@ -158,31 +187,39 @@ export class SessionFilter {
}
/**
- * Handle a new session by checking rate limits and blocking if necessary.
+ * Handle a batch of new sessions by checking each against its team's rate limit and blocking the
+ * ones that exceed it. The rate-limit check is an in-memory token bucket, so the only Redis cost is
+ * one pipelined write for whichever sessions get blocked.
*
- * This method should be called for new sessions (as determined by SessionTracker).
- * If the team has exceeded its rate limit and rate limiting is enabled,
- * the session will be blocked. The caller should then check isBlocked() to
- * determine whether to process the message.
+ * Should be called with the genuinely-new sessions only — those neither seen nor already blocked —
+ * so a session already on the blocklist isn't charged a second token.
*
- * @param teamId - The team ID
- * @param sessionId - The session ID
+ * @param sessions - The new sessions to rate-limit
+ * @returns the sessions this call blocked, so the caller can gate them without a second isBlocked read
*/
- public async handleNewSession(teamId: number, sessionId: string): Promise<void> {
- const isAllowed = this.sessionLimiter.consume(String(teamId), 1)
-
- if (!isAllowed) {
+ public async handleNewSessions(sessions: SessionSet): Promise<SessionSet> {
+ const toBlock = new SessionSet()
+ for (const { teamId, sessionId } of sessions) {
+ const isAllowed = this.sessionLimiter.consume(String(teamId), 1)
+ if (isAllowed) {
+ continue
+ }
logger.debug('session_filter_new_session_rate_limited', {
teamId,
sessionId,
blockingEnabled: this.blockingEnabled,
})
SessionBatchMetrics.incrementNewSessionsRateLimited(teamId)
-
if (this.blockingEnabled && this.filterEnabled) {
- await this.blockSession(teamId, sessionId)
+ toBlock.add(teamId, sessionId)
}
}
+
+ if (toBlock.size > 0) {
+ await this.blockSessions(toBlock)
+ }
+
+ return toBlock
}
private generateKey(teamId: number, sessionId: string): string {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-tracker.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-tracker.test.ts
index c7c5435c1348..124029d92f49 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-tracker.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-tracker.test.ts
@@ -1,5 +1,6 @@
import { Redis } from 'ioredis'
+import { SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'
import { RedisPool } from '~/types'
import { SessionBatchMetrics } from './metrics'
@@ -15,184 +16,143 @@ jest.mock('./metrics', () => ({
},
}))
+const sessionSet = (...pairs: [number, string][]): SessionSet => {
+ const set = new SessionSet()
+ pairs.forEach(([teamId, sessionId]) => set.add(teamId, sessionId))
+ return set
+}
+
+const TTL_SECONDS = 48 * 60 * 60
+
describe('SessionTracker', () => {
let sessionTracker: SessionTracker
let mockRedisClient: jest.Mocked<Redis>
+ let mockPipeline: { set: jest.Mock; exec: jest.Mock }
let mockRedisPool: jest.Mocked<RedisPool>
beforeEach(() => {
jest.clearAllMocks()
+ mockPipeline = { set: jest.fn().mockReturnThis(), exec: jest.fn().mockResolvedValue([]) }
mockRedisClient = {
- set: jest.fn(),
+ mget: jest.fn().mockResolvedValue([]),
+ pipeline: jest.fn().mockReturnValue(mockPipeline),
} as unknown as jest.Mocked<Redis>
mockRedisPool = {
acquire: jest.fn().mockResolvedValue(mockRedisClient),
release: jest.fn(),
} as unknown as jest.Mocked<RedisPool>
+
+ sessionTracker = new SessionTracker(mockRedisPool, 5 * 60 * 1000)
})
- describe('trackSession', () => {
- it('should return true for new session when key does not exist', async () => {
- mockRedisClient.set = jest.fn().mockResolvedValue('OK')
- sessionTracker = new SessionTracker(mockRedisPool, 5 * 60 * 1000)
+ describe('hasSeen', () => {
+ it('reports new and already-seen sessions from a single MGET', async () => {
+ mockRedisClient.mget = jest.fn().mockResolvedValue([null, '1'])
- const isNew = await sessionTracker.trackSession(1, 'session-123')
+ const result = await sessionTracker.hasSeen(sessionSet([1, 'new'], [1, 'old']))
- expect(isNew).toBe(true)
- expect(mockRedisClient.set).toHaveBeenCalledWith(
- '@posthog/replay/session-seen:1:session-123',
- '1',
- 'EX',
- 48 * 60 * 60,
- 'NX'
- )
- expect(SessionBatchMetrics.incrementNewSessionsDetected).toHaveBeenCalledTimes(1)
+ expect(result.get(1, 'new')).toBe(false)
+ expect(result.get(1, 'old')).toBe(true)
+ expect(mockRedisClient.mget).toHaveBeenCalledTimes(1)
+ expect(mockRedisClient.mget).toHaveBeenCalledWith([
+ '@posthog/replay/session-seen:1:new',
+ '@posthog/replay/session-seen:1:old',
+ ])
})
- it('should return false when session already exists', async () => {
- mockRedisClient.set = jest.fn().mockResolvedValue(null)
- sessionTracker = new SessionTracker(mockRedisPool, 5 * 60 * 1000)
-
- const isNew = await sessionTracker.trackSession(1, 'session-123')
+ it('returns an empty map without touching Redis for an empty set', async () => {
+ const result = await sessionTracker.hasSeen(sessionSet())
- expect(isNew).toBe(false)
- expect(SessionBatchMetrics.incrementNewSessionsDetected).not.toHaveBeenCalled()
+ expect(result.size).toBe(0)
+ expect(mockRedisPool.acquire).not.toHaveBeenCalled()
})
- it('should track sessions separately per team', async () => {
- mockRedisClient.set = jest.fn().mockResolvedValue('OK')
- sessionTracker = new SessionTracker(mockRedisPool, 5 * 60 * 1000)
+ it('serves a marked session from the local cache without an MGET', async () => {
+ await sessionTracker.markSeen(sessionSet([1, 'a']))
- await sessionTracker.trackSession(1, 'session-123')
- await sessionTracker.trackSession(2, 'session-123')
+ const result = await sessionTracker.hasSeen(sessionSet([1, 'a']))
- expect(mockRedisClient.set).toHaveBeenCalledWith(
- '@posthog/replay/session-seen:1:session-123',
- '1',
- 'EX',
- 48 * 60 * 60,
- 'NX'
- )
- expect(mockRedisClient.set).toHaveBeenCalledWith(
- '@posthog/replay/session-seen:2:session-123',
- '1',
- 'EX',
- 48 * 60 * 60,
- 'NX'
- )
+ expect(result.get(1, 'a')).toBe(true)
+ expect(mockRedisClient.mget).not.toHaveBeenCalled()
+ expect(SessionBatchMetrics.incrementSessionTrackerCacheHit).toHaveBeenCalledTimes(1)
})
- it('should fail open and return false on Redis set error', async () => {
- mockRedisClient.set = jest.fn().mockRejectedValue(new Error('Redis error'))
- sessionTracker = new SessionTracker(mockRedisPool, 5 * 60 * 1000)
-
- const isNew = await sessionTracker.trackSession(1, 'session-123')
-
- expect(isNew).toBe(false)
- expect(mockRedisPool.release).toHaveBeenCalledWith(mockRedisClient)
- expect(SessionBatchMetrics.incrementSessionTrackerRedisErrors).toHaveBeenCalled()
+ it('caches a positive hit so the next check skips Redis, but rechecks a negative', async () => {
+ mockRedisClient.mget = jest.fn().mockResolvedValue(['1'])
+ await sessionTracker.hasSeen(sessionSet([1, 'seen']))
+ await sessionTracker.hasSeen(sessionSet([1, 'seen']))
+ // Positive was cached: only the first call hit Redis.
+ expect(mockRedisClient.mget).toHaveBeenCalledTimes(1)
+
+ mockRedisClient.mget = jest.fn().mockResolvedValue([null])
+ await sessionTracker.hasSeen(sessionSet([1, 'unseen']))
+ await sessionTracker.hasSeen(sessionSet([1, 'unseen']))
+ // Negatives aren't cached, so an unseen session is rechecked every time.
+ expect(mockRedisClient.mget).toHaveBeenCalledTimes(2)
})
- it('should fail open and return false on Redis acquire error', async () => {
- mockRedisPool.acquire = jest.fn().mockRejectedValue(new Error('Pool exhausted'))
- sessionTracker = new SessionTracker(mockRedisPool, 5 * 60 * 1000)
+ it('fails hard by throwing on a Redis error so the caller retries instead of guessing', async () => {
+ mockRedisClient.mget = jest.fn().mockRejectedValue(new Error('Redis down'))
- const isNew = await sessionTracker.trackSession(1, 'session-123')
-
- expect(isNew).toBe(false)
+ // hasSeen drives the key generate-vs-get decision, so it must not guess "seen" (which would
+ // record cleartext / switch keys). It throws for the step's retry wrapper to re-run.
+ await expect(sessionTracker.hasSeen(sessionSet([1, 'a']))).rejects.toThrow('Redis down')
expect(SessionBatchMetrics.incrementSessionTrackerRedisErrors).toHaveBeenCalled()
- expect(mockRedisPool.release).not.toHaveBeenCalled()
- })
-
- it('should use 48 hour TTL', async () => {
- mockRedisClient.set = jest.fn().mockResolvedValue('OK')
- sessionTracker = new SessionTracker(mockRedisPool, 5 * 60 * 1000)
-
- await sessionTracker.trackSession(1, 'session-123')
-
- const expectedTTL = 48 * 60 * 60
- expect(mockRedisClient.set).toHaveBeenCalledWith(expect.any(String), '1', 'EX', expectedTTL, 'NX')
+ expect(mockRedisPool.release).toHaveBeenCalledWith(mockRedisClient)
})
})
- describe('local cache', () => {
- it('should return false from cache without calling Redis on second call', async () => {
- mockRedisClient.set = jest.fn().mockResolvedValue('OK')
- sessionTracker = new SessionTracker(mockRedisPool, 5 * 60 * 1000)
-
- // First call should hit Redis
- const isNew1 = await sessionTracker.trackSession(1, 'session-123')
- expect(isNew1).toBe(true)
- expect(mockRedisClient.set).toHaveBeenCalledTimes(1)
- expect(SessionBatchMetrics.incrementSessionTrackerCacheMiss).toHaveBeenCalledTimes(1)
-
- // Second call should use cache
- const isNew2 = await sessionTracker.trackSession(1, 'session-123')
- expect(isNew2).toBe(false)
- expect(mockRedisClient.set).toHaveBeenCalledTimes(1) // Still only 1 call
- expect(SessionBatchMetrics.incrementSessionTrackerCacheHit).toHaveBeenCalledTimes(1)
- })
-
- it('should cache sessions separately per team', async () => {
- mockRedisClient.set = jest.fn().mockResolvedValue('OK')
- sessionTracker = new SessionTracker(mockRedisPool, 5 * 60 * 1000)
+ describe('markSeen', () => {
+ it('sets each session key with a 48h TTL in one pipeline', async () => {
+ await sessionTracker.markSeen(sessionSet([1, 'a'], [2, 'b']))
- await sessionTracker.trackSession(1, 'session-123')
- await sessionTracker.trackSession(2, 'session-123')
-
- // Both should have hit Redis (different teams)
- expect(mockRedisClient.set).toHaveBeenCalledTimes(2)
- expect(SessionBatchMetrics.incrementSessionTrackerCacheMiss).toHaveBeenCalledTimes(2)
+ expect(mockPipeline.set).toHaveBeenCalledWith('@posthog/replay/session-seen:1:a', '1', 'EX', TTL_SECONDS)
+ expect(mockPipeline.set).toHaveBeenCalledWith('@posthog/replay/session-seen:2:b', '1', 'EX', TTL_SECONDS)
+ expect(mockPipeline.exec).toHaveBeenCalledTimes(1)
+ expect(SessionBatchMetrics.incrementNewSessionsDetected).toHaveBeenCalledTimes(2)
+ })
- // Now both should be cached
- await sessionTracker.trackSession(1, 'session-123')
- await sessionTracker.trackSession(2, 'session-123')
+ it('does nothing for an empty set', async () => {
+ await sessionTracker.markSeen(sessionSet())
- expect(mockRedisClient.set).toHaveBeenCalledTimes(2) // No additional calls
- expect(SessionBatchMetrics.incrementSessionTrackerCacheHit).toHaveBeenCalledTimes(2)
+ expect(mockRedisPool.acquire).not.toHaveBeenCalled()
+ expect(mockPipeline.set).not.toHaveBeenCalled()
})
- it('should hit Redis again after cache TTL expires', async () => {
- mockRedisClient.set = jest.fn().mockResolvedValue(null) // Session already exists
- const shortCacheTtlMs = 50 // 50ms TTL for testing
- sessionTracker = new SessionTracker(mockRedisPool, shortCacheTtlMs)
+ it('namespaces the Redis keys when a key namespace is given, isolating it from the main lane', async () => {
+ const namespaced = new SessionTracker(mockRedisPool, 5 * 60 * 1000, undefined, 'ml-mirror')
- // First call
- await sessionTracker.trackSession(1, 'session-123')
- expect(mockRedisClient.set).toHaveBeenCalledTimes(1)
+ await namespaced.markSeen(sessionSet([1, 'a']))
- // Second call within TTL - should use cache
- await sessionTracker.trackSession(1, 'session-123')
- expect(mockRedisClient.set).toHaveBeenCalledTimes(1)
+ expect(mockPipeline.set).toHaveBeenCalledWith(
+ '@posthog/replay/ml-mirror/session-seen:1:a',
+ '1',
+ 'EX',
+ TTL_SECONDS
+ )
+ })
- // Wait for TTL to expire
- await new Promise((resolve) => setTimeout(resolve, shortCacheTtlMs + 10))
+ it('fails open on a pipeline error', async () => {
+ mockPipeline.exec = jest.fn().mockRejectedValue(new Error('Redis down'))
- // Third call after TTL - should hit Redis again
- await sessionTracker.trackSession(1, 'session-123')
- expect(mockRedisClient.set).toHaveBeenCalledTimes(2)
+ await expect(sessionTracker.markSeen(sessionSet([1, 'a']))).resolves.toBeUndefined()
+ expect(SessionBatchMetrics.incrementSessionTrackerRedisErrors).toHaveBeenCalled()
+ expect(mockRedisPool.release).toHaveBeenCalledWith(mockRedisClient)
})
- it('should cache both new and existing sessions', async () => {
- sessionTracker = new SessionTracker(mockRedisPool, 5 * 60 * 1000)
-
- // New session
- mockRedisClient.set = jest.fn().mockResolvedValue('OK')
- await sessionTracker.trackSession(1, 'new-session')
- expect(mockRedisClient.set).toHaveBeenCalledTimes(1)
+ it('still records the session in the local cache when the pipeline write fails', async () => {
+ mockPipeline.exec = jest.fn().mockRejectedValue(new Error('Redis down'))
- // Existing session
- mockRedisClient.set = jest.fn().mockResolvedValue(null)
- await sessionTracker.trackSession(1, 'existing-session')
- expect(mockRedisClient.set).toHaveBeenCalledTimes(1)
+ await sessionTracker.markSeen(sessionSet([1, 'a']))
- // Both should now be cached
- mockRedisClient.set = jest.fn()
- await sessionTracker.trackSession(1, 'new-session')
- await sessionTracker.trackSession(1, 'existing-session')
- expect(mockRedisClient.set).not.toHaveBeenCalled()
+ // Redis never persisted the mark, but this consumer must still treat the session as seen —
+ // partition affinity keeps it here, so failing open without the local record would re-key
+ // and re-charge the new-session budget for every session during a Redis blip.
+ const result = await sessionTracker.hasSeen(sessionSet([1, 'a']))
+ expect(result.get(1, 'a')).toBe(true)
+ expect(mockRedisClient.mget).not.toHaveBeenCalled()
})
})
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-tracker.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-tracker.ts
index c0daa47dd5ec..2ea25d4b0a8e 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-tracker.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-tracker.ts
@@ -2,24 +2,63 @@ import { LRUCache } from 'lru-cache'
import { logger } from '~/common/utils/logger'
import { SESSION_TRACKER_REDIS_TTL_SECONDS } from '~/ingestion/pipelines/sessionreplay/constants'
+import { SessionMap, SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'
import { RedisPool } from '~/types'
import { SessionBatchMetrics } from './metrics'
const DEFAULT_LOCAL_CACHE_MAX_SIZE = 100_000
+/**
+ * Tracks which sessions have been seen before, so a session's first sighting can be treated as new
+ * (rate-limited, key-generated) and later sightings as existing.
+ *
+ * The check ({@link hasSeen}) and the write ({@link markSeen}) are deliberately separate: the caller
+ * marks a session seen only once it has durably generated the session's key. If they were fused (mark
+ * on check, as an atomic SET NX), a failure between marking and key generation would leave a session
+ * flagged seen but keyless — on retry it would resolve as existing and fetch a key that was never
+ * generated. Keeping them apart lets a failed key generation leave the session unseen so the retry
+ * regenerates.
+ *
+ * An in-memory LRU cache fronts Redis. Kafka partitions by session id, so the same session always
+ * hits the same consumer, which makes the local cache effective and the split safe from cross-consumer
+ * races.
+ *
+ * ## Failure policy
+ *
+ * The two methods degrade in opposite directions because they answer different questions, and the
+ * pipeline holds two non-negotiable rules:
+ * 1. Rate limiting is best-effort — on failure it may UNDER-count (let a session through un-limited)
+ * but must never OVER-count. Failing open is fine.
+ * 2. Anything that could corrupt encryption — recording without a key (cleartext), or switching a
+ * session's key mid-stream — must FAIL HARD (throw and let the retry re-run), never guess.
+ *
+ * {@link hasSeen} answers "new or existing?", which the record path uses BOTH to rate-limit (rule 1)
+ * AND to decide generate-vs-fetch of the encryption key (rule 2). Because a wrong answer there records
+ * cleartext or switches keys, rule 2 wins: hasSeen fails hard. {@link markSeen} only persists the seen
+ * flag; if it's lost the session is treated as new again next batch, but the key store is idempotent
+ * (same key, no cleartext, no switch), so there's no integrity risk — it fails open under rule 1, with
+ * the local cache masking the loss on this consumer.
+ */
export class SessionTracker {
- private readonly keyPrefix = '@posthog/replay/session-seen'
+ private readonly keyPrefix: string
- // In-memory cache to avoid hitting Redis for every message
- // Since Kafka partitions by session ID, the same session always hits the same consumer
private readonly localCache: LRUCache<string, true>
+ /**
+ * @param keyNamespace - Optional Redis key namespace. Omit (the default) for the main lane — this
+ * keeps the key prefix exactly `@posthog/replay/session-seen` so existing sessions aren't seen as
+ * new. A secondary pipeline (e.g. the ML mirror) MUST pass its own namespace so it doesn't share
+ * seen-state with the main lane; otherwise it can mark a session seen without the main lane's key
+ * and cause a cleartext recording there.
+ */
constructor(
private readonly redisPool: RedisPool,
localCacheTtlMs: number,
- localCacheMaxSize: number = DEFAULT_LOCAL_CACHE_MAX_SIZE
+ localCacheMaxSize: number = DEFAULT_LOCAL_CACHE_MAX_SIZE,
+ keyNamespace?: string
) {
+ this.keyPrefix = keyNamespace ? `@posthog/replay/${keyNamespace}/session-seen` : '@posthog/replay/session-seen'
this.localCache = new LRUCache({
max: localCacheMaxSize,
ttl: localCacheTtlMs,
@@ -27,59 +66,96 @@ export class SessionTracker {
}
/**
- * Check if session has been seen before, mark as seen if not.
+ * Which of the given sessions have been seen before, without marking any. Pair with
+ * {@link markSeen} after a session's key has been generated. Local-cache hits are answered without
+ * Redis; the remaining sessions are checked in a single MGET.
*
- * Fails open: if Redis is unavailable, assumes the session is not new
- * to avoid incorrectly triggering rate limits.
+ * Fails hard: on a Redis error this throws so the caller's retry wrapper re-runs. hasSeen decides
+ * whether a session generates a new key or fetches its existing one, so a wrong answer would record
+ * cleartext (new session fetched as existing → no key) or switch a session's key mid-outage. Guessing
+ * would corrupt encryption; halting until Redis recovers is the safe degradation. (Rate limiting can
+ * tolerate a wrong answer — key integrity can't — so the stricter requirement wins here.)
*
- * @param teamId - The team ID
- * @param sessionId - The session ID
- * @returns true if this is a new session, false if already seen
+ * @returns a map keyed by `(teamId, sessionId)` — true if seen before, false if new
*/
- public async trackSession(teamId: number, sessionId: string): Promise<boolean> {
- const key = this.generateKey(teamId, sessionId)
-
- // Check local cache first to avoid Redis round-trip
- if (this.localCache.has(key)) {
- SessionBatchMetrics.incrementSessionTrackerCacheHit()
- return false
+ public async hasSeen(sessions: SessionSet): Promise<SessionMap<boolean>> {
+ const result = new SessionMap<boolean>()
+ const misses: { teamId: number; sessionId: string }[] = []
+ for (const { teamId, sessionId } of sessions) {
+ if (this.localCache.has(this.generateKey(teamId, sessionId))) {
+ SessionBatchMetrics.incrementSessionTrackerCacheHit()
+ result.set(teamId, sessionId, true)
+ } else {
+ SessionBatchMetrics.incrementSessionTrackerCacheMiss()
+ misses.push({ teamId, sessionId })
+ }
}
- SessionBatchMetrics.incrementSessionTrackerCacheMiss()
+ if (misses.length === 0) {
+ return result
+ }
const startTime = performance.now()
let client
try {
client = await this.redisPool.acquire()
+ const values = await client.mget(misses.map(({ teamId, sessionId }) => this.generateKey(teamId, sessionId)))
+ for (let i = 0; i < misses.length; i++) {
+ const { teamId, sessionId } = misses[i]
+ const seen = values[i] !== null
+ // Cache positives so repeated messages for a known session skip Redis. A negative isn't
+ // cached: markSeen caches it once the session is actually recorded as seen.
+ if (seen) {
+ this.localCache.set(this.generateKey(teamId, sessionId), true)
+ }
+ result.set(teamId, sessionId, seen)
+ }
+ return result
+ } catch (error) {
+ // Hard-fail: rethrow so the step's retry re-runs rather than guessing "seen" and risking a
+ // keyless (cleartext) recording or a mid-session key switch.
+ logger.error('session_tracker_has_seen_redis_error', { error: String(error) })
+ SessionBatchMetrics.incrementSessionTrackerRedisErrors()
+ throw error
+ } finally {
+ if (client) {
+ await this.redisPool.release(client)
+ }
+ SessionBatchMetrics.observeSessionTrackerRedisLatency((performance.now() - startTime) / 1000)
+ }
+ }
- // Use SET with NX (only set if not exists) and EX (expiry) for atomic check-and-set
- // Returns 'OK' if key was set (new session), null if already exists
- const wasSet = await client.set(key, '1', 'EX', SESSION_TRACKER_REDIS_TTL_SECONDS, 'NX')
- const isNewSession = wasSet === 'OK'
-
- // Cache the result locally regardless of whether it's new
- // This prevents repeated Redis calls for the same session
- this.localCache.set(key, true)
+ /**
+ * Mark the given sessions as seen, in a single Redis pipeline. Call this only after each session's
+ * key has been durably generated, so a failure before the key exists leaves the session unseen and
+ * the retry regenerates.
+ *
+ * Fails open (rate-limiting rule 1 — see the class doc): if Redis is unavailable the marks aren't
+ * persisted, but the local cache still records them for this consumer (the same session stays on this
+ * consumer via partition affinity). A lost mark can only make the session look new again later, which
+ * the idempotent key store handles without any cleartext/key-switch — so there's no integrity reason
+ * to fail hard here, and doing so would needlessly halt on a fire-and-forget write.
+ */
+ public async markSeen(sessions: SessionSet): Promise<void> {
+ if (sessions.size === 0) {
+ return
+ }
- if (isNewSession) {
+ const startTime = performance.now()
+ let client
+ try {
+ client = await this.redisPool.acquire()
+ const pipeline = client.pipeline()
+ for (const { teamId, sessionId } of sessions) {
+ const key = this.generateKey(teamId, sessionId)
+ this.localCache.set(key, true)
SessionBatchMetrics.incrementNewSessionsDetected()
-
- logger.debug('session_tracker_new_session', {
- teamId,
- sessionId,
- })
+ pipeline.set(key, '1', 'EX', SESSION_TRACKER_REDIS_TTL_SECONDS)
}
-
- return isNewSession
+ await pipeline.exec()
} catch (error) {
- // Fail open: if Redis is unavailable, assume not a new session
- logger.error('session_tracker_redis_error', {
- teamId,
- sessionId,
- error: String(error),
- })
+ logger.error('session_tracker_mark_seen_redis_error', { error: String(error) })
SessionBatchMetrics.incrementSessionTrackerRedisErrors()
- return false
} finally {
if (client) {
await this.redisPool.release(client)
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.ts
index 0a3dc4948983..a152f2fe402b 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
@@ -55,6 +55,18 @@ describe('MemoryCachedKeyStore', () => {
expect(cachedResult).toEqual(mockSessionKey)
})
+ it('should serve a cached key on a repeat generateKey without hitting the delegate', async () => {
+ // A session grouped per batch can call generateKey once per message; only the first should
+ // reach the delegate (KMS/DynamoDB), the rest come from cache.
+ await cachedKeyStore.generateKey('session-123', 1, 30)
+ mockDelegate.generateKey.mockClear()
+
+ const result = await cachedKeyStore.generateKey('session-123', 1, 30)
+
+ expect(mockDelegate.generateKey).not.toHaveBeenCalled()
+ expect(result).toEqual(mockSessionKey)
+ })
+
it('should propagate delegate generateKey error', async () => {
mockDelegate.generateKey.mockRejectedValue(new Error('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.ts
index a20c4c111ab1..2faec39a54fc 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
@@ -27,6 +27,14 @@ export class MemoryCachedKeyStore implements KeyStore {
}
async generateKey(sessionId: string, teamId: number, retentionDays: number): Promise<SessionKey> {
+ // Serve a cached key if one exists, so repeated new-session sightings within a batch (grouped
+ // per session) don't each hit KMS/DynamoDB — the delegate's generateKey is idempotent, so a
+ // cached key is the same key it would return anyway.
+ const cached = this.cache.get(this.cacheKey(sessionId, teamId))
+ if (cached) {
+ return cached
+ }
+
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/test-helpers.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/test-helpers.ts
index f34b873f7e12..395d071e275e 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/test-helpers.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/test-helpers.ts
@@ -1,4 +1,13 @@
-import { KeyStore, RecordingEncryptor } from './types'
+import { KeyStore, RecordingEncryptor, SessionKey } from './types'
+
+export function createMockSessionKey(overrides: Partial<SessionKey> = {}): SessionKey {
+ return {
+ plaintextKey: Buffer.alloc(0),
+ encryptedKey: Buffer.alloc(0),
+ sessionState: 'cleartext',
+ ...overrides,
+ }
+}
export function createMockKeyStore(): jest.Mocked<KeyStore> {
return {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.ts
index e6c0158d7eec..4040da5481e2 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.ts
@@ -3,7 +3,7 @@ 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 { SessionReplayHeaders } from './validate-headers-step'
+import { SessionReplayHeaders } from './pipeline-types'
export type TeamTokenResolver = Pick<TeamService, 'getTeamByToken' | 'getRetentionPeriodByTeamId'>
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/validate-headers-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/validate-headers-step.ts
index 9cd31fc0aab3..8772d3852cdc 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/validate-headers-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/validate-headers-step.ts
@@ -3,19 +3,7 @@ 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
-}
+import { SessionReplayHeaders } from './pipeline-types'
export interface ValidateSessionReplayHeadersStepInput {
headers: EventHeaders
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
index e9789b245374..7376443af805 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
@@ -159,6 +159,10 @@ export class IngestionSessionReplayMlMirrorServer implements NodeServer {
keyStore,
encryptor: new CleartextRecordingEncryptor(keyStore),
createPipeline: (pipelineConfig) => createMlMirrorReplayPipeline({ ...pipelineConfig, scrubContext }),
+ // Isolate the mirror's session tracker/filter keys from the main lane. Sharing them would let
+ // the cleartext mirror mark a session seen without the main lane's KMS key, so the main lane
+ // would then fetch a missing key and record cleartext.
+ redisKeyNamespace: 'ml-mirror',
}
const ingester = new SessionRecordingIngester(
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.ts
index 93c3f8d65b4b..369d4b60ee82 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
@@ -35,13 +35,11 @@ import {
} from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-file-storage'
import { SessionBatchRecorder } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder'
import { SessionConsoleLogStore } from '~/ingestion/pipelines/sessionreplay/sessions/session-console-log-store'
-import { SessionFilter } from '~/ingestion/pipelines/sessionreplay/sessions/session-filter'
-import { SessionTracker } from '~/ingestion/pipelines/sessionreplay/sessions/session-tracker'
import { SessionFeatureStore } from '~/ingestion/pipelines/sessionreplay/shared/features/session-feature-store'
import { SessionBlockMetadata } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata'
import { SessionMetadataStore } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-metadata-store'
-import { createMockEncryptor, createMockKeyStore } from '~/ingestion/pipelines/sessionreplay/shared/test-helpers'
-import { KeyStore, RecordingEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/types'
+import { createMockEncryptor, createMockSessionKey } from '~/ingestion/pipelines/sessionreplay/shared/test-helpers'
+import { RecordingEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/types'
import { MessageWithTeam } from '~/ingestion/pipelines/sessionreplay/teams/types'
jest.mock('~/ingestion/pipelines/sessionreplay/sessions/session-feature-recorder', () => ({
@@ -105,9 +103,6 @@ describe('session recording integration', () => {
let mockMetadataStore: jest.Mocked<SessionMetadataStore>
let mockConsoleLogStore: jest.Mocked<SessionConsoleLogStore>
let mockFeatureStore: jest.Mocked<SessionFeatureStore>
- let mockSessionTracker: jest.Mocked<SessionTracker>
- let mockSessionFilter: jest.Mocked<SessionFilter>
- let mockKeyStore: jest.Mocked<KeyStore>
let mockEncryptor: jest.Mocked<RecordingEncryptor>
let batchBuffer: Uint8Array
let currentOffset: number
@@ -158,16 +153,6 @@ describe('session recording integration', () => {
storeSessionFeatures: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<SessionFeatureStore>
- mockSessionTracker = {
- trackSession: jest.fn().mockResolvedValue(false),
- } as unknown as jest.Mocked<SessionTracker>
-
- mockSessionFilter = {
- isBlocked: jest.fn().mockResolvedValue(false),
- handleNewSession: jest.fn().mockResolvedValue(undefined),
- } as unknown as jest.Mocked<SessionFilter>
-
- mockKeyStore = createMockKeyStore()
mockEncryptor = createMockEncryptor()
recorder = new SessionBatchRecorder(
@@ -176,9 +161,6 @@ describe('session recording integration', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- mockKeyStore,
mockEncryptor
)
})
@@ -261,7 +243,7 @@ describe('session recording integration', () => {
// Record all messages
for (const message of messages) {
- await recorder.record(message, '30d')
+ await recorder.record(message, '30d', createMockSessionKey())
}
// Flush and get metadata
diff --git a/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-encryption.integration.test.ts b/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-encryption.integration.test.ts
index 2d57f6100307..74add40add69 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
@@ -11,8 +11,7 @@ import {
} from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-file-storage'
import { SessionBatchRecorder } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder'
import { SessionConsoleLogStore } from '~/ingestion/pipelines/sessionreplay/sessions/session-console-log-store'
-import { SessionFilter } from '~/ingestion/pipelines/sessionreplay/sessions/session-filter'
-import { SessionTracker } from '~/ingestion/pipelines/sessionreplay/sessions/session-tracker'
+import { RetentionPeriod, RetentionPeriodToDaysMap } from '~/ingestion/pipelines/sessionreplay/shared/constants'
import { SodiumRecordingDecryptor, SodiumRecordingEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/crypto'
import { SessionFeatureStore } from '~/ingestion/pipelines/sessionreplay/shared/features/session-feature-store'
import { MemoryKeyStore } from '~/ingestion/pipelines/sessionreplay/shared/keystore'
@@ -85,10 +84,27 @@ describe('session recording encryption integration', () => {
let mockMetadataStore: jest.Mocked<SessionMetadataStore>
let mockConsoleLogStore: jest.Mocked<SessionConsoleLogStore>
let mockFeatureStore: jest.Mocked<SessionFeatureStore>
- let mockSessionTracker: jest.Mocked<SessionTracker>
- let mockSessionFilter: jest.Mocked<SessionFilter>
let batchBuffer: Uint8Array
let currentOffset: number
+ // Sessions whose key has already been generated, so repeats resolve via getKey — mirroring what
+ // the pre-record resolve-key step does in production.
+ let seenSessions: Set<string>
+
+ // Resolves the session's key the way the pre-record step would (generate once, then get) and
+ // records it, since the recorder no longer resolves keys itself.
+ const recordMessage = async (
+ message: MessageWithTeam,
+ retentionPeriod: RetentionPeriod = '30d'
+ ): Promise<number> => {
+ const { session_id: sessionId } = message.message
+ const { teamId } = message.team
+ const cacheKey = `${teamId}:${sessionId}`
+ const sessionKey = seenSessions.has(cacheKey)
+ ? await keyStore.getKey(sessionId, teamId)
+ : await keyStore.generateKey(sessionId, teamId, RetentionPeriodToDaysMap[retentionPeriod])
+ seenSessions.add(cacheKey)
+ return recorder.record(message, retentionPeriod, sessionKey)
+ }
beforeAll(async () => {
await sodium.ready
@@ -97,6 +113,7 @@ describe('session recording encryption integration', () => {
beforeEach(async () => {
currentOffset = 0
batchBuffer = new Uint8Array()
+ seenSessions = new Set()
keyStore = new MemoryKeyStore()
await keyStore.start()
@@ -149,24 +166,12 @@ describe('session recording encryption integration', () => {
storeSessionFeatures: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<SessionFeatureStore>
- mockSessionTracker = {
- trackSession: jest.fn().mockResolvedValue(true),
- } as unknown as jest.Mocked<SessionTracker>
-
- mockSessionFilter = {
- isBlocked: jest.fn().mockResolvedValue(false),
- handleNewSession: jest.fn().mockResolvedValue(undefined),
- } as unknown as jest.Mocked<SessionFilter>
-
recorder = new SessionBatchRecorder(
mockOffsetManager,
mockStorage,
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- keyStore,
encryptor
)
})
@@ -232,7 +237,7 @@ describe('session recording encryption integration', () => {
]
const message = createMessage(sessionId, teamId, originalEvents)
- await recorder.record(message, '30d')
+ await recordMessage(message)
const metadata = await recorder.flush()
expect(metadata).toHaveLength(1)
@@ -266,11 +271,10 @@ describe('session recording encryption integration', () => {
const sessionId = 'multi-block-session'
const teamId = 42
- mockSessionTracker.trackSession.mockResolvedValueOnce(true)
const message1 = createMessage(sessionId, teamId, [
{ type: EventType.FullSnapshot, data: { source: 1, snapshot: { html: '<div>Block 1</div>' } } },
])
- await recorder.record(message1, '30d')
+ await recordMessage(message1)
const metadata1 = await recorder.flush()
const encryptedBlock1 = readEncryptedBlockFromBatch(metadata1[0])
@@ -285,17 +289,13 @@ describe('session recording encryption integration', () => {
mockMetadataStore,
mockConsoleLogStore,
mockFeatureStore,
- mockSessionTracker,
- mockSessionFilter,
- keyStore,
encryptor
)
- mockSessionTracker.trackSession.mockResolvedValueOnce(false)
const message2 = createMessage(sessionId, teamId, [
{ type: EventType.IncrementalSnapshot, data: { source: 2, mutations: [{ id: 2 }] } },
])
- await recorder.record(message2, '30d')
+ await recordMessage(message2)
const metadata2 = await recorder.flush()
const encryptedBlock2 = readEncryptedBlockFromBatch(metadata2[0])
@@ -320,7 +320,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, '30d')
+ await recordMessage(message)
const metadata = await recorder.flush()
const encryptedBlock = readEncryptedBlockFromBatch(metadata[0])
@@ -345,7 +345,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, '30d')
+ await recordMessage(message)
}
const metadata = await recorder.flush()
diff --git a/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-filter.integration.test.ts b/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-filter.integration.test.ts
index 3237526e54e6..143988f59bbe 100644
--- a/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-filter.integration.test.ts
+++ b/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-filter.integration.test.ts
@@ -2,10 +2,15 @@ import { v4 as uuidv4 } from 'uuid'
import { createRedisPoolFromConfig } from '~/common/utils/db/redis'
import { SessionFilter, SessionFilterConfig } from '~/ingestion/pipelines/sessionreplay/sessions/session-filter'
+import { SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'
// nosemgrep: redis-unencrypted-transport (local testing only)
const REDIS_URL = process.env.REDIS_URL || 'redis://127.0.0.1'
+// Single-session convenience over the batched isBlocked.
+const blocked = (filter: SessionFilter, teamId: number, sessionId: string): Promise<boolean> =>
+ filter.isBlocked(new SessionSet().add(teamId, sessionId)).then((s) => s.has(teamId, sessionId))
+
describe('SessionFilter integration', () => {
let sessionFilter: SessionFilter
let redisPool: SessionFilterConfig['redisPool']
@@ -44,15 +49,15 @@ describe('SessionFilter integration', () => {
// Bucket capacity is 5, so 6th session should be blocked
for (let i = 1; i <= 5; i++) {
const sessionId = `${testRunId}-session-${i}`
- await sessionFilter.handleNewSession(teamId, sessionId)
- const isBlocked = await sessionFilter.isBlocked(teamId, sessionId)
+ await sessionFilter.handleNewSessions(new SessionSet().add(teamId, sessionId))
+ const isBlocked = await blocked(sessionFilter, teamId, sessionId)
expect(isBlocked).toBe(false)
}
// 6th session should be rate limited and blocked
const blockedSessionId = `${testRunId}-session-6`
- await sessionFilter.handleNewSession(teamId, blockedSessionId)
- const isBlocked = await sessionFilter.isBlocked(teamId, blockedSessionId)
+ await sessionFilter.handleNewSessions(new SessionSet().add(teamId, blockedSessionId))
+ const isBlocked = await blocked(sessionFilter, teamId, blockedSessionId)
expect(isBlocked).toBe(true)
})
@@ -71,11 +76,11 @@ describe('SessionFilter integration', () => {
})
// First session consumes the bucket
- await filter1.handleNewSession(teamId, `${testRunId}-first-session`)
+ await filter1.handleNewSessions(new SessionSet().add(teamId, `${testRunId}-first-session`))
// Second session should be blocked
- await filter1.handleNewSession(teamId, sessionId)
- expect(await filter1.isBlocked(teamId, sessionId)).toBe(true)
+ await filter1.handleNewSessions(new SessionSet().add(teamId, sessionId))
+ expect(await blocked(filter1, teamId, sessionId)).toBe(true)
// Create a new filter instance (simulating a new consumer)
const filter2 = new SessionFilter({
@@ -88,11 +93,11 @@ describe('SessionFilter integration', () => {
})
// The blocked session should still be blocked (fetched from Redis)
- const isBlockedInNewFilter = await filter2.isBlocked(teamId, sessionId)
+ const isBlockedInNewFilter = await blocked(filter2, teamId, sessionId)
expect(isBlockedInNewFilter).toBe(true)
// A new session that was never blocked should not be blocked
- const isNewSessionBlocked = await filter2.isBlocked(teamId, `${testRunId}-never-blocked`)
+ const isNewSessionBlocked = await blocked(filter2, teamId, `${testRunId}-never-blocked`)
expect(isNewSessionBlocked).toBe(false)
})
@@ -109,12 +114,12 @@ describe('SessionFilter integration', () => {
})
// First session consumes the bucket
- await disabledFilter.handleNewSession(teamId, `${testRunId}-disabled-session-1`)
+ await disabledFilter.handleNewSessions(new SessionSet().add(teamId, `${testRunId}-disabled-session-1`))
// Second session would be rate limited but should NOT be blocked
const session2 = `${testRunId}-disabled-session-2`
- await disabledFilter.handleNewSession(teamId, session2)
- expect(await disabledFilter.isBlocked(teamId, session2)).toBe(false)
+ await disabledFilter.handleNewSessions(new SessionSet().add(teamId, session2))
+ expect(await blocked(disabledFilter, teamId, session2)).toBe(false)
})
it('should correctly cache blocked status locally', async () => {
@@ -130,18 +135,94 @@ describe('SessionFilter integration', () => {
})
// Exhaust bucket and block a session
- await filter.handleNewSession(teamId, `${testRunId}-cache-first`)
+ await filter.handleNewSessions(new SessionSet().add(teamId, `${testRunId}-cache-first`))
const blockedSession = `${testRunId}-cache-blocked`
- await filter.handleNewSession(teamId, blockedSession)
+ await filter.handleNewSessions(new SessionSet().add(teamId, blockedSession))
// First isBlocked call goes to Redis
- const isBlocked1 = await filter.isBlocked(teamId, blockedSession)
+ const isBlocked1 = await blocked(filter, teamId, blockedSession)
expect(isBlocked1).toBe(true)
// Second call should be served from cache (we can't directly verify this
// in integration test, but we can verify the result is consistent)
- const isBlocked2 = await filter.isBlocked(teamId, blockedSession)
+ const isBlocked2 = await blocked(filter, teamId, blockedSession)
expect(isBlocked2).toBe(true)
})
})
+
+ describe('batch behavior', () => {
+ it('blocks a mixed batch in one call and reads each session back from a fresh instance', async () => {
+ const teamId = 5
+ const allowed = `${testRunId}-batch-allowed`
+ const blockedA = `${testRunId}-batch-blocked-a`
+ const blockedB = `${testRunId}-batch-blocked-b`
+
+ // Budget of 1: within a single batched call the first new session is allowed and the rest
+ // are rate-limited and blocked. Verifies the pipelined write persists every blocked key.
+ const writer = new SessionFilter({
+ redisPool,
+ bucketCapacity: 1,
+ bucketReplenishRate: 0.001,
+ blockingEnabled: true,
+ filterEnabled: true,
+ localCacheTtlMs: 100,
+ })
+ await writer.handleNewSessions(
+ new SessionSet().add(teamId, allowed).add(teamId, blockedA).add(teamId, blockedB)
+ )
+
+ // A fresh instance (cold local cache) resolves the whole batch from Redis in one read.
+ const reader = new SessionFilter({
+ redisPool,
+ bucketCapacity: 1000,
+ bucketReplenishRate: 1,
+ blockingEnabled: true,
+ filterEnabled: true,
+ localCacheTtlMs: 100,
+ })
+ const result = await reader.isBlocked(
+ new SessionSet()
+ .add(teamId, allowed)
+ .add(teamId, blockedA)
+ .add(teamId, blockedB)
+ .add(teamId, `${testRunId}-batch-never`)
+ )
+
+ expect(result.has(teamId, allowed)).toBe(false)
+ expect(result.has(teamId, blockedA)).toBe(true)
+ expect(result.has(teamId, blockedB)).toBe(true)
+ expect(result.has(teamId, `${testRunId}-batch-never`)).toBe(false)
+ })
+
+ it('keeps blocks isolated per team in Redis', async () => {
+ const teamA = 6
+ const teamB = 7
+ const shared = `${testRunId}-team-shared`
+
+ // Block (team A, shared) by exhausting team A's budget; team B is never touched.
+ const writer = new SessionFilter({
+ redisPool,
+ bucketCapacity: 1,
+ bucketReplenishRate: 0.001,
+ blockingEnabled: true,
+ filterEnabled: true,
+ localCacheTtlMs: 100,
+ })
+ await writer.handleNewSessions(new SessionSet().add(teamA, `${testRunId}-team-filler`).add(teamA, shared))
+
+ // A fresh instance reads both teams' identically-named session from Redis in one batch.
+ const reader = new SessionFilter({
+ redisPool,
+ bucketCapacity: 1000,
+ bucketReplenishRate: 1,
+ blockingEnabled: true,
+ filterEnabled: true,
+ localCacheTtlMs: 100,
+ })
+ const result = await reader.isBlocked(new SessionSet().add(teamA, shared).add(teamB, shared))
+
+ expect(result.has(teamA, shared)).toBe(true) // blocked in Redis for team A
+ expect(result.has(teamB, shared)).toBe(false) // team B's key was never written
+ })
+ })
})
diff --git a/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-tracker.integration.test.ts b/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-tracker.integration.test.ts
index 4bf1b741f748..979c7a03616e 100644
--- a/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-tracker.integration.test.ts
+++ b/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-tracker.integration.test.ts
@@ -2,11 +2,18 @@ import { v4 as uuidv4 } from 'uuid'
import { createRedisPoolFromConfig } from '~/common/utils/db/redis'
import { SessionTracker } from '~/ingestion/pipelines/sessionreplay/sessions/session-tracker'
+import { SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'
import { RedisPool } from '~/types'
// nosemgrep: redis-unencrypted-transport (local testing only)
const REDIS_URL = process.env.REDIS_URL || 'redis://127.0.0.1'
+const sessionSet = (...pairs: [number, string][]): SessionSet => {
+ const set = new SessionSet()
+ pairs.forEach(([teamId, sessionId]) => set.add(teamId, sessionId))
+ return set
+}
+
describe('SessionTracker integration', () => {
let redisPool: RedisPool
let testRunId: string
@@ -25,56 +32,109 @@ describe('SessionTracker integration', () => {
await redisPool.clear()
})
- describe('end-to-end session tracking', () => {
- it('should return true for new sessions and false for existing ones', async () => {
- const sessionTracker = new SessionTracker(redisPool, 100)
- const teamId = 1
- const sessionId = `new-session-${testRunId}-1`
+ it('reports a session unseen until it is marked, then seen', async () => {
+ const tracker = new SessionTracker(redisPool, 100)
+ const teamId = 1
+ const sessionId = `new-session-${testRunId}`
- // First call should return true (new session)
- const isNew1 = await sessionTracker.trackSession(teamId, sessionId)
- expect(isNew1).toBe(true)
+ expect((await tracker.hasSeen(sessionSet([teamId, sessionId]))).get(teamId, sessionId)).toBe(false)
- // Second call should return false (session already exists)
- const isNew2 = await sessionTracker.trackSession(teamId, sessionId)
- expect(isNew2).toBe(false)
- })
+ await tracker.markSeen(sessionSet([teamId, sessionId]))
- it('should persist session tracking across SessionTracker instances', async () => {
- const teamId = 3
- const sessionId = `persistent-session-${testRunId}`
+ expect((await tracker.hasSeen(sessionSet([teamId, sessionId]))).get(teamId, sessionId)).toBe(true)
+ })
- // Create first tracker and track session
- const tracker1 = new SessionTracker(redisPool, 100)
- const isNew1 = await tracker1.trackSession(teamId, sessionId)
- expect(isNew1).toBe(true)
+ it('persists a marked session across tracker instances via Redis', async () => {
+ const teamId = 3
+ const sessionId = `persistent-session-${testRunId}`
- // Create a new tracker instance (simulating a new consumer)
- const tracker2 = new SessionTracker(redisPool, 100)
+ const tracker1 = new SessionTracker(redisPool, 100)
+ expect((await tracker1.hasSeen(sessionSet([teamId, sessionId]))).get(teamId, sessionId)).toBe(false)
+ await tracker1.markSeen(sessionSet([teamId, sessionId]))
- // The session should already exist (fetched from Redis)
- const isNew2 = await tracker2.trackSession(teamId, sessionId)
- expect(isNew2).toBe(false)
- })
+ // A fresh instance (empty local cache) still sees it, because markSeen persisted to Redis.
+ const tracker2 = new SessionTracker(redisPool, 100)
+ expect((await tracker2.hasSeen(sessionSet([teamId, sessionId]))).get(teamId, sessionId)).toBe(true)
+ })
- it('should use local cache to avoid Redis calls', async () => {
- const teamId = 4
- const sessionId = `cached-session-${testRunId}`
+ it('resolves a mixed batch of seen and unseen sessions in one call', async () => {
+ const teamId = 4
+ const seen = `seen-${testRunId}`
+ const unseen = `unseen-${testRunId}`
- // Use a long cache TTL
- const trackerWithCache = new SessionTracker(redisPool, 5 * 60 * 1000)
+ await new SessionTracker(redisPool, 5 * 60 * 1000).markSeen(sessionSet([teamId, seen]))
- // First call goes to Redis and returns true
- const isNew1 = await trackerWithCache.trackSession(teamId, sessionId)
- expect(isNew1).toBe(true)
+ // Fresh instance so the local cache doesn't pre-answer; the read must come from Redis (MGET).
+ const result = await new SessionTracker(redisPool, 5 * 60 * 1000).hasSeen(
+ sessionSet([teamId, seen], [teamId, unseen])
+ )
- // Second call should use cache and return false
- const isNew2 = await trackerWithCache.trackSession(teamId, sessionId)
- expect(isNew2).toBe(false)
+ expect(result.get(teamId, seen)).toBe(true)
+ expect(result.get(teamId, unseen)).toBe(false)
+ })
- // Third call should also use cache
- const isNew3 = await trackerWithCache.trackSession(teamId, sessionId)
- expect(isNew3).toBe(false)
- })
+ it('marks an entire batch seen in one call and reads them all back from a fresh instance', async () => {
+ const teamId = 5
+ const a = `batch-a-${testRunId}`
+ const b = `batch-b-${testRunId}`
+ const c = `batch-c-${testRunId}`
+
+ await new SessionTracker(redisPool, 5 * 60 * 1000).markSeen(sessionSet([teamId, a], [teamId, b], [teamId, c]))
+
+ // Fresh instance so the read comes from Redis: every key in the pipeline must have persisted.
+ const result = await new SessionTracker(redisPool, 5 * 60 * 1000).hasSeen(
+ sessionSet([teamId, a], [teamId, b], [teamId, c], [teamId, `batch-never-${testRunId}`])
+ )
+
+ expect(result.get(teamId, a)).toBe(true)
+ expect(result.get(teamId, b)).toBe(true)
+ expect(result.get(teamId, c)).toBe(true)
+ expect(result.get(teamId, `batch-never-${testRunId}`)).toBe(false)
+ })
+
+ it('resolves a large interleaved batch across teams, matching each session to its own seen state', async () => {
+ const teams = [10, 11, 12]
+ const all = new SessionSet()
+ const toMark = new SessionSet()
+ const expectedSeen = new Map<string, boolean>()
+
+ // Interleave seen/unseen within each team and across teams, so a misaligned MGET (result i
+ // read against the wrong session) or a per-team key collision surfaces as a mismatch.
+ for (const teamId of teams) {
+ for (let i = 0; i < 8; i++) {
+ const sessionId = `mixed-${teamId}-${i}-${testRunId}`
+ const seen = i % 2 === 0
+ all.add(teamId, sessionId)
+ if (seen) {
+ toMark.add(teamId, sessionId)
+ }
+ expectedSeen.set(`${teamId}:${sessionId}`, seen)
+ }
+ }
+
+ await new SessionTracker(redisPool, 5 * 60 * 1000).markSeen(toMark)
+
+ // Fresh instance so every answer comes from Redis (MGET), not the local cache.
+ const result = await new SessionTracker(redisPool, 5 * 60 * 1000).hasSeen(all)
+
+ for (const { teamId, sessionId } of all) {
+ expect(result.get(teamId, sessionId)).toBe(expectedSeen.get(`${teamId}:${sessionId}`))
+ }
+ })
+
+ it('keeps seen state isolated per team in Redis', async () => {
+ const teamA = 6
+ const teamB = 7
+ const shared = `team-shared-${testRunId}`
+
+ await new SessionTracker(redisPool, 5 * 60 * 1000).markSeen(sessionSet([teamA, shared]))
+
+ // A fresh instance reads both teams' identically-named session from Redis.
+ const result = await new SessionTracker(redisPool, 5 * 60 * 1000).hasSeen(
+ sessionSet([teamA, shared], [teamB, shared])
+ )
+
+ expect(result.get(teamA, shared)).toBe(true) // marked for team A
+ expect(result.get(teamB, shared)).toBe(false) // team B was never marked
})
})