:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay): flush the session batch on partition revoke via consumer v2 (#70491)
Paweł Ledwońfbfd6857b95a
diff --git a/nodejs/src/common/kafka/consumer/consumer-v2.rebalance.integration.test.ts b/nodejs/src/common/kafka/consumer/consumer-v2.rebalance.integration.test.tsnew file mode 100644index 000000000000..7807b3a1d1ab--- /dev/null+++ b/nodejs/src/common/kafka/consumer/consumer-v2.rebalance.integration.test.ts@@ -0,0 +1,1160 @@+import {+ AdminClient,+ HighLevelProducer,+ LibrdKafkaError,+ Message,+ KafkaConsumer as RdKafkaConsumer,+ TopicPartitionOffset,+} from 'node-rdkafka'+import { randomUUID } from 'node:crypto'++import { defaultConfig } from '../../config/config'+import { delay } from '../../utils/utils'+import { KafkaConsumerV2 } from './consumer-v2'++/**+ * Exact rebalance-semantics tests for KafkaConsumerV2, against a real broker reachable at+ * KAFKA_HOSTS (default: kafka:9092). The existing consumer-v2.integration.test.ts validates+ * liveness properties with tolerance ("no loss, bounded duplicates"); this suite pins the+ * exact offset semantics of a cooperative rebalance:+ * - work settled before the rebalance is committed at exactly the delivered offsets, and+ * the new owner resumes with zero redelivery,+ * - cooperative-sticky revokes are incremental: the surviving consumer never drops to zero+ * assignments while a partition moves,+ * - the generation guard: a batch in flight when the revoke arrives skips its offset store,+ * so its messages are redelivered on the moved partition (exactly once more) while the+ * retained partition never re-reads them and the group commit stays at the pre-batch mark,+ * - the onPartitionsRevoked hook (the session replay flush-on-revoke contract): it runs+ * after the drain while the partitions are still assigned, offsets it stores are committed+ * exactly as the partitions are given up — including from an already-committed baseline+ * when a flushed cycle precedes the in-flight one — a throwing hook never strands the+ * rebalance, a hook outliving the consumer's own budget (CONSUMER_REBALANCE_TIMEOUT_MS) is+ * abandoned — the rebalance proceeds without fencing the member and the late store for the+ * moved partition is discarded — and a hook outliving the broker-enforced rebalance timeout+ * (max.poll.interval.ms) gets the member fenced, its late store discarded, and recovers,+ * - the two-phase shutdown (the session replay flush-on-stop contract): stopConsuming+ * resolves only after in-flight work drains and halts intake for good, offsets stored+ * between stopConsuming and disconnect are committed as the member leaves, and a restart+ * resumes exactly after them.+ *+ * Producing uses a raw HighLevelProducer with explicit partitions so every delivery report's+ * assigned offset is kept; all expectations are derived from those reports, never assumed.+ */++jest.setTimeout(60_000)++const KAFKA_HOSTS = process.env.KAFKA_HOSTS ?? 'kafka:9092'+const KAFKA_CONFIG = { 'metadata.broker.list': KAFKA_HOSTS }++type LedgerEntry = {+ consumerId: string+ partition: number+ offset: number+ key: string+ value: string+ seenAt: number+}++type ProducedRecord = {+ key: string+ value: string+ partition: number+ offset: number+}++async function createTopic(topic: string, numPartitions: number): Promise<void> {+ const client = AdminClient.create(KAFKA_CONFIG)+ await new Promise<void>((resolve, reject) => {+ client.createTopic(+ { topic, num_partitions: numPartitions, replication_factor: 1 },+ 10_000,+ (err: LibrdKafkaError) => {+ if (err && err.message && !/already exists/i.test(err.message)) {+ reject(err)+ } else {+ resolve()+ }+ }+ )+ })+ client.disconnect()+}++async function deleteTopic(topic: string): Promise<void> {+ const client = AdminClient.create(KAFKA_CONFIG)+ await new Promise<void>((resolve) => {+ client.deleteTopic(topic, 10_000, () => resolve())+ })+ client.disconnect()+}++async function createRawProducer(): Promise<HighLevelProducer> {+ const producer = new HighLevelProducer(KAFKA_CONFIG)+ await new Promise<void>((resolve, reject) => {+ producer.connect(undefined, (err) => (err ? reject(err) : resolve()))+ })+ producer.setPollInterval(50)+ return producer+}++/**+ * Produces one message per (key, partition) pair and returns each delivery report's+ * broker-assigned offset, so tests can assert against exact offsets instead of assuming them.+ */+async function produceTracked(+ producer: HighLevelProducer,+ topic: string,+ records: { key: string; partition: number }[]+): Promise<ProducedRecord[]> {+ return await Promise.all(+ records.map(+ ({ key, partition }) =>+ new Promise<ProducedRecord>((resolve, reject) => {+ const value = `payload-${key}`+ producer.produce(+ topic,+ partition,+ Buffer.from(value),+ Buffer.from(key),+ Date.now(),+ [],+ (err: unknown, offset: number | null | undefined) => {+ if (err || typeof offset !== 'number') {+ reject(err ?? new Error('no offset in delivery report'))+ } else {+ resolve({ key, value, partition, offset })+ }+ }+ )+ })+ )+ )+}++async function waitFor(predicate: () => boolean, timeoutMs: number, pollMs = 20): Promise<void> {+ const deadline = Date.now() + timeoutMs+ while (Date.now() < deadline) {+ if (predicate()) {+ return+ }+ await delay(pollMs)+ }+ throw new Error(`waitFor timed out after ${timeoutMs}ms`)+}++async function waitForAsync(predicate: () => Promise<boolean>, timeoutMs: number, pollMs = 200): Promise<void> {+ const deadline = Date.now() + timeoutMs+ while (Date.now() < deadline) {+ if (await predicate()) {+ return+ }+ await delay(pollMs)+ }+ throw new Error(`waitForAsync timed out after ${timeoutMs}ms`)+}++/**+ * Reads the group's committed offset for a partition via a raw consumer in the same group.+ * Connecting without subscribing does not join the group, so this never triggers a rebalance.+ * Returns null when nothing has been committed yet.+ */+async function fetchCommittedOffset(groupId: string, topic: string, partition: number): Promise<number | null> {+ const consumer = new RdKafkaConsumer({ 'group.id': groupId, ...KAFKA_CONFIG }, {})+ await new Promise<void>((resolve, reject) => {+ consumer.on('ready', () => resolve())+ consumer.on('event.error', (err) => reject(err))+ consumer.connect()+ })+ try {+ const committed = await new Promise<TopicPartitionOffset[]>((resolve, reject) => {+ consumer.committed([{ topic, partition }], 10_000, (err, toppars) =>+ err ? reject(err) : resolve(toppars as TopicPartitionOffset[])+ )+ })+ const offset = committed[0]?.offset+ return typeof offset === 'number' && offset >= 0 ? offset : null+ } finally {+ consumer.disconnect()+ }+}++function makeConsumer(+ groupId: string,+ topic: string,+ eachBatch: (messages: Message[]) => Promise<{ backgroundTask?: Promise<unknown> } | void>,+ opts: {+ autoOffsetStore?: boolean+ onPartitionsRevoked?: (assignments: { topic: string; partition: number }[]) => Promise<void>+ rdKafkaOverrides?: Record<string, string | number | boolean>+ } = {}+): KafkaConsumerV2 {+ const consumer = new KafkaConsumerV2(+ { groupId, topic, batchTimeoutMs: 50, autoOffsetStore: opts.autoOffsetStore },+ {+ ...KAFKA_CONFIG,+ // Short but realistic session timeout keeps group transitions in these tests fast.+ // 6s is the broker's floor (group.min.session.timeout.ms defaults to 6000).+ 'session.timeout.ms': 6_000,+ // The broker-enforced rebalance timeout (librdkafka sends max.poll.interval.ms as+ // the JoinGroup rebalance timeout). Every flush in this suite must finish inside+ // it — except in the fencing test, which lowers it deliberately to get fenced.+ 'max.poll.interval.ms': 30_000,+ // Commit stored offsets promptly so exact committed-offset assertions don't wait+ // out the 5s librdkafka default between polls.+ 'auto.commit.interval.ms': 500,+ ...opts.rdKafkaOverrides,+ } as Record<string, unknown>+ )+ void consumer.connect(eachBatch, opts.onPartitionsRevoked).catch((err: unknown) => {+ throw new Error(`Consumer failed to connect: ${String(err)}`)+ })+ return consumer+}++function countByPartitionOffset(ledger: LedgerEntry[]): Map<string, number> {+ const counts = new Map<string, number>()+ for (const e of ledger) {+ const k = `${e.partition}:${e.offset}`+ counts.set(k, (counts.get(k) ?? 0) + 1)+ }+ return counts+}++describe('KafkaConsumerV2 rebalance semantics (integration)', () => {+ let producer: HighLevelProducer++ beforeAll(async () => {+ producer = await createRawProducer()+ })++ afterAll(async () => {+ await new Promise<void>((resolve) => producer.disconnect(() => resolve()))+ })++ // v2's automatic offset path: each settled batch stores highest+1 itself, and librdkafka+ // commits stored offsets on the auto-commit timer and on unassign. No test code in this+ // group stores offsets.+ describe('autoOffsetStore on: offsets stored automatically as batches settle', () => {+ it('settled work commits exactly; cooperative rebalance moves one partition with zero redelivery', async () => {+ const topic = `v2_int_reb_exact_${randomUUID()}`+ const groupId = `v2-int-reb-exact-${randomUUID()}`+ await createTopic(topic, 2)++ const ledger: LedgerEntry[] = []+ const record = (consumerId: string) => (messages: Message[]) => {+ for (const m of messages) {+ ledger.push({+ consumerId,+ partition: m.partition,+ offset: m.offset,+ key: m.key?.toString() ?? '',+ value: m.value?.toString() ?? '',+ seenAt: Date.now(),+ })+ }+ return Promise.resolve()+ }++ const consumerA = makeConsumer(groupId, topic, record('A'), { autoOffsetStore: true })+ let consumerB: KafkaConsumerV2 | undefined++ try {+ await waitFor(() => consumerA.assignments().length === 2, 10_000)++ const wave1 = await produceTracked(producer, topic, [+ ...Array.from({ length: 5 }, (_, i) => ({ key: `a${i}`, partition: 0 })),+ ...Array.from({ length: 5 }, (_, i) => ({ key: `b${i}`, partition: 1 })),+ ])+ // Fresh topic: the broker must have assigned offsets 0..4 on each partition.+ for (const partition of [0, 1]) {+ expect(+ wave1+ .filter((r) => r.partition === partition)+ .map((r) => r.offset)+ .sort((x, y) => x - y)+ ).toEqual([0, 1, 2, 3, 4])+ }+ await waitFor(() => ledger.length >= wave1.length, 8_000)++ // With every batch settled, the stored offsets are committed at exactly+ // highest-delivered + 1 per partition.+ const expectedCommit = new Map<number, number>()+ for (const partition of [0, 1]) {+ const highest = Math.max(...wave1.filter((r) => r.partition === partition).map((r) => r.offset))+ expectedCommit.set(partition, highest + 1)+ }+ for (const [partition, offset] of expectedCommit) {+ await waitForAsync(+ async () => (await fetchCommittedOffset(groupId, topic, partition)) === offset,+ 10_000+ )+ }++ // B joins: cooperative-sticky moves exactly one partition, and A never drops to+ // zero assignments while it happens (the incremental-rebalance property).+ consumerB = makeConsumer(groupId, topic, record('B'), { autoOffsetStore: true })+ const b = consumerB+ let minAssignedA = 2+ await waitFor(() => {+ minAssignedA = Math.min(minAssignedA, consumerA.assignments().length)+ return consumerA.assignments().length === 1 && b.assignments().length === 1+ }, 15_000)+ expect(minAssignedA).toBeGreaterThanOrEqual(1)++ // The new owner resumes from the exact committed offsets: a second wave lands+ // contiguously after the first, and nothing from the first wave is redelivered.+ const wave2 = await produceTracked(producer, topic, [+ ...Array.from({ length: 3 }, (_, i) => ({ key: `a${5 + i}`, partition: 0 })),+ ...Array.from({ length: 3 }, (_, i) => ({ key: `b${5 + i}`, partition: 1 })),+ ])+ for (const partition of [0, 1]) {+ expect(Math.min(...wave2.filter((r) => r.partition === partition).map((r) => r.offset))).toBe(+ expectedCommit.get(partition)+ )+ }++ const produced = [...wave1, ...wave2]+ await waitFor(() => countByPartitionOffset(ledger).size >= produced.length, 15_000)++ // Exact per-message validation: every produced record consumed at exactly the+ // (partition, offset) its delivery report announced, exactly once, correct content.+ expect(ledger.length).toBe(produced.length)+ const consumedAt = new Map(+ ledger.map((e) => [`${e.partition}:${e.offset}`, { key: e.key, value: e.value }])+ )+ const producedAt = new Map(+ produced.map((r) => [`${r.partition}:${r.offset}`, { key: r.key, value: r.value }])+ )+ expect(consumedAt).toEqual(producedAt)++ // Both members did real work after the split.+ expect(+ new Set(ledger.filter((e) => wave2.some((r) => r.value === e.value)).map((e) => e.consumerId)).size+ ).toBe(2)+ } finally {+ await consumerA.disconnect()+ await consumerB?.disconnect()+ await deleteTopic(topic)+ }+ })++ it('a batch in flight at revoke skips its offset store (generation guard): moved partition redelivers it, retained partition does not', async () => {+ const topic = `v2_int_reb_gen_${randomUUID()}`+ const groupId = `v2-int-reb-gen-${randomUUID()}`+ await createTopic(topic, 2)++ // The generation guard only engages when the loop processes the REVOKE while a task+ // is still in flight. With the default of 1 background slot, backpressure blocks the+ // loop on that very task (no polling → no rebalance callback → the task settles and+ // stores before the generation ever bumps). Give the loop free slots so it can take+ // the revoke while the gated task is pending — the scenario the guard exists for.+ const savedMaxBackgroundTasks = defaultConfig.CONSUMER_MAX_BACKGROUND_TASKS+ defaultConfig.CONSUMER_MAX_BACKGROUND_TASKS = 4++ const ledger: LedgerEntry[] = []+ // Gate for consumer A's background tasks: once armed, A's batches don't settle+ // until the test releases them — keeping their offset stores in flight across+ // the revoke so the generation guard is what decides their fate.+ let gateArmed = false+ let releaseGate: () => void = () => {}+ const gate = new Promise<void>((resolve) => {+ releaseGate = resolve+ })++ const recordA = (messages: Message[]): { backgroundTask?: Promise<unknown> } => {+ for (const m of messages) {+ ledger.push({+ consumerId: 'A',+ partition: m.partition,+ offset: m.offset,+ key: m.key?.toString() ?? '',+ value: m.value?.toString() ?? '',+ seenAt: Date.now(),+ })+ }+ return gateArmed ? { backgroundTask: gate } : {}+ }+ const recordB = (messages: Message[]): void => {+ for (const m of messages) {+ ledger.push({+ consumerId: 'B',+ partition: m.partition,+ offset: m.offset,+ key: m.key?.toString() ?? '',+ value: m.value?.toString() ?? '',+ seenAt: Date.now(),+ })+ }+ }++ const consumerA = makeConsumer(groupId, topic, (msgs) => Promise.resolve(recordA(msgs)), {+ autoOffsetStore: true,+ })+ let consumerB: KafkaConsumerV2 | undefined++ try {+ await waitFor(() => consumerA.assignments().length === 2, 10_000)++ const wave1 = await produceTracked(producer, topic, [+ ...Array.from({ length: 3 }, (_, i) => ({ key: `a${i}`, partition: 0 })),+ ...Array.from({ length: 3 }, (_, i) => ({ key: `b${i}`, partition: 1 })),+ ])+ await waitFor(() => ledger.length >= wave1.length, 8_000)++ const preGateCommit = new Map<number, number>()+ for (const partition of [0, 1]) {+ const highest = Math.max(...wave1.filter((r) => r.partition === partition).map((r) => r.offset))+ preGateCommit.set(partition, highest + 1)+ await waitForAsync(+ async () => (await fetchCommittedOffset(groupId, topic, partition)) === highest + 1,+ 10_000+ )+ }++ // One gated message per partition: consumed by A, but its settle chain (and+ // therefore its offset store) hangs on the gate.+ gateArmed = true+ const gated = await produceTracked(producer, topic, [+ { key: 'gated-p0', partition: 0 },+ { key: 'gated-p1', partition: 1 },+ ])+ await waitFor(() => gated.every((g) => ledger.some((e) => e.value === g.value)), 8_000)++ // B joins while the gated batch is still in flight. The revoke bumps the+ // generation and drains — the drain blocks on our gate. Hold it long enough+ // for the revoke to be firmly in progress, then release.+ consumerB = makeConsumer(groupId, topic, (msgs) => Promise.resolve(recordB(msgs)), {+ autoOffsetStore: true,+ })+ const b = consumerB+ await delay(8_000)+ releaseGate()++ await waitFor(() => consumerA.assignments().length === 1 && b.assignments().length === 1, 15_000)+ const movedPartition = b.assignments()[0].partition+ const retainedPartition = movedPartition === 0 ? 1 : 0++ // The generation guard skipped the gated batch's store, so the moved partition's+ // gated message is redelivered to B from the pre-gate commit point: seen exactly+ // twice overall (once by A pre-revoke, once by B). The retained partition stays+ // with A, whose in-memory position is already past its gated message: exactly once.+ const gatedMoved = gated.find((g) => g.partition === movedPartition)!+ const gatedRetained = gated.find((g) => g.partition === retainedPartition)!+ await waitFor(() => ledger.filter((e) => e.value === gatedMoved.value).length >= 2, 15_000)+ expect(+ ledger+ .filter((e) => e.value === gatedMoved.value)+ .map((e) => e.consumerId)+ .sort()+ ).toEqual(['A', 'B'])+ expect(ledger.filter((e) => e.value === gatedRetained.value).map((e) => e.consumerId)).toEqual(['A'])++ // Commits reflect the guard exactly: the retained partition's commit is still the+ // pre-gate mark (its gated store was skipped and nothing re-stored it), while the+ // moved partition advances past the gated message once B's redelivery settles.+ await waitForAsync(+ async () => (await fetchCommittedOffset(groupId, topic, movedPartition)) === gatedMoved.offset + 1,+ 15_000+ )+ expect(await fetchCommittedOffset(groupId, topic, retainedPartition)).toBe(+ preGateCommit.get(retainedPartition)+ )+ } finally {+ defaultConfig.CONSUMER_MAX_BACKGROUND_TASKS = savedMaxBackgroundTasks+ await consumerA.disconnect()+ await consumerB?.disconnect()+ await deleteTopic(topic)+ }+ })+ })++ // The session replay mode: autoCommit stays on but nothing is stored automatically, so+ // offsets reach the broker only when a flush stores them explicitly — here, the revoke hook.+ describe('autoOffsetStore off: offsets stored only by the revoke hook (replay-style)', () => {+ // The flush-on-revoke contract the session replay consumer relies on, at v2's cooperative+ // protocol. The flush deliberately outlives session.timeout.ms (6s): the background+ // heartbeat thread must keep the member alive for its whole duration — a slow flush is+ // bounded by max.poll.interval.ms, never the session timeout. The long window also gives+ // an unassign racing ahead of the hook ample time to manifest.+ it('flush-on-revoke outliving the session timeout: hook runs while assigned, stored offsets commit, no reprocessing', async () => {+ const flushDurationMs = 7_000+ const topic = `v2_int_reb_hook_${randomUUID()}`+ const groupId = `v2-int-reb-hook-${randomUUID()}`+ await createTopic(topic, 2)++ const ledger: LedgerEntry[] = []+ const trackedHighest = new Map<number, number>()+ const hook: {+ invocations: number+ revokedPartitions: { topic: string; partition: number }[]+ assignedOnEntry: number+ assignedAfterDelay: number+ storeError: unknown+ completedAt: number+ } = {+ invocations: 0,+ revokedPartitions: [],+ assignedOnEntry: -1,+ assignedAfterDelay: -1,+ storeError: null,+ completedAt: 0,+ }++ const record = (consumerId: string) => (messages: Message[]) => {+ for (const m of messages) {+ ledger.push({+ consumerId,+ partition: m.partition,+ offset: m.offset,+ key: m.key?.toString() ?? '',+ value: m.value?.toString() ?? '',+ seenAt: Date.now(),+ })+ trackedHighest.set(m.partition, Math.max(trackedHighest.get(m.partition) ?? -1, m.offset))+ }+ return Promise.resolve()+ }++ const consumerA = makeConsumer(groupId, topic, record('A'), {+ autoOffsetStore: false,+ onPartitionsRevoked: async (revoked) => {+ if (++hook.invocations > 1) {+ return+ }+ hook.revokedPartitions = revoked.map((tp) => ({ topic: tp.topic, partition: tp.partition }))+ hook.assignedOnEntry = consumerA.assignments().length+ // The simulated flush: widens the revoke window so an unassign racing+ // ahead of the hook reliably manifests — as a shrunken assignment or a+ // store error below.+ await delay(flushDurationMs)+ hook.assignedAfterDelay = consumerA.assignments().length+ try {+ // Like the real ingester's flush: store offsets for everything tracked,+ // not just the partitions being revoked.+ consumerA.offsetsStore(+ [...trackedHighest.entries()].map(([partition, offset]) => ({+ topic,+ partition,+ offset: offset + 1,+ }))+ )+ } catch (e) {+ hook.storeError = e+ }+ hook.completedAt = Date.now()+ },+ })+ let consumerB: KafkaConsumerV2 | undefined++ try {+ await waitFor(() => consumerA.assignments().length === 2, 10_000)++ const wave1 = await produceTracked(producer, topic, [+ ...Array.from({ length: 4 }, (_, i) => ({ key: `a${i}`, partition: 0 })),+ ...Array.from({ length: 4 }, (_, i) => ({ key: `b${i}`, partition: 1 })),+ ])+ await waitFor(() => ledger.length >= wave1.length, 8_000)++ // Precondition: autoOffsetStore is off and nothing was stored, so nothing is+ // committed — only the hook's store can move the group offsets.+ for (const partition of [0, 1]) {+ expect(await fetchCommittedOffset(groupId, topic, partition)).toBeNull()+ }++ consumerB = makeConsumer(groupId, topic, record('B'), { autoOffsetStore: false })+ const b = consumerB++ await waitFor(() => hook.completedAt > 0, 15_000)++ // Cooperative revoke: exactly one partition moves, and A still owns BOTH+ // partitions for the whole duration of the flush.+ expect(hook.revokedPartitions).toHaveLength(1)+ expect(hook.assignedOnEntry).toBe(2)+ expect(hook.assignedAfterDelay).toBe(2)+ expect(hook.storeError).toBeNull()++ await waitFor(() => consumerA.assignments().length === 1 && b.assignments().length === 1, 15_000)+ const movedPartition = b.assignments()[0].partition++ // The moved partition's stored offset is committed as part of the unassign;+ // the retained partition's store lands via the auto-commit timer. Both exact.+ const expectedCommit = new Map<number, number>()+ for (const partition of [0, 1]) {+ const highest = Math.max(...wave1.filter((r) => r.partition === partition).map((r) => r.offset))+ expectedCommit.set(partition, highest + 1)+ }+ for (const partition of [movedPartition, movedPartition === 0 ? 1 : 0]) {+ await waitForAsync(+ async () =>+ (await fetchCommittedOffset(groupId, topic, partition)) === expectedCommit.get(partition),+ 15_000+ )+ }++ // The new owner resumes after the flushed offsets: a second wave lands+ // contiguously and nothing from the first wave is ever redelivered.+ const wave2 = await produceTracked(producer, topic, [+ ...Array.from({ length: 3 }, (_, i) => ({ key: `a${4 + i}`, partition: 0 })),+ ...Array.from({ length: 3 }, (_, i) => ({ key: `b${4 + i}`, partition: 1 })),+ ])+ for (const partition of [0, 1]) {+ expect(Math.min(...wave2.filter((r) => r.partition === partition).map((r) => r.offset))).toBe(+ expectedCommit.get(partition)+ )+ }++ const produced = [...wave1, ...wave2]+ await waitFor(() => countByPartitionOffset(ledger).size >= produced.length, 15_000)+ expect(ledger.length).toBe(produced.length)+ const consumedAt = new Map(+ ledger.map((e) => [`${e.partition}:${e.offset}`, { key: e.key, value: e.value }])+ )+ const producedAt = new Map(+ produced.map((r) => [`${r.partition}:${r.offset}`, { key: r.key, value: r.value }])+ )+ expect(consumedAt).toEqual(producedAt)+ } finally {+ await consumerA.disconnect()+ await consumerB?.disconnect()+ await deleteTopic(topic)+ }+ })++ it('a throwing revoke hook still releases the partition: moved partition reprocesses, retained partition is unaffected', async () => {+ const topic = `v2_int_reb_hookthrow_${randomUUID()}`+ const groupId = `v2-int-reb-hookthrow-${randomUUID()}`+ await createTopic(topic, 2)++ const ledger: LedgerEntry[] = []+ const record = (consumerId: string) => (messages: Message[]) => {+ for (const m of messages) {+ ledger.push({+ consumerId,+ partition: m.partition,+ offset: m.offset,+ key: m.key?.toString() ?? '',+ value: m.value?.toString() ?? '',+ seenAt: Date.now(),+ })+ }+ return Promise.resolve()+ }++ const consumerA = makeConsumer(groupId, topic, record('A'), {+ autoOffsetStore: false,+ onPartitionsRevoked: () => {+ throw new Error('flush failed during revoke')+ },+ })+ let consumerB: KafkaConsumerV2 | undefined++ try {+ await waitFor(() => consumerA.assignments().length === 2, 10_000)+ const wave1 = await produceTracked(producer, topic, [+ ...Array.from({ length: 3 }, (_, i) => ({ key: `a${i}`, partition: 0 })),+ ...Array.from({ length: 3 }, (_, i) => ({ key: `b${i}`, partition: 1 })),+ ])+ await waitFor(() => ledger.length >= wave1.length, 8_000)++ consumerB = makeConsumer(groupId, topic, record('B'), { autoOffsetStore: false })+ const b = consumerB++ // The hook threw, so nothing was stored — but the partition must still be given+ // up. The new owner starts from earliest and redelivers the moved partition's+ // wave; the retained partition stays with A and is never re-read.+ await waitFor(() => consumerA.assignments().length === 1 && b.assignments().length === 1, 20_000)+ const movedPartition = b.assignments()[0].partition+ const retainedPartition = movedPartition === 0 ? 1 : 0+ const movedHighest = Math.max(+ ...wave1.filter((r) => r.partition === movedPartition).map((r) => r.offset)+ )++ await waitFor(+ () =>+ ledger.filter(+ (e) => e.consumerId === 'B' && e.partition === movedPartition && e.offset === movedHighest+ ).length >= 1,+ 15_000+ )+ for (const r of wave1) {+ const expectedCount = r.partition === movedPartition ? 2 : 1+ expect(ledger.filter((e) => e.value === r.value)).toHaveLength(expectedCount)+ }+ expect(await fetchCommittedOffset(groupId, topic, retainedPartition)).toBeNull()+ } finally {+ await consumerA.disconnect()+ await consumerB?.disconnect()+ await deleteTopic(topic)+ }+ })++ it('a flush exceeding the consumer budget: the hook is abandoned, the rebalance proceeds, the member survives unfenced', async () => {+ const topic = `v2_int_reb_hookabandon_${randomUUID()}`+ const groupId = `v2-int-reb-hookabandon-${randomUUID()}`+ await createTopic(topic, 2)++ // The consumer-side budget for the revoke hook (drainTimeoutMs), well under+ // max.poll.interval.ms (30s here): the consumer gives the partitions up itself, so+ // the member must NOT get fenced — it keeps its retained partition and stays live.+ // The flush outlives the budget by enough that the takeover assertions all land+ // while it is still running.+ const hookBudgetMs = 3_000+ const flushDurationMs = 15_000+ const savedRebalanceTimeout = defaultConfig.CONSUMER_REBALANCE_TIMEOUT_MS+ defaultConfig.CONSUMER_REBALANCE_TIMEOUT_MS = hookBudgetMs++ const ledger: LedgerEntry[] = []+ const tracked = new Map<number, number>()+ const hook = { invocations: 0, completedAt: 0 }++ const record = (consumerId: string, track: boolean) => (messages: Message[]) => {+ for (const m of messages) {+ ledger.push({+ consumerId,+ partition: m.partition,+ offset: m.offset,+ key: m.key?.toString() ?? '',+ value: m.value?.toString() ?? '',+ seenAt: Date.now(),+ })+ if (track) {+ tracked.set(m.partition, Math.max(tracked.get(m.partition) ?? 0, m.offset + 1))+ }+ }+ return Promise.resolve()+ }++ const consumerA = makeConsumer(groupId, topic, record('A', true), {+ autoOffsetStore: false,+ onPartitionsRevoked: async () => {+ if (++hook.invocations > 1) {+ return+ }+ await delay(flushDurationMs)+ // The abandoned flush finally stores its tracked offsets. For the moved+ // partition this must never become a group commit — the new owner already+ // reprocessed instead.+ try {+ consumerA.offsetsStore(+ [...tracked.entries()].map(([partition, offset]) => ({ topic, partition, offset }))+ )+ } catch {+ // Rejection of the moved partition's store is an acceptable outcome too.+ }+ hook.completedAt = Date.now()+ },+ })+ let consumerB: KafkaConsumerV2 | undefined++ try {+ await waitFor(() => consumerA.assignments().length === 2, 10_000)+ const wave1 = await produceTracked(producer, topic, [+ ...Array.from({ length: 3 }, (_, i) => ({ key: `a${i}`, partition: 0 })),+ ...Array.from({ length: 3 }, (_, i) => ({ key: `b${i}`, partition: 1 })),+ ])+ await waitFor(() => ledger.length >= wave1.length, 8_000)+ for (const partition of [0, 1]) {+ expect(await fetchCommittedOffset(groupId, topic, partition)).toBeNull()+ }++ consumerB = makeConsumer(groupId, topic, record('B', false), { autoOffsetStore: false })+ const b = consumerB++ // The budget releases the rebalance: B owns the moved partition and (with no+ // committed offsets) redelivers its wave while the flush is still running.+ await waitFor(+ () => consumerA.assignments().length === 1 && b.assignments().length === 1,+ hookBudgetMs + 10_000+ )+ const movedPartition = b.assignments()[0].partition+ const retainedPartition = movedPartition === 0 ? 1 : 0+ await waitFor(+ () =>+ wave1+ .filter((r) => r.partition === movedPartition)+ .every((r) =>+ ledger.some(+ (e) => e.consumerId === 'B' && e.partition === r.partition && e.offset === r.offset+ )+ ),+ 12_000+ )+ expect(hook.completedAt).toBe(0)++ // Unlike the fencing case, the member survives: it keeps the retained partition+ // and keeps consuming new messages on it while the flush is still in progress.+ const wave2 = await produceTracked(producer, topic, [+ { key: 'retained-post', partition: retainedPartition },+ ])+ await waitFor(() => ledger.some((e) => e.consumerId === 'A' && e.value === wave2[0].value), 10_000)+ expect(consumerA.assignments().length).toBe(1)++ // Once the flush finishes, its late store for the moved partition is discarded:+ // the group offset stays unset (B stored nothing; A no longer owns it).+ await waitFor(() => hook.completedAt > 0, flushDurationMs + 10_000)+ await delay(1_500)+ expect(await fetchCommittedOffset(groupId, topic, movedPartition)).toBeNull()+ } finally {+ defaultConfig.CONSUMER_REBALANCE_TIMEOUT_MS = savedRebalanceTimeout+ await consumerA.disconnect()+ await consumerB?.disconnect()+ await deleteTopic(topic)+ }+ })++ it('a flush exceeding the rebalance timeout: the broker fences the slow member, the new owner reprocesses, the slow consumer recovers', async () => {+ const topic = `v2_int_reb_hookslow_${randomUUID()}`+ const groupId = `v2-int-reb-hookslow-${randomUUID()}`+ await createTopic(topic, 2)++ // max.poll.interval.ms doubles as the broker-enforced rebalance timeout: a member+ // that hasn't rejoined within it is kicked and the rebalance completes without it.+ // 6s is the tightest legal value — librdkafka requires it >= session.timeout.ms,+ // whose broker-enforced floor is 6s. The flush outlives it by enough that B holds+ // both partitions for several seconds mid-flush (once the flush ends, A rejoins and+ // takes a partition back — the redelivery assertions need the sole-owner window).+ const rebalanceTimeoutMs = 6_000+ const flushDurationMs = 12_000++ const ledger: LedgerEntry[] = []+ const tracked = new Map<number, number>()+ const hook = { invocations: 0, completedAt: 0 }+ const record = (consumerId: string) => (messages: Message[]) => {+ for (const m of messages) {+ ledger.push({+ consumerId,+ partition: m.partition,+ offset: m.offset,+ key: m.key?.toString() ?? '',+ value: m.value?.toString() ?? '',+ seenAt: Date.now(),+ })+ if (consumerId === 'A') {+ tracked.set(m.partition, Math.max(tracked.get(m.partition) ?? 0, m.offset + 1))+ }+ }+ return Promise.resolve()+ }++ const consumerA = makeConsumer(groupId, topic, record('A'), {+ autoOffsetStore: false,+ onPartitionsRevoked: async () => {+ if (++hook.invocations > 1) {+ return+ }+ await delay(flushDurationMs)+ // Like a real slow flush, store the tracked offsets once it finally completes —+ // the member has been fenced by now, and the test asserts this late store never+ // becomes a group commit (the new owner already reprocessed instead).+ try {+ consumerA.offsetsStore(+ [...tracked.entries()].map(([partition, offset]) => ({ topic, partition, offset }))+ )+ } catch {+ // Rejection is fine — either outcome must leave the group offsets unset.+ }+ hook.completedAt = Date.now()+ },+ rdKafkaOverrides: { 'max.poll.interval.ms': rebalanceTimeoutMs },+ })+ let consumerB: KafkaConsumerV2 | undefined++ try {+ await waitFor(() => consumerA.assignments().length === 2, 10_000)+ const wave1 = await produceTracked(producer, topic, [+ ...Array.from({ length: 3 }, (_, i) => ({ key: `a${i}`, partition: 0 })),+ ...Array.from({ length: 3 }, (_, i) => ({ key: `b${i}`, partition: 1 })),+ ])+ await waitFor(() => ledger.filter((e) => e.consumerId === 'A').length >= wave1.length, 8_000)++ consumerB = makeConsumer(groupId, topic, record('B'), {+ autoOffsetStore: false,+ rdKafkaOverrides: { 'max.poll.interval.ms': rebalanceTimeoutMs },+ })++ // The fenced member is kicked entirely, so B takes over BOTH partitions and+ // (with nothing committed) redelivers the first wave while A's flush is still+ // in progress: a slow flush delays the rebalance only up to the rebalance+ // timeout, never indefinitely.+ await waitFor(+ () =>+ wave1.every((r) =>+ ledger.some(+ (e) => e.consumerId === 'B' && e.partition === r.partition && e.offset === r.offset+ )+ ),+ rebalanceTimeoutMs + 10_000+ )+ expect(hook.completedAt).toBe(0)+ for (const partition of [0, 1]) {+ expect(await fetchCommittedOffset(groupId, topic, partition)).toBeNull()+ }++ // The slow consumer must recover rather than wedge: once the flush finishes,+ // newly produced messages are still consumed.+ await waitFor(() => hook.completedAt > 0, flushDurationMs + 10_000)+ const wave2 = await produceTracked(producer, topic, [+ { key: 'a-post', partition: 0 },+ { key: 'b-post', partition: 1 },+ ])+ await waitFor(() => wave2.every((r) => ledger.some((e) => e.value === r.value)), 20_000)++ // The fenced flush's late offset store never becomes a group commit: nothing in+ // this test stores offsets successfully, so the group offsets must still be unset.+ for (const partition of [0, 1]) {+ expect(await fetchCommittedOffset(groupId, topic, partition)).toBeNull()+ }+ } finally {+ await consumerA.disconnect()+ await consumerB?.disconnect()+ await deleteTopic(topic)+ }+ })++ it('a flushed batch then a batch in flight at revoke: commits advance from the flushed mark to the revoke mark, never backwards', async () => {+ const topic = `v2_int_reb_twocycle_${randomUUID()}`+ const groupId = `v2-int-reb-twocycle-${randomUUID()}`+ await createTopic(topic, 2)++ const ledger: LedgerEntry[] = []+ // Replay-style offset manager: track next-to-process per partition (monotonic), store+ // everything tracked on flush, clear so the next cycle starts fresh.+ const tracked = new Map<number, number>()+ const flushOffsets = (): { partition: number; offset: number }[] => {+ const stored = [...tracked.entries()].map(([partition, offset]) => ({ topic, partition, offset }))+ tracked.clear()+ if (stored.length > 0) {+ consumerA.offsetsStore(stored)+ }+ return stored.map(({ partition, offset }) => ({ partition, offset }))+ }+ const hook: {+ invocations: number+ storedAtRevoke: { partition: number; offset: number }[]+ completedAt: number+ } = {+ invocations: 0,+ storedAtRevoke: [],+ completedAt: 0,+ }++ const record = (consumerId: string, track: boolean) => (messages: Message[]) => {+ for (const m of messages) {+ ledger.push({+ consumerId,+ partition: m.partition,+ offset: m.offset,+ key: m.key?.toString() ?? '',+ value: m.value?.toString() ?? '',+ seenAt: Date.now(),+ })+ if (track) {+ tracked.set(m.partition, Math.max(tracked.get(m.partition) ?? 0, m.offset + 1))+ }+ }+ return Promise.resolve()+ }++ const consumerA = makeConsumer(groupId, topic, record('A', true), {+ autoOffsetStore: false,+ onPartitionsRevoked: () => {+ if (++hook.invocations === 1) {+ hook.storedAtRevoke = flushOffsets()+ hook.completedAt = Date.now()+ }+ return Promise.resolve()+ },+ })+ let consumerB: KafkaConsumerV2 | undefined++ try {+ await waitFor(() => consumerA.assignments().length === 2, 10_000)++ // Cycle 1: consumed, then flushed normally (the periodic size/age flush) — the+ // stored offsets reach the broker via the auto-commit timer.+ const wave1 = await produceTracked(producer, topic, [+ ...Array.from({ length: 3 }, (_, i) => ({ key: `a${i}`, partition: 0 })),+ ...Array.from({ length: 3 }, (_, i) => ({ key: `b${i}`, partition: 1 })),+ ])+ await waitFor(() => ledger.length >= wave1.length, 8_000)+ const flush1 = flushOffsets()+ const mark1 = new Map(flush1.map(({ partition, offset }) => [partition, offset]))+ for (const partition of [0, 1]) {+ await waitForAsync(+ async () => (await fetchCommittedOffset(groupId, topic, partition)) === mark1.get(partition),+ 10_000+ )+ }++ // Cycle 2: in flight at the revoke — produced to partition 0 only, so the flush the+ // revoke hook runs must advance partition 0 and leave partition 1 exactly at its+ // cycle-1 mark (tracked state was cleared by the first flush).+ const wave2 = await produceTracked(+ producer,+ topic,+ Array.from({ length: 3 }, (_, i) => ({ key: `a${3 + i}`, partition: 0 }))+ )+ await waitFor(() => wave2.every((r) => ledger.some((e) => e.value === r.value)), 8_000)+ const mark2 = Math.max(...wave2.map((r) => r.offset)) + 1++ consumerB = makeConsumer(groupId, topic, record('B', false), { autoOffsetStore: false })+ const b = consumerB+ await waitFor(() => hook.completedAt > 0, 15_000)++ // The revoke flush stored exactly the in-flight cycle: partition 0 at its new mark,+ // nothing for partition 1.+ expect(hook.storedAtRevoke).toEqual([{ partition: 0, offset: mark2 }])++ await waitFor(() => consumerA.assignments().length === 1 && b.assignments().length === 1, 15_000)++ // Commits advance, never rewind: partition 0 moves from mark1 to mark2 (the unassign+ // or timer commits the newer store over the earlier cycle-1 commit), partition 1+ // stays exactly at mark1.+ await waitForAsync(async () => (await fetchCommittedOffset(groupId, topic, 0)) === mark2, 15_000)+ expect(await fetchCommittedOffset(groupId, topic, 1)).toBe(mark1.get(1))++ // Resumption is exact on both partitions: a third wave lands contiguously and every+ // message across all three cycles was delivered exactly once — neither flushed cycle+ // is ever reprocessed, regardless of which partition moved.+ const wave3 = await produceTracked(producer, topic, [+ { key: 'a-final', partition: 0 },+ { key: 'b-final', partition: 1 },+ ])+ expect(Math.min(...wave3.filter((r) => r.partition === 0).map((r) => r.offset))).toBe(mark2)+ expect(Math.min(...wave3.filter((r) => r.partition === 1).map((r) => r.offset))).toBe(mark1.get(1))++ const produced = [...wave1, ...wave2, ...wave3]+ await waitFor(() => countByPartitionOffset(ledger).size >= produced.length, 15_000)+ expect(ledger.length).toBe(produced.length)+ const consumedAt = new Map(ledger.map((e) => [`${e.partition}:${e.offset}`, e.value]))+ const producedAt = new Map(produced.map((r) => [`${r.partition}:${r.offset}`, r.value]))+ expect(consumedAt).toEqual(producedAt)+ } finally {+ await consumerA.disconnect()+ await consumerB?.disconnect()+ await deleteTopic(topic)+ }+ })++ // The flush-on-stop contract the session replay consumer's shutdown relies on:+ // stopConsuming() → final flush stores offsets → disconnect() commits them leaving the+ // group. The batch in flight when stopConsuming is called must settle before it resolves,+ // and nothing may be consumed after it — otherwise the final flush races live intake.+ it('shutdown flush: stopConsuming drains in-flight work and halts intake, offsets stored before disconnect commit exactly', async () => {+ const topic = `v2_int_reb_stop_${randomUUID()}`+ const groupId = `v2-int-reb-stop-${randomUUID()}`+ await createTopic(topic, 2)++ const ledger: LedgerEntry[] = []+ // Replay-style offset manager: track next-to-process per partition; the shutdown+ // flush stores everything tracked between stopConsuming and disconnect.+ const tracked = new Map<number, number>()+ // Once armed, batches don't settle until the test releases them — keeping a batch+ // in flight across the stopConsuming call.+ let gateArmed = false+ let releaseGate: () => void = () => {}+ const gate = new Promise<void>((resolve) => {+ releaseGate = resolve+ })++ const record = (consumerId: string, track: boolean) => (messages: Message[]) => {+ for (const m of messages) {+ ledger.push({+ consumerId,+ partition: m.partition,+ offset: m.offset,+ key: m.key?.toString() ?? '',+ value: m.value?.toString() ?? '',+ seenAt: Date.now(),+ })+ if (track) {+ tracked.set(m.partition, Math.max(tracked.get(m.partition) ?? 0, m.offset + 1))+ }+ }+ }++ const consumerA = makeConsumer(+ groupId,+ topic,+ (messages) => {+ record('A', true)(messages)+ return Promise.resolve(gateArmed ? { backgroundTask: gate } : {})+ },+ { autoOffsetStore: false }+ )+ let consumerB: KafkaConsumerV2 | undefined++ try {+ await waitFor(() => consumerA.assignments().length === 2, 10_000)++ const wave1 = await produceTracked(producer, topic, [+ ...Array.from({ length: 3 }, (_, i) => ({ key: `a${i}`, partition: 0 })),+ ...Array.from({ length: 3 }, (_, i) => ({ key: `b${i}`, partition: 1 })),+ ])+ await waitFor(() => ledger.length >= wave1.length, 8_000)++ // One gated message: consumed, but its settle chain hangs on the gate, so its+ // batch is still in flight when stopConsuming is called.+ gateArmed = true+ const gated = await produceTracked(producer, topic, [{ key: 'gated-p0', partition: 0 }])+ await waitFor(() => ledger.some((e) => e.value === gated[0].value), 8_000)++ // stopConsuming must not resolve while the in-flight batch is pending — the+ // drain guarantee the shutdown flush depends on.+ let stopSettled = false+ const stopPromise = consumerA.stopConsuming().then(() => {+ stopSettled = true+ })+ await delay(1_500)+ expect(stopSettled).toBe(false)+ releaseGate()+ await stopPromise++ // Intake is halted for good: messages produced after stopConsuming are never+ // consumed by A, even though it is still connected and owns the partitions.+ const wave2 = await produceTracked(producer, topic, [+ ...Array.from({ length: 3 }, (_, i) => ({ key: `a${4 + i}`, partition: 0 })),+ ...Array.from({ length: 3 }, (_, i) => ({ key: `b${3 + i}`, partition: 1 })),+ ])+ await delay(2_000)+ expect(ledger.filter((e) => wave2.some((r) => r.value === e.value))).toEqual([])++ // The shutdown flush window: the store must succeed (the partitions are still+ // owned), and disconnect commits it as the member leaves the group.+ consumerA.offsetsStore(+ [...tracked.entries()].map(([partition, offset]) => ({ topic, partition, offset }))+ )+ await consumerA.disconnect()++ const expectedCommit = new Map(tracked)+ for (const partition of [0, 1]) {+ await waitForAsync(+ async () =>+ (await fetchCommittedOffset(groupId, topic, partition)) === expectedCommit.get(partition),+ 10_000+ )+ }++ // A restart resumes exactly after the shutdown flush: the new consumer sees+ // wave2 only — nothing the flush covered is redelivered — each message exactly+ // once at the offset its delivery report announced.+ consumerB = makeConsumer(groupId, topic, (msgs) => Promise.resolve(record('B', false)(msgs)), {+ autoOffsetStore: false,+ })+ await waitFor(+ () => wave2.every((r) => ledger.some((e) => e.consumerId === 'B' && e.value === r.value)),+ 15_000+ )+ const bEntries = ledger.filter((e) => e.consumerId === 'B')+ expect(bEntries).toHaveLength(wave2.length)+ expect(new Map(bEntries.map((e) => [`${e.partition}:${e.offset}`, e.value]))).toEqual(+ new Map(wave2.map((r) => [`${r.partition}:${r.offset}`, r.value]))+ )+ } finally {+ await consumerA.disconnect()+ await consumerB?.disconnect()+ await deleteTopic(topic)+ }+ })+ })+})diff --git a/nodejs/src/common/kafka/consumer/consumer-v2.test.ts b/nodejs/src/common/kafka/consumer/consumer-v2.test.tsindex df1bd9e11f5a..9e3753941428 100644--- a/nodejs/src/common/kafka/consumer/consumer-v2.test.ts+++ b/nodejs/src/common/kafka/consumer/consumer-v2.test.ts@@ -131,8 +131,12 @@ describe('KafkaConsumerV2', () => {})/** Drive the consumer through ASSIGN so it transitions to CONSUMING. */- const startConsuming = async (eachBatch: jest.Mock, partitions = [{ topic: 'test-topic', partition: 0 }]) => {- await consumer.connect(eachBatch)+ const startConsuming = async (+ eachBatch: jest.Mock,+ partitions = [{ topic: 'test-topic', partition: 0 }],+ onPartitionsRevoked?: (assignments: { topic: string; partition: number }[]) => Promise<void>+ ) => {+ await consumer.connect(eachBatch, onPartitionsRevoked)registeredRebalanceCb!({ code: CODES.ERRORS.ERR__ASSIGN_PARTITIONS } as any, partitions)// The loop is currently inside the IDLE keepalive consume(1, cb). Release it with// an empty batch so the loop processes ASSIGN and arms a fresh consume() in CONSUMING.@@ -385,6 +389,47 @@ describe('KafkaConsumerV2', () => {expect(mockRdKafka.incrementalUnassign).toHaveBeenCalled()})+ it('Revoke hook timeout: a hook outliving drainTimeoutMs is abandoned and unassign proceeds', async () => {+ ;(consumer as any).drainTimeoutMs = 50+ const hookGate = triggerablePromise<void>()+ const hook = jest.fn(() => hookGate.promise)+ const eachBatch = jest.fn(() => Promise.resolve({}))+ await startConsuming(eachBatch, [{ topic: 'test-topic', partition: 0 }], hook)++ fireRevoke()+ await delay(20)+ // Within budget: the rebalance waits for the hook (flush-on-revoke).+ expect(hook).toHaveBeenCalled()+ expect(mockRdKafka.incrementalUnassign).not.toHaveBeenCalled()++ await delay(100)+ // Budget exceeded: the partitions are given up without waiting for the hook.+ expect(mockRdKafka.incrementalUnassign).toHaveBeenCalledWith([{ topic: 'test-topic', partition: 0 }])+ hookGate.resolve()+ })++ it('Revoke budget is total: a stuck drain leaves no extra budget for the hook', async () => {+ ;(consumer as any).drainTimeoutMs = 150+ ;(consumer as any).maxBackgroundTasks = 5+ const hookGate = triggerablePromise<void>()+ const hook = jest.fn(() => hookGate.promise)+ const eachBatch = jest.fn(() => Promise.resolve({}))+ await startConsuming(eachBatch, [{ topic: 'test-topic', partition: 0 }], hook)++ // A never-settling task forces the drain to spend the entire budget.+ const stuck = triggerablePromise()+ await dispatchBatch(eachBatch, [createMessage({ offset: 1, partition: 0 })], stuck.promise)++ fireRevoke()+ // The hook shares the drain's budget rather than getting its own: with the budget+ // exhausted, it is abandoned immediately and the total hold stays ~one budget, not two.+ await delay(220)+ expect(hook).toHaveBeenCalled()+ expect(mockRdKafka.incrementalUnassign).toHaveBeenCalled()+ hookGate.resolve()+ stuck.resolve()+ })+it('ASSIGN after REVOKE: state transitions back to CONSUMING and resumes fetching', async () => {const eachBatch = jest.fn(() => Promise.resolve({}))await startConsuming(eachBatch)diff --git a/nodejs/src/common/kafka/consumer/consumer-v2.ts b/nodejs/src/common/kafka/consumer/consumer-v2.tsindex 1c93a5bbd630..c803e8565dc8 100644--- a/nodejs/src/common/kafka/consumer/consumer-v2.ts+++ b/nodejs/src/common/kafka/consumer/consumer-v2.ts@@ -75,7 +75,9 @@ type TaskEntry = {* Single-coroutine Kafka consumer. The loop is the only mutator; the rebalance callback* just enqueues events. On REVOKE the loop synchronously drains in-flight settle promises* (post-storeOffsets, not raw user tasks), bumps `generation` so any laggard task skips- * its now-invalid storeOffsets, then calls incrementalUnassign.+ * its now-invalid storeOffsets, runs the optional onPartitionsRevoked hook while the+ * partitions are still assigned (so a flush there can store offsets that get committed+ * on the unassign), then calls incrementalUnassign.*/export class KafkaConsumerV2 {private rdKafkaConsumer: RdKafkaConsumer@@ -94,6 +96,13 @@ export class KafkaConsumerV2 {// makes the loop exit on the next tick so the pod replays from the last good commit.private fatalError: unknown | undefined+ // Optional async hook invoked with the partitions being revoked, after the in-flight+ // drain and while the partitions are still assigned, before the unassign. The drain and+ // the hook share one budget (drainTimeoutMs): the hook gets whatever the drain left, and+ // a hook outliving it is abandoned so the rebalance proceeds. Not invoked for the final+ // revoke during disconnect — callers flush explicitly before disconnecting.+ private onPartitionsRevoked?: (assignments: Assignment[]) => Promise<void>+// Tunables (resolved at construction)private fetchBatchSize: numberprivate batchTimeoutMs: number@@ -197,7 +206,11 @@ export class KafkaConsumerV2 {this.rdKafkaConsumer.offsetsStore(offsets)}- public async connect(eachBatch: EachBatch): Promise<void> {+ public async connect(+ eachBatch: EachBatch,+ onPartitionsRevoked?: (assignments: Assignment[]) => Promise<void>+ ): Promise<void> {+ this.onPartitionsRevoked = onPartitionsRevokedtry {await promisifyCallback<Metadata>((cb) => this.rdKafkaConsumer.connect({}, cb))logger.info('📝', 'kafka_consumer_v2_connected', { groupId: this.config.groupId, topic: this.config.topic })@@ -224,10 +237,13 @@ export class KafkaConsumerV2 {})}- public async disconnect(): Promise<void> {- if (!this.running) {- return- }+ /**+ * Stop the consume loop and drain in-flight batches without leaving the group. After this+ * resolves, eachBatch will never be called again. Callers that buffer work across batches+ * flush and store offsets between this and disconnect(), which then commits the stored+ * offsets as it leaves the group — that ordering is what makes the final flush race-free.+ */+ public async stopConsuming(): Promise<void> {// Flip running so the loop exits and so the final REVOKE during disconnect goes// through rebalanceCallback's special-case path.this.running = false@@ -236,6 +252,10 @@ export class KafkaConsumerV2 {logger.error('🔁', 'kafka_consumer_v2_loop_failed_during_disconnect', { error: String(error) })})}+ }++ public async disconnect(): Promise<void> {+ await this.stopConsuming()if (this.rdKafkaConsumer.isConnected()) {await new Promise<void>((res, rej) => this.rdKafkaConsumer.disconnect((e) => (e ? rej(e) : res())))}@@ -421,8 +441,37 @@ export class KafkaConsumerV2 {generation: this.generation,partitions: event.partitions.map((p) => `${p.topic}/${p.partition}`),})+ // One budget for the whole revoke path: the drain spends what it needs and the+ // hook gets the remainder, so CONSUMER_REBALANCE_TIMEOUT_MS bounds the total hold+ // on the rebalance — not each phase separately.+ const revokeDeadline = Date.now() + this.drainTimeoutMsawait this.drainAll('revoke')+ if (this.onPartitionsRevoked) {+ const hookBudgetMs = Math.max(revokeDeadline - Date.now(), 0)+ try {+ // A wedged flush (e.g. a produce stuck until its delivery timeout) must not+ // hold the group's rebalance hostage until max.poll.interval.ms fences the+ // member. On timeout the partitions are given up without the flush's+ // offsets — the new owner replays from the last commit, exactly as with a+ // failed flush.+ const { timedOut } = await raceWithTimeout(this.onPartitionsRevoked(event.partitions), hookBudgetMs)+ if (timedOut) {+ consumerDrainTimeouts.labels(this.config.topic, this.config.groupId, 'revoke_hook').inc()+ logger.error('🔁', 'kafka_consumer_v2_revoke_handler_timeout', {+ hookBudgetMs,+ rebalanceTimeoutMs: this.drainTimeoutMs,+ })+ }+ } catch (error) {+ // A failed flush must not strand the rebalance — give the partitions up+ // anyway. The offsets simply won't have been stored, so the new owner+ // reprocesses from the last commit.+ logger.error('🔁', 'kafka_consumer_v2_revoke_handler_failed', { error: String(error) })+ captureException(error)+ }+ }+try {if (this.rdKafkaConsumer.rebalanceProtocol() === 'COOPERATIVE') {this.rdKafkaConsumer.incrementalUnassign(event.partitions)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.test.tsnew file mode 100644index 000000000000..f418bd7f2644--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.test.ts@@ -0,0 +1,200 @@+import { Message } from 'node-rdkafka'++import { PostgresRouter } from '~/common/utils/db/postgres'+import { SessionReplayPipeline, runSessionReplayPipeline } from '~/ingestion/pipelines/sessionreplay'+import { KeyStore, RecordingEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/types'+import { RedisPool } from '~/types'++import { getDefaultSessionRecordingApiConfig, getDefaultSessionRecordingConfig } from './config'+import { SessionRecordingIngester, SessionRecordingIngesterConfig } from './consumer'+import { BlackholeSessionBatchFileStorage } from './sessions/blackhole-session-batch-writer'++jest.mock('~/common/kafka/consumer/consumer-v2', () => {+ class FakeKafkaConsumerV2 {+ public connect = jest.fn().mockResolvedValue(undefined)+ public stopConsuming = jest.fn().mockResolvedValue(undefined)+ public disconnect = jest.fn().mockResolvedValue(undefined)+ public offsetsStore = jest.fn()+ public assignments = jest.fn().mockReturnValue([])+ public isHealthy = jest.fn()+ }+ return { KafkaConsumerV2: FakeKafkaConsumerV2 }+})++jest.mock('~/ingestion/pipelines/sessionreplay', () => ({+ ...jest.requireActual('~/ingestion/pipelines/sessionreplay'),+ runSessionReplayPipeline: jest.fn(),+}))++function deferred(): { promise: Promise<void>; resolve: () => void } {+ let resolve!: () => void+ const promise = new Promise<void>((r) => (resolve = r))+ return { promise, resolve }+}++/** Flush all pending microtasks (one macrotask hop). */+function flushMicrotasks(): Promise<void> {+ return new Promise((resolve) => setImmediate(resolve))+}++function kafkaMessage(partition: number, offset: number): Message {+ return {+ value: Buffer.from('data'),+ size: 4,+ topic: 'test-session-replay-topic',+ partition,+ offset,+ timestamp: Date.now(),+ }+}++describe('SessionRecordingIngester', () => {+ let ingester: SessionRecordingIngester+ let events: string[]++ const runPipelineMock = jest.mocked(runSessionReplayPipeline)++ const consumeTopic = getDefaultSessionRecordingConfig().INGESTION_SESSION_REPLAY_CONSUMER_CONSUME_TOPIC++ const createIngester = (configOverrides: Partial<SessionRecordingIngesterConfig> = {}): void => {+ const config: SessionRecordingIngesterConfig = {+ ...getDefaultSessionRecordingConfig(),+ ...getDefaultSessionRecordingApiConfig(),+ INGESTION_OVERFLOW_MODE: 'disabled',+ INGESTION_PIPELINE: 'sessionreplay',+ INGESTION_LANE: 'main',+ // Age/size flushes would interleave with the flush under test; keep them out of+ // reach unless a test opts in via overrides.+ SESSION_RECORDING_MAX_BATCH_AGE_MS: 60 * 60 * 1000,+ SESSION_RECORDING_MAX_BATCH_SIZE_KB: 1024 * 1024,+ ...configOverrides,+ }++ const fakeKeyStore = {+ start: jest.fn().mockResolvedValue(undefined),+ stop: jest.fn(),+ } as unknown as KeyStore+ const fakeEncryptor = {+ start: jest.fn().mockResolvedValue(undefined),+ } as unknown as RecordingEncryptor++ ingester = new SessionRecordingIngester(+ config,+ {} as jest.Mocked<PostgresRouter>,+ {} as unknown as ConstructorParameters<typeof SessionRecordingIngester>[2],+ {} as unknown as RedisPool,+ {} as unknown as RedisPool,+ {+ fileStorage: new BlackholeSessionBatchFileStorage(),+ keyStore: fakeKeyStore,+ encryptor: fakeEncryptor,+ createPipeline: () => ({}) as unknown as SessionReplayPipeline,+ }+ )++ jest.mocked(ingester.kafkaConsumer).offsetsStore.mockImplementation(() => {+ events.push('offsets_stored')+ })+ jest.mocked(ingester.kafkaConsumer).disconnect.mockImplementation(() => {+ events.push('disconnected')+ return Promise.resolve()+ })+ }++ beforeEach(() => {+ events = []+ runPipelineMock.mockReset()+ createIngester()+ })++ it('stop() stores the in-flight batch offsets only after its side effects settle, before disconnect', async () => {+ const pipelineEntered = deferred()+ const pipelineGate = deferred()++ // Models a poll batch mid-record when stop() arrives: the pipeline holds the batch lock+ // until the gate opens, and only then schedules its side effect (a DLQ/overflow produce+ // that takes one macrotask to become durable) and reports its offsets.+ runPipelineMock.mockImplementation(async (_pipeline, _messages, _recorder, scheduler) => {+ pipelineEntered.resolve()+ await pipelineGate.promise+ void scheduler.schedule(+ new Promise<void>((resolve) =>+ setImmediate(() => {+ events.push('side_effect_settled')+ resolve()+ })+ )+ )+ return new Map([[0, 42]])+ })++ const batchPromise = ingester.handleEachBatch([kafkaMessage(0, 42)])+ await pipelineEntered.promise++ // Model the real consumer contract: stopConsuming resolves only once the in-flight+ // eachBatch has settled. (The drain itself is covered by the consumer-v2 tests.)+ jest.mocked(ingester.kafkaConsumer).stopConsuming.mockImplementation(async () => {+ await batchPromise+ })++ const stopPromise = ingester.stop()+ await flushMicrotasks()++ // The batch finishes: it schedules its side effect and reports offset 42 for partition 0.+ pipelineGate.resolve()++ await batchPromise+ await stopPromise++ // The shutdown contract: the batch's produce must be durable before its offset is stored,+ // and the offset must be stored before disconnect commits it to the broker.+ expect(events).toEqual(['side_effect_settled', 'offsets_stored', 'disconnected'])+ })++ it('flushes on the age trigger: side effects drain before the batch offsets are stored, at exactly highest+1', async () => {+ createIngester({ SESSION_RECORDING_MAX_BATCH_AGE_MS: 0 })++ // The pipeline schedules a side effect (a DLQ/overflow produce that takes one macrotask+ // to become durable) and reports its offsets; the age trigger then flushes immediately.+ runPipelineMock.mockImplementation((_pipeline, _messages, _recorder, scheduler) => {+ void scheduler.schedule(+ new Promise<void>((resolve) =>+ setImmediate(() => {+ events.push('side_effect_settled')+ resolve()+ })+ )+ )+ return Promise.resolve(new Map([[0, 42]]))+ })++ await ingester.handleEachBatch([kafkaMessage(0, 42)])++ // Never commit a message's offset before its produce is durable — and commit at+ // exactly the next-to-process offset.+ expect(events).toEqual(['side_effect_settled', 'offsets_stored'])+ expect(jest.mocked(ingester.kafkaConsumer).offsetsStore).toHaveBeenCalledWith([+ { topic: consumeTopic, partition: 0, offset: 43 },+ ])+ })++ it('start() wires the revoke hook, and the hook flushes the tracked offsets', async () => {+ await ingester.start()+ const connectMock = jest.mocked(ingester.kafkaConsumer).connect+ expect(connectMock).toHaveBeenCalledTimes(1)+ const [eachBatch, onPartitionsRevoked] = connectMock.mock.calls[0]+ expect(onPartitionsRevoked).toBeDefined()++ runPipelineMock.mockImplementation(() => Promise.resolve(new Map([[0, 7]])))+ await eachBatch([kafkaMessage(0, 7)])+ // Age/size are out of reach, so nothing has flushed yet.+ expect(events).toEqual([])++ await onPartitionsRevoked!([{ topic: consumeTopic, partition: 0 }])+ expect(jest.mocked(ingester.kafkaConsumer).offsetsStore).toHaveBeenCalledWith([+ { topic: consumeTopic, partition: 0, offset: 8 },+ ])++ await ingester.stop()+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.tsindex 47715ed679e8..cd52e098447d 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts@@ -1,7 +1,8 @@-import { CODES, Message, TopicPartition, TopicPartitionOffset, features, librdkafkaVersion } from 'node-rdkafka'+import { Message, TopicPartition, TopicPartitionOffset, features, librdkafkaVersion } from 'node-rdkafka'+import pLimit from 'p-limit'import { buildIntegerMatcher } from '~/common/config/config'-import { KafkaConsumer } from '~/common/kafka/consumer/consumer-v1'+import { KafkaConsumerV2 } from '~/common/kafka/consumer/consumer-v2'import { DlqOutput, IngestionWarningsOutput, LogEntriesOutput, OverflowOutput, TophogOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { instrumentFn } from '~/common/tracing/tracing-utils'@@ -11,7 +12,6 @@ import {EventIngestionRestrictionManagerComponent,} from '~/common/utils/event-ingestion-restrictions'import { logger } from '~/common/utils/logger'-import { captureException } from '~/common/utils/posthog'import { PromiseScheduler } from '~/common/utils/promise-scheduler'import { IngestionConsumerConfig } from '~/ingestion/config'import { TopHog } from '~/ingestion/framework/tophog/tophog'@@ -43,6 +43,7 @@ import { BlackholeSessionBatchFileStorage } from './sessions/blackhole-session-bimport { RetentionAwareStorage } from './sessions/retention-aware-batch-writer'import { SessionBatchFileStorage } from './sessions/session-batch-file-storage'import { SessionBatchManager } from './sessions/session-batch-manager'+import { SessionBatchRecorder } from './sessions/session-batch-recorder'import { SessionConsoleLogStore } from './sessions/session-console-log-store'import { SessionFilter } from './sessions/session-filter'import { SessionTracker } from './sessions/session-tracker'@@ -80,15 +81,24 @@ export interface SessionRecordingIngesterCollaborators {}export class SessionRecordingIngester {- kafkaConsumer: KafkaConsumer+ kafkaConsumer: KafkaConsumerV2topic: stringconsumerGroupId: string- totalNumPartitions = 0isStopping = falseprivate isDebugLoggingEnabled: ValueMatcher<number>private readonly promiseScheduler: PromiseSchedulerprivate readonly sessionBatchManager: SessionBatchManager+ /** The accumulator for the current flush cycle. Owned here, minted and flushed via the manager. */+ private currentBatch: SessionBatchRecorder+ /** When the current accumulation cycle started (last flush, or startup), for the age flush trigger. */+ private lastFlushTime: number+ /**+ * Serializes access to {@link currentBatch}: recording a poll batch, flushing on size/age, and+ * flushing on partition revoke all run one at a time, so a revoke can't flush a batch a concurrent+ * poll is still recording into. (The accumulating pipeline will own this serialization later.)+ */+ private readonly batchLock = pLimit(1)private readonly redisPool: RedisPoolprivate readonly restrictionRedisPool: RedisPoolprivate readonly teamService: TeamService@@ -136,7 +146,10 @@ export class SessionRecordingIngester {this.promiseScheduler = new PromiseScheduler()- this.kafkaConsumer = new KafkaConsumer({+ // The v2 consumer defers the unassign on revoke until in-flight work is drained and the+ // revoke hook has run, so a revoke can flush the current batch (persisting sessions and+ // storing offsets) before the revoked partitions are given up.+ this.kafkaConsumer = new KafkaConsumerV2({topic: this.topic,groupId: this.consumerGroupId,callEachBatchWhenEmpty: true,@@ -227,6 +240,9 @@ export class SessionRecordingIngester {featureStore,encryptor: this.encryptor,})++ this.currentBatch = this.sessionBatchManager.createBatch()+ this.lastFlushTime = Date.now()}public get service(): PluginServerService {@@ -238,8 +254,6 @@ export class SessionRecordingIngester {}public async handleEachBatch(messages: Message[]): Promise<void> {- this.kafkaConsumer.heartbeat()-if (messages.length > 0) {logger.info('🔁', `blob_ingester_consumer_v2 - handling batch`, {size: messages.length,@@ -269,26 +283,40 @@ export class SessionRecordingIngester {// Run messages through the pipeline (handles restrictions, parsing, team filtering, and recording)// and track the highest offset reached per partition — the single place Kafka progress is tracked.+ // Recording holds the batch lock so a concurrent revoke can't flush the batch mid-record.const offsets = await instrumentFn(`recordingingesterv2.handleEachBatch.runPipeline`, async () =>- runSessionReplayPipeline(this.sessionReplayPipeline, messages, this.promiseScheduler)+ this.batchLock(() =>+ runSessionReplayPipeline(this.sessionReplayPipeline, messages, this.currentBatch, this.promiseScheduler)+ ))this.sessionBatchManager.trackProcessedOffsets(offsets)- this.kafkaConsumer.heartbeat()-- if (this.sessionBatchManager.shouldFlush()) {- // The pipeline schedules its side effects (DLQ and overflow produces) fire-and-forget on- // the promise scheduler. Drain them before flushing so we never commit a message's offset- // before its produce is durable — otherwise a crash in that window would lose it.- await instrumentFn(`recordingingesterv2.handleEachBatch.flush.awaitSideEffects`, async () => {- await this.promiseScheduler.waitForAllSettled()- })- await instrumentFn(`recordingingesterv2.handleEachBatch.flush`, async () =>- this.sessionBatchManager.flush()- )+ if (this.sessionBatchManager.shouldFlush(this.currentBatch, this.lastFlushTime)) {+ await this.flushCurrentBatch()}}+ /**+ * Flush the current accumulator (persisting it and committing its tracked offsets) and start a new+ * cycle. Serialized by the batch lock so it can't run while a batch is being recorded or another+ * flush (e.g. a partition revoke) is in progress.+ */+ private async flushCurrentBatch(): Promise<void> {+ // The pipeline schedules its side effects (DLQ and overflow produces) fire-and-forget on the+ // promise scheduler. Drain them before flushing so we never commit a message's offset before its+ // produce is durable — otherwise a crash in that window would lose it. Drain outside the lock so a+ // scheduled revoke waiting on the lock can't deadlock this drain.+ await instrumentFn(`recordingingesterv2.handleEachBatch.flush.awaitSideEffects`, async () => {+ await this.promiseScheduler.waitForAllSettled()+ })+ await this.batchLock(async () => {+ logger.info('🔁', 'blob_ingester_consumer_v2 - flushing batch', { batchSize: this.currentBatch.size })+ await instrumentFn(`recordingingesterv2.handleEachBatch.flush`, async () => this.currentBatch.flush())+ this.currentBatch = this.sessionBatchManager.createBatch()+ this.lastFlushTime = Date.now()+ })+ }+public async start(): Promise<void> {logger.info('🔁', 'blob_ingester_consumer_v2 - starting session recordings blob consumer', {librdKafkaVersion: librdkafkaVersion,@@ -313,46 +341,18 @@ export class SessionRecordingIngester {keyStore: this.keyStore,sessionKeyResolutionMaxConcurrency: this.config.SESSION_RECORDING_KEY_RESOLUTION_MAX_CONCURRENCY,topHog: this.topHog,- sessionBatchManager: this.sessionBatchManager,isDebugLoggingEnabled: this.isDebugLoggingEnabled,})// Check that the storage backend is healthy before starting the consumer// This is especially important in local dev with minioawait this.fileStorage.checkHealth()- await this.kafkaConsumer.connect((messages) => this.handleEachBatch(messages))-- this.totalNumPartitions = (await this.kafkaConsumer.getPartitionsForTopic(this.topic)).length-- this.kafkaConsumer.on('rebalance', async (err, topicPartitions) => {- logger.info('🔁', 'blob_ingester_consumer_v2 - rebalancing', { err, topicPartitions })- /**- * see https://github.com/Blizzard/node-rdkafka#rebalancing- *- * This event is received when the consumer group starts _or_ finishes rebalancing.- *- * NB if the partition assignment strategy changes then this code may need to change too.- * e.g. round-robin and cooperative strategies will assign partitions differently- */-- if (err.code === CODES.ERRORS.ERR__ASSIGN_PARTITIONS) {- return- }-- if (err.code === CODES.ERRORS.ERR__REVOKE_PARTITIONS) {- return this.promiseScheduler.schedule(this.onRevokePartitions(topicPartitions))- }-- // We had a "real" error- logger.error('🔥', 'blob_ingester_consumer_v2 - rebalancing error', { err })- captureException(err)- // TODO: immediately die? or just keep going?- })-- // nothing happens here unless we configure SESSION_RECORDING_KAFKA_CONSUMPTION_STATISTICS_EVENT_INTERVAL_MS- this.kafkaConsumer.on('event.stats', (stats) => {- logger.info('🪵', 'blob_ingester_consumer_v2 - kafka stats', { stats })- })+ // The revoke hook runs inside the rebalance callback, before the partitions are unassigned, so+ // the flush it triggers stores offsets that librdkafka commits as it gives the partitions up.+ await this.kafkaConsumer.connect(+ (messages) => this.handleEachBatch(messages),+ (revokedPartitions) => this.onRevokePartitions(revokedPartitions)+ )// Start periodic flushing of TopHog metricsthis.topHog.start()@@ -362,14 +362,18 @@ export class SessionRecordingIngester {logger.info('🔁', 'blob_ingester_consumer_v2 - stopping')this.isStopping = true+ // Stop the consume loop and drain in-flight batches first, so the final flush below can't+ // race a poll batch that is still recording (and scheduling side effects) concurrently.+ await this.kafkaConsumer.stopConsuming()+// Stop TopHog and flush final metricsawait this.topHog.stop()- const assignedPartitions = this.assignedTopicPartitions+ // Persist whatever is buffered and store its offsets while we still own the partitions;+ // disconnect commits them as it leaves the group.+ await this.flushCurrentBatch()await this.kafkaConsumer.disconnect()- void this.promiseScheduler.schedule(this.onRevokePartitions(assignedPartitions))-const promiseResults = await this.promiseScheduler.waitForAllSettled()this.keyStore.stop()@@ -397,8 +401,10 @@ export class SessionRecordingIngester {private onRevokePartitions(topicPartitions: TopicPartition[]): Promise<void> {/**- * The revoke_partitions indicates that the consumer group has had partitions revoked.- * As a result, we need to drop all sessions currently managed for the revoked partitions+ * The revoke_partitions event indicates that the consumer group has had partitions revoked.+ * Rather than reaching into the live batch to discard the revoked partitions' sessions, we flush+ * whatever is buffered (persisting it and committing its offsets), so the new owner resumes from+ * after the work we already persisted instead of reprocessing it.*/const revokedPartitions = topicPartitions.map((x) => x.partition)@@ -407,8 +413,7 @@ export class SessionRecordingIngester {}SessionRecordingIngesterMetrics.resetSessionsHandled()- this.sessionBatchManager.discardPartitions(revokedPartitions)- return Promise.resolve()+ return this.flushCurrentBatch()}private async commitOffsets(offsets: TopicPartitionOffset[]): Promise<void> {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/kafka/offset-manager.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/kafka/offset-manager.test.tsindex ef4a83725f83..e7893d8ff0f0 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/kafka/offset-manager.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/kafka/offset-manager.test.ts@@ -57,53 +57,6 @@ describe('KafkaOffsetManager', () => {})describe('partition handling', () => {- it('should not commit offsets for discarded partitions', async () => {- // Record messages for two partitions- offsetManager.trackOffset({ partition: 1, offset: 100 })- offsetManager.trackOffset({ partition: 2, offset: 200 })-- // Discard partition 1- offsetManager.discardPartition(1)-- await offsetManager.commit()-- // Should only commit offset for partition 2- expect(mockCommitOffsets).toHaveBeenCalledWith([- {- topic: 'test_topic',- partition: 2,- offset: 201,- },- ])- })-- it('should handle discarding already committed partitions', async () => {- // Record and commit a message- offsetManager.trackOffset({ partition: 1, offset: 100 })- await offsetManager.commit()-- // Discard the partition after commit- offsetManager.discardPartition(1)-- // Record new message for same partition- offsetManager.trackOffset({ partition: 1, offset: 101 })- await offsetManager.commit()-- expect(mockCommitOffsets).toHaveBeenCalledTimes(2)- expect(mockCommitOffsets).toHaveBeenLastCalledWith([- {- topic: 'test_topic',- partition: 1,- offset: 102,- },- ])- })-- it('should handle discarding non-existent partitions', () => {- offsetManager.discardPartition(999)- // No error should be thrown- })-it('should maintain highest offset when recording multiple messages', async () => {// Record messages in non-sequential orderoffsetManager.trackOffset({ partition: 1, offset: 100 })diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/kafka/offset-manager.ts b/nodejs/src/ingestion/pipelines/sessionreplay/kafka/offset-manager.tsindex ced11ec4a97a..0cfa2c681bf0 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/kafka/offset-manager.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/kafka/offset-manager.ts@@ -24,10 +24,6 @@ export class KafkaOffsetManager {}}- public discardPartition(partition: number): void {- this.partitionOffsets.delete(partition)- }-public async commit(): Promise<void> {const topicPartitionOffsets: TopicPartitionOffset[] = []diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.tsindex f7b9f529106e..ee3e9af9a00b 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,7 +12,6 @@ import { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'import { ok } from '~/ingestion/framework/results'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'@@ -60,7 +59,7 @@ function createMockTopHog(): TopHogRegistry {describe('ml-mirror-pipeline', () => {let recordMock: jest.Mock- let mockSessionBatchManager: jest.Mocked<SessionBatchManager>+ let mockBatchRecorder: jest.Mocked<SessionBatchRecorder>let mockTeamService: TeamServicelet topHog: TopHogRegistrylet promiseScheduler: PromiseScheduler@@ -109,16 +108,10 @@ describe('ml-mirror-pipeline', () => {outputs = createMockIngestionOutputs()recordMock = jest.fn().mockResolvedValue(undefined)- const recorder = {+ mockBatchRecorder = {record: recordMock,getRetention: jest.fn().mockReturnValue(undefined),} as unknown as jest.Mocked<SessionBatchRecorder>- mockSessionBatchManager = {- getCurrentBatch: jest.fn().mockReturnValue(recorder),- shouldFlush: jest.fn().mockReturnValue(false),- flush: jest.fn().mockResolvedValue(undefined),- discardPartitions: jest.fn(),- } as unknown as jest.Mocked<SessionBatchManager>topHog = createMockTopHog()promiseScheduler = new PromiseScheduler()@@ -148,7 +141,6 @@ describe('ml-mirror-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled: () => false,})}@@ -250,7 +242,7 @@ describe('ml-mirror-pipeline', () => {getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),} as unknown as TeamService- await runSessionReplayPipeline(buildPipeline(), [message('sess-1')], promiseScheduler)+ await runSessionReplayPipeline(buildPipeline(), [message('sess-1')], mockBatchRecorder, promiseScheduler)expect(recordMock).toHaveBeenCalledTimes(1)const [windowId, event] = recordedEvents()[0]@@ -265,7 +257,7 @@ describe('ml-mirror-pipeline', () => {getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),} as unknown as TeamService- await runSessionReplayPipeline(buildPipeline(), [message('sess-2')], promiseScheduler)+ await runSessionReplayPipeline(buildPipeline(), [message('sess-2')], mockBatchRecorder, promiseScheduler)expect(recordMock).not.toHaveBeenCalled()})@@ -276,7 +268,12 @@ describe('ml-mirror-pipeline', () => {getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),} as unknown as TeamService- await runSessionReplayPipeline(buildPipeline(), [fullSnapshotMessage('sess-3')], promiseScheduler)+ await runSessionReplayPipeline(+ buildPipeline(),+ [fullSnapshotMessage('sess-3')],+ mockBatchRecorder,+ promiseScheduler+ )expect(recordMock).toHaveBeenCalledTimes(1)const node = recordedEvents()[0][1].data.node.childNodes[0]diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.tsindex 62da407f6e64..19efc89944c9 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@@ -15,10 +15,8 @@ import { createAiTrainingOptInFilterStep } from '~/ingestion/pipelines/sessionreimport { createParseAndAnonymizeMessageStep } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'import { MessageContext } from '~/ingestion/pipelines/sessionreplay/pipeline-types'import { createRecordSessionEventStep } from '~/ingestion/pipelines/sessionreplay/record-session-event-step'-import { SessionBatchContext } from '~/ingestion/pipelines/sessionreplay/session-batch-context'import { createMarkSeenStep } from '~/ingestion/pipelines/sessionreplay/session-batch-mark-seen-step'import { createResolveRetentionStep } from '~/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step'-import { createAttachSessionBatchStep } from '~/ingestion/pipelines/sessionreplay/session-batch-step'import { createTrackAndGateStep } from '~/ingestion/pipelines/sessionreplay/session-batch-track-and-gate-step'import { createResolveKeyStep } from '~/ingestion/pipelines/sessionreplay/session-resolve-key-step'import { createTeamFilterStep } from '~/ingestion/pipelines/sessionreplay/team-filter-step'@@ -37,7 +35,6 @@ export function createMlMirrorReplayPipeline(config: SessionReplayPipelineConfigkeyStore,sessionKeyResolutionMaxConcurrency,topHog,- sessionBatchManager,isDebugLoggingEnabled,} = config@@ -48,11 +45,14 @@ export function createMlMirrorReplayPipeline(config: SessionReplayPipelineConfigSessionReplayPipelineInput,SessionReplayPipelineOutput,MessageContext,- SessionBatchContext,+ Record<never, object>,MessageContext,OverflowOutput>(- (beforeBatch) => beforeBatch.pipe(createAttachSessionBatchStep(sessionBatchManager)),+ (beforeBatch) =>+ beforeBatch.pipe(function passThroughBeforeBatch(input) {+ return Promise.resolve(ok(input))+ }),(batch) =>batch.messageAware((b) =>diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-context.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-context.tsindex 0b23121cb0e3..76f707a1f50a 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-context.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-context.ts@@ -1,12 +1,9 @@import { SessionBatchRecorder } from './sessions/session-batch-recorder'/**- * Batch context attached to every element of a pipeline batch: the recorder the record step folds- * events into. Tagged on by the pipeline's beforeBatch hook, so steps read the recorder from their- * element instead of holding a reference to shared batch state.- *- * This is a pipeline-level concern (the unit the pipeline threads through its steps), not a recorder- * concern — the recorder is just what it happens to carry.+ * The recorder a session replay message folds into, carried on every pipeline input element. The layer+ * above the pipeline (the consumer, later the accumulating pipeline) owns the recorder and stamps it on+ * the messages it feeds, so steps read it from their element instead of reaching into shared batch state.*/export interface SessionBatchContext {sessionBatchRecorder: SessionBatchRecorderdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-step.tsdeleted file mode 100644index 44724629532f..000000000000--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-step.ts+++ /dev/null@@ -1,25 +0,0 @@-import { BeforeBatchInput, BeforeBatchOutput } from '~/ingestion/framework/batching-pipeline'-import { ok } from '~/ingestion/framework/results'-import { ProcessingStep } from '~/ingestion/framework/steps'--import { SessionBatchContext } from './session-batch-context'-import { SessionBatchManager } from './sessions/session-batch-manager'--/**- * beforeBatch hook for the session replay pipeline: tags the manager's current recorder onto the- * batch context, which the batching pipeline merges into every element ({@link SessionBatchContext}).- * Steps that fold into or read from the batch take the recorder off their element, so they stay- * decoupled from the manager and its current-batch state.- */-export function createAttachSessionBatchStep<TInput, CInput>(- sessionBatchManager: SessionBatchManager-): ProcessingStep<BeforeBatchInput<TInput, CInput>, BeforeBatchOutput<TInput, CInput, SessionBatchContext>> {- return function attachSessionBatchStep(input) {- return Promise.resolve(- ok({- elements: input.elements,- batchContext: { ...input.batchContext, sessionBatchRecorder: sessionBatchManager.getCurrentBatch() },- })- )- }-}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-rate-limiter.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-rate-limiter.test.tsindex 9f9e27de373e..b5870db289c8 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-rate-limiter.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-rate-limiter.test.ts@@ -49,7 +49,6 @@ 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'@@ -144,17 +143,11 @@ class FakePipeline {}}-function createMockSessionBatchManager(): jest.Mocked<SessionBatchManager> {- const mockBatchRecorder = {+function createMockBatchRecorder(): jest.Mocked<SessionBatchRecorder> {+ return {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@@ -177,7 +170,7 @@ describe('session-replay-pipeline rate limiter failure modes', () => {let sessionTracker: SessionTrackerlet sessionFilter: SessionFilterlet keyStore: jest.Mocked<KeyStore>- let sessionBatchManager: jest.Mocked<SessionBatchManager>+ let mockBatchRecorder: jest.Mocked<SessionBatchRecorder>let outputs: jest.Mocked<IngestionOutputs<typeof DLQ_OUTPUT | typeof OVERFLOW_OUTPUT | typeof INGESTION_WARNINGS_OUTPUT>>@@ -233,7 +226,6 @@ describe('session-replay-pipeline rate limiter failure modes', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog: createMockTopHog(),- sessionBatchManager,isDebugLoggingEnabled: () => false,})}@@ -265,7 +257,12 @@ describe('session-replay-pipeline rate limiter failure modes', () => {}async function runBatch(sessionId: string, offset: number): Promise<void> {- await runSessionReplayPipeline(buildPipeline(), [createMessage(sessionId, offset)], new PromiseScheduler())+ await runSessionReplayPipeline(+ buildPipeline(),+ [createMessage(sessionId, offset)],+ mockBatchRecorder,+ new PromiseScheduler()+ )}// Assert a one-shot fault armed with failNext() actually fired — guards against a silently-inert fault@@ -316,7 +313,7 @@ describe('session-replay-pipeline rate limiter failure modes', () => {deleteKey: jest.fn(),stop: jest.fn(),} as unknown as jest.Mocked<KeyStore>- sessionBatchManager = createMockSessionBatchManager()+ mockBatchRecorder = createMockBatchRecorder()outputs = createMockIngestionOutputs()countedSessions = []diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.tsindex 879c5ae30900..6ce71eb07b78 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts@@ -9,7 +9,6 @@ import { PromiseScheduler } from '~/common/utils/promise-scheduler'import { createApplyEventRestrictionsStep, createParseHeadersStep } from '~/ingestion/common/steps/event-preprocessing'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'@@ -30,18 +29,11 @@ jest.mock('~/ingestion/common/steps/event-preprocessing', () => ({createApplyEventRestrictionsStep: jest.fn(),}))-function createMockSessionBatchManager(): jest.Mocked<SessionBatchManager> {- const mockBatchRecorder = {+function createMockBatchRecorder(): jest.Mocked<SessionBatchRecorder> {+ return {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@@ -87,7 +79,7 @@ function createMockTopHog(): MockTopHogRegistry {describe('session-replay-pipeline', () => {let mockRestrictionManager: EventIngestionRestrictionManagerlet mockTeamService: TeamService- let mockSessionBatchManager: jest.Mocked<SessionBatchManager>+ let mockBatchRecorder: jest.Mocked<SessionBatchRecorder>let promiseScheduler: PromiseSchedulerlet topHog: MockTopHogRegistrylet outputs: jest.Mocked<@@ -190,7 +182,7 @@ describe('session-replay-pipeline', () => {getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),} as unknown as TeamService- mockSessionBatchManager = createMockSessionBatchManager()+ mockBatchRecorder = createMockBatchRecorder()topHog = createMockTopHog()promiseScheduler = new PromiseScheduler()@@ -284,9 +276,7 @@ describe('session-replay-pipeline', () => {// The runner now returns the max offset per partition; which messages actually reached// recording is observed through the batch recorder mock.const recordedSessionIds = (): string[] =>- (mockSessionBatchManager.getCurrentBatch().record as jest.Mock).mock.calls.map(- (call) => call[0].message.session_id- )+ (mockBatchRecorder.record as jest.Mock).mock.calls.map((call) => call[0].message.session_id)it('passes through messages when no restrictions apply', async () => {const pipeline = createSessionReplayPipeline({@@ -301,13 +291,12 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})const messages = [createMessage(0, 1, 'session-1'), createMessage(0, 2, 'session-2')]- const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1', 'session-2'])// Highest offset reached on the partition is tracked.@@ -336,7 +325,6 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})@@ -346,7 +334,7 @@ describe('session-replay-pipeline', () => {createMessage(0, 3, 'session-3'),]- const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1', 'session-3'])// The dropped message (offset 2) is not recorded, but its offset is still accounted for —@@ -376,7 +364,6 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})@@ -386,7 +373,7 @@ describe('session-replay-pipeline', () => {createMessage(0, 3, 'session-3'),]- const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1', 'session-2'])// The highest offset on the partition belongs to the dropped message; it must still be@@ -422,7 +409,6 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})@@ -432,7 +418,7 @@ describe('session-replay-pipeline', () => {createMessage(0, 3, 'session-3'),]- const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1', 'session-2'])// The highest offset on the partition belongs to the blocked session; it must still be tracked@@ -496,7 +482,6 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})@@ -507,7 +492,7 @@ describe('session-replay-pipeline', () => {createMessage(1, 5, 'session-4'), // recorded on partition 1 at a higher offset]- const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)expect(recordedSessionIds().sort()).toEqual(['session-1', 'session-2', 'session-4'])expect(offsets).toEqual(@@ -531,7 +516,6 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})@@ -549,7 +533,7 @@ describe('session-replay-pipeline', () => {const messages = [createMessage(0, 1, 'session-1'), invalidMessage, createMessage(0, 3, 'session-3')]- const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1', 'session-3'])// The unparseable message (offset 2) is DLQ'd, but its offset is still accounted for.@@ -569,7 +553,6 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})@@ -587,7 +570,7 @@ describe('session-replay-pipeline', () => {const messages = [invalidMessage]- await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)// Wait for side effects to completeawait promiseScheduler.waitForAll()@@ -623,7 +606,6 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})@@ -633,7 +615,7 @@ describe('session-replay-pipeline', () => {createMessage(0, 3, 'session-3'),]- const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)// Wait for side effects to completeawait promiseScheduler.waitForAll()@@ -659,11 +641,10 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})- const offsets = await runSessionReplayPipeline(pipeline, [], promiseScheduler)+ const offsets = await runSessionReplayPipeline(pipeline, [], mockBatchRecorder, promiseScheduler)expect(offsets.size).toBe(0)})@@ -691,7 +672,6 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})@@ -701,7 +681,7 @@ describe('session-replay-pipeline', () => {messages.push(createMessage(0, i))}- const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)// 100 messages dropped (10, 20, ..., 1000), 900 recordedconst recorded = recordedSessionIds()@@ -739,7 +719,6 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})@@ -748,7 +727,7 @@ describe('session-replay-pipeline', () => {createMessage(0, 2, 'session-2', { token: 'team-token-789' }),]- await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1', 'session-2'])// Verify headers were correctly parsed and passed through@@ -779,7 +758,6 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})@@ -789,7 +767,7 @@ describe('session-replay-pipeline', () => {messages.push(createMessage(0, i))}- const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)const recorded = recordedSessionIds()expect(recorded).toHaveLength(500)@@ -822,7 +800,6 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})@@ -832,7 +809,7 @@ describe('session-replay-pipeline', () => {createMessage(0, 3, 'session-3', { token: 'valid-token' }),]- const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1', 'session-3'])// The invalid-team message (offset 2) isn't recorded, but its offset is still tracked.@@ -852,14 +829,13 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})// Explicitly pass empty headers (no token)const messages = [createMessage(0, 1, 'session-1', {})]- const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)// Message is dropped by team filter due to missing token — not recorded, offset still tracked.expect(recordedSessionIds()).toEqual([])@@ -879,13 +855,12 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})const messages = [createMessage(0, 1, 'session-1', { token: 'test-token', lib_version: '1.74.0' })]- await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1'])expect(outputs.queueMessages).toHaveBeenCalledTimes(1)@@ -923,13 +898,12 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})const messages = [createMessage(0, 1, 'session-1', { token: 'test-token', lib_version: '1.75.0' })]- await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1'])expect(outputs.queueMessages).not.toHaveBeenCalled()@@ -948,13 +922,12 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})const messages = [createMessage(0, 1, 'session-1', { token: 'test-token' })]- await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)expect(recordedSessionIds()).toEqual(['session-1'])expect(outputs.queueMessages).not.toHaveBeenCalled()@@ -973,14 +946,13 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})// Create a message with timestamps 10 days old (threshold is 7 days)const messages = [createMessageWithOldTimestamps(0, 1, 'session-1', 10, { token: 'test-token' })]- const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)// Message is dropped (not recorded) but its offset is tracked and a warning is sent.expect(recordedSessionIds()).toEqual([])@@ -1014,18 +986,14 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})const messages = [createMessage(0, 1, 'session-1')]- await runSessionReplayPipeline(pipeline, messages, promiseScheduler)-- expect(mockSessionBatchManager.getCurrentBatch).toHaveBeenCalled()- const mockBatch = mockSessionBatchManager.getCurrentBatch()- expect(mockBatch.record).toHaveBeenCalledTimes(1)- expect(mockBatch.record).toHaveBeenCalledWith(+ await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)+ expect(mockBatchRecorder.record).toHaveBeenCalledTimes(1)+ expect(mockBatchRecorder.record).toHaveBeenCalledWith(expect.objectContaining({team: defaultTeam,message: expect.objectContaining({@@ -1050,7 +1018,6 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})@@ -1060,10 +1027,9 @@ describe('session-replay-pipeline', () => {createMessage(0, 3, 'session-3'),]- await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)- const mockBatch = mockSessionBatchManager.getCurrentBatch()- expect(mockBatch.record).toHaveBeenCalledTimes(3)+ expect(mockBatchRecorder.record).toHaveBeenCalledTimes(3)})it('does not record dropped messages to session batch', async () => {@@ -1082,16 +1048,14 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})const messages = [createMessage(0, 1, 'session-1')]- const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)- const mockBatch = mockSessionBatchManager.getCurrentBatch()- expect(mockBatch.record).not.toHaveBeenCalled()+ expect(mockBatchRecorder.record).not.toHaveBeenCalled()// Dropped, but its offset is still tracked so the partition commits past it.expect(offsets).toEqual(new Map([[0, 1]]))})@@ -1113,16 +1077,14 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})const messages = [createMessage(0, 1, 'session-1', { token: 'invalid-token' })]- const offsets = await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)- const mockBatch = mockSessionBatchManager.getCurrentBatch()- expect(mockBatch.record).not.toHaveBeenCalled()+ expect(mockBatchRecorder.record).not.toHaveBeenCalled()// Dropped, but its offset is still tracked so the partition commits past it.expect(offsets).toEqual(new Map([[0, 1]]))})@@ -1140,13 +1102,12 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})const messages = [createMessage(0, 1, 'session-1', { token: 'test-token' })]- await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)// Verify parse time metric was registered and recordedconst parseTimeRecorder = topHog.sumRecorders.get('parse_time_ms_by_session_id')@@ -1171,13 +1132,12 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})const messages = [createMessage(0, 1, 'session-1', { token: 'test-token' })]- await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)// Verify message size metric was registered and recordedconst messageSizeRecorder = topHog.sumRecorders.get('message_size_by_session_id')@@ -1202,13 +1162,12 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})const messages = [createMessage(0, 1, 'session-1', { token: 'test-token' })]- await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)// Verify consume time metric was registered and recordedconst consumeTimeRecorder = topHog.sumRecorders.get('consume_time_ms_by_session_id')@@ -1233,7 +1192,6 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})@@ -1243,7 +1201,7 @@ describe('session-replay-pipeline', () => {createMessage(0, 3, 'session-3', { token: 'token-1' }),]- await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)// Verify all three messages were recorded for each metricconst parseTimeRecorder = topHog.sumRecorders.get('parse_time_ms_by_session_id')@@ -1285,13 +1243,12 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})const messages = [createMessage(0, 1, 'session-1')]- await runSessionReplayPipeline(pipeline, messages, promiseScheduler)+ await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)// Metrics should not be recorded for dropped messages since they never reach the stepsconst parseTimeRecorder = topHog.sumRecorders.get('parse_time_ms_by_session_id')@@ -1336,7 +1293,6 @@ describe('session-replay-pipeline', () => {keyStore,sessionKeyResolutionMaxConcurrency: 20,topHog,- sessionBatchManager: mockSessionBatchManager,isDebugLoggingEnabled,})@@ -1353,7 +1309,7 @@ describe('session-replay-pipeline', () => {size: 100,}- await runSessionReplayPipeline(pipeline, [messageWithoutToken], promiseScheduler)+ await runSessionReplayPipeline(pipeline, [messageWithoutToken], mockBatchRecorder, promiseScheduler)// The parsed message should have token from Kafka headersconst messageSizeRecorder = topHog.sumRecorders.get('message_size_by_session_id')diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.tsindex 97bd9b959bf0..dfa5ae635158 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts@@ -13,7 +13,7 @@ import { createBatch } from '~/ingestion/framework/helpers'import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'import { ok } from '~/ingestion/framework/results'import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'-import { SessionBatchManager } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-manager'+import { 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'@@ -29,13 +29,12 @@ import { createRecordSessionEventStep } from './record-session-event-step'import { SessionBatchContext } from './session-batch-context'import { createMarkSeenStep } from './session-batch-mark-seen-step'import { createResolveRetentionStep } from './session-batch-resolve-retention-step'-import { createAttachSessionBatchStep } from './session-batch-step'import { createTrackAndGateStep } from './session-batch-track-and-gate-step'import { createResolveKeyStep } from './session-resolve-key-step'import { createTeamFilterStep } from './team-filter-step'import { createValidateSessionReplayHeadersStep } from './validate-headers-step'-export interface SessionReplayPipelineInput {+export interface SessionReplayPipelineInput extends SessionBatchContext {message: Message}@@ -45,15 +44,16 @@ export interface SessionReplayPipelineOutput {}/**- * The session replay pipeline: a batching pipeline whose beforeBatch tags the current session batch- * recorder onto every element ({@link SessionBatchContext}), so the steps fold into the recorder- * they were fed with rather than reaching into shared batch state.+ * The session replay pipeline: a batching pipeline whose input elements each carry the session batch+ * recorder they fold into ({@link SessionBatchContext}). The layer above (the consumer, later the+ * accumulating pipeline) owns the recorder and stamps it on the messages it feeds, so the steps stay+ * decoupled from batch creation and flushing.*/export type SessionReplayPipeline = BatchingPipeline<SessionReplayPipelineInput,SessionReplayPipelineOutput,MessageContext,- SessionBatchContext,+ Record<never, object>,MessageContext & BatchingContext,OverflowOutput>@@ -76,8 +76,6 @@ export interface SessionReplayPipelineConfig {sessionKeyResolutionMaxConcurrency: number/** TopHog registry for tracking metrics. */topHog: TopHogRegistry- /** Session batch manager for recording sessions. */- sessionBatchManager: SessionBatchManager/** Debug logging matcher for partition-based debugging. */isDebugLoggingEnabled: ValueMatcher<number>}@@ -85,8 +83,8 @@ export interface SessionReplayPipelineConfig {/*** Creates the session replay pipeline.*- * Each feed() is one batch: the beforeBatch hook tags the manager's current recorder onto every- * element, and the per-message sub-pipeline processes messages through these phases:+ * Each feed() is one batch: every element already carries the recorder it folds into (stamped by the+ * layer above), and the per-message sub-pipeline processes messages through these phases:* 1. Restrictions - Parse headers and apply event ingestion restrictions (drop/overflow)* 2. Team Filter - Validate team ownership and enrich with team context* 3. Parse - Parse Kafka messages into structured session recording data (inside teamAware for warning handling)@@ -106,7 +104,6 @@ export function createSessionReplayPipeline(config: SessionReplayPipelineConfig)keyStore,sessionKeyResolutionMaxConcurrency,topHog,- sessionBatchManager,isDebugLoggingEnabled,} = config@@ -121,11 +118,14 @@ export function createSessionReplayPipeline(config: SessionReplayPipelineConfig)SessionReplayPipelineInput,SessionReplayPipelineOutput,MessageContext,- SessionBatchContext,+ Record<never, object>,MessageContext,OverflowOutput>(- (beforeBatch) => beforeBatch.pipe(createAttachSessionBatchStep(sessionBatchManager)),+ (beforeBatch) =>+ beforeBatch.pipe(function passThroughBeforeBatch(input) {+ return Promise.resolve(ok(input))+ }),(batch) =>batch.messageAware((b) =>@@ -238,8 +238,9 @@ export function createSessionReplayPipeline(config: SessionReplayPipelineConfig)afterBatch.pipe(function passThroughAfterBatch(input) {return Promise.resolve(ok(input))}),- // One batch in flight at a time (also the framework default): each feed tags the manager's- // current recorder, so a concurrent batch could span a flush and record into a stale recorder.+ // One batch in flight at a time (also the framework default): a feed's elements carry the+ // recorder current when it was fed, so a concurrent batch could span a flush and record into a+ // stale recorder.{ concurrentBatches: 1 })}@@ -265,6 +266,7 @@ export function createSessionReplayPipeline(config: SessionReplayPipelineConfig)export async function runSessionReplayPipeline(pipeline: SessionReplayPipeline,messages: Message[],+ sessionBatchRecorder: SessionBatchRecorder,promiseScheduler: PromiseScheduler): Promise<Map<number, number>> {const maxOffsetByPartition = new Map<number, number>()@@ -272,7 +274,9 @@ export async function runSessionReplayPipeline(return maxOffsetByPartition}- const batch = createBatch(messages.map((message) => ({ message })))+ // Stamp the caller's current recorder onto every message, so the record step folds into the batch+ // the layer above owns for this cycle.+ const batch = createBatch(messages.map((message) => ({ message, sessionBatchRecorder })))// The consumer drains each batch fully before feeding the next and the hooks always succeed,// so a rejected feed can only be a framework invariant violation.const feedResult = await pipeline.feed(batch)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.tsindex 1b13a3dce324..abe5130b1a9e 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@@ -5,7 +5,7 @@ import { createMockEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/import { RecordingEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/types'import { SessionBatchFileStorage, SessionBatchFileWriter } from './session-batch-file-storage'-import { SessionBatchManager } from './session-batch-manager'+import { SessionBatchManager, SessionBatchManagerConfig } from './session-batch-manager'import { SessionBatchRecorder } from './session-batch-recorder'import { SessionConsoleLogStore } from './session-console-log-store'@@ -14,7 +14,6 @@ jest.mock('./session-batch-recorder')describe('SessionBatchManager', () => {let manager: SessionBatchManager- let currentBatch: jest.Mocked<SessionBatchRecorder>let mockOffsetManager: jest.Mocked<KafkaOffsetManager>let mockFileStorage: jest.Mocked<SessionBatchFileStorage>let mockWriter: jest.Mocked<SessionBatchFileWriter>@@ -30,19 +29,27 @@ describe('SessionBatchManager', () => {get size() {return 0},- discardPartition: jest.fn(),}) as unknown as jest.Mocked<SessionBatchRecorder>+ const config = (overrides: Partial<SessionBatchManagerConfig> = {}): SessionBatchManagerConfig => ({+ maxBatchSizeBytes: 100,+ maxBatchAgeMs: 1000,+ maxEventsPerSessionPerBatch: Number.MAX_SAFE_INTEGER,+ offsetManager: mockOffsetManager,+ fileStorage: mockFileStorage,+ metadataStore: mockMetadataStore,+ consoleLogStore: mockConsoleLogStore,+ featureStore: mockFeatureStore,+ encryptor: mockEncryptor,+ ...overrides,+ })+beforeEach(() => {- jest.mocked(SessionBatchRecorder).mockImplementation(() => {- currentBatch = createMockBatch()- return currentBatch- })+ jest.mocked(SessionBatchRecorder).mockImplementation(() => createMockBatch())mockOffsetManager = {commit: jest.fn().mockResolvedValue(undefined),trackOffset: jest.fn(),- discardPartition: jest.fn(),} as unknown as jest.Mocked<KafkaOffsetManager>mockWriter = {@@ -68,118 +75,16 @@ describe('SessionBatchManager', () => {mockEncryptor = createMockEncryptor()- manager = new SessionBatchManager({- maxBatchSizeBytes: 100,- maxBatchAgeMs: 1000,- maxEventsPerSessionPerBatch: Number.MAX_SAFE_INTEGER,- offsetManager: mockOffsetManager,- fileStorage: mockFileStorage,- metadataStore: mockMetadataStore,- consoleLogStore: mockConsoleLogStore,- featureStore: mockFeatureStore,- encryptor: mockEncryptor,- })+ manager = new SessionBatchManager(config())})afterEach(() => {jest.clearAllMocks()})- it('should create new batch with correct params on flush', async () => {- const firstBatch = manager.getCurrentBatch()- await manager.flush()-- expect(firstBatch.flush).toHaveBeenCalled()- expect(SessionBatchRecorder).toHaveBeenCalledWith(- mockOffsetManager,- mockFileStorage,- mockMetadataStore,- mockConsoleLogStore,- mockFeatureStore,- mockEncryptor,- Number.MAX_SAFE_INTEGER,- 100- )-- const secondBatch = manager.getCurrentBatch()- expect(secondBatch).not.toBe(firstBatch)- expect(secondBatch.size).toBe(0)- })-- describe('size-based flushing', () => {- it('should indicate flush needed when buffer is full', () => {- jest.spyOn(currentBatch, 'size', 'get').mockReturnValue(150)- expect(manager.shouldFlush()).toBe(true)- })-- it('should not indicate flush needed when buffer is under limit', () => {- jest.spyOn(currentBatch, 'size', 'get').mockReturnValue(50)- expect(manager.shouldFlush()).toBe(false)- })- })-- describe('time-based flushing', () => {- beforeEach(() => {- jest.useFakeTimers()- })-- afterEach(() => {- jest.useRealTimers()- })-- it('should not indicate flush needed when buffer is under limit and timeout not reached', () => {- jest.spyOn(currentBatch, 'size', 'get').mockReturnValue(50)- jest.advanceTimersByTime(500)- expect(manager.shouldFlush()).toBe(false)- })-- it('should indicate flush needed when timeout is reached', () => {- jest.spyOn(currentBatch, 'size', 'get').mockReturnValue(50)- jest.advanceTimersByTime(1500)- expect(manager.shouldFlush()).toBe(true)- })-- it('should not indicate flush needed immediately after flushing', async () => {- jest.spyOn(currentBatch, 'size', 'get').mockReturnValue(50)- jest.advanceTimersByTime(1500)- expect(manager.shouldFlush()).toBe(true)-- await manager.flush()- expect(manager.shouldFlush()).toBe(false)- })- })-- describe('partition handling', () => {- it('should discard partitions on current batch', () => {- const batch = manager.getCurrentBatch()- manager.discardPartitions([1, 2])-- expect(batch.discardPartition).toHaveBeenCalledWith(1)- expect(batch.discardPartition).toHaveBeenCalledWith(2)- expect(batch.discardPartition).toHaveBeenCalledTimes(2)- })-- it('should handle empty partition array', () => {- const batch = manager.getCurrentBatch()- manager.discardPartitions([])- expect(batch.discardPartition).not.toHaveBeenCalled()- })- })-- describe('rate limiting config', () => {- it('should pass maxEventsPerSessionPerBatch to new batches', () => {- manager = new SessionBatchManager({- maxBatchSizeBytes: 100,- maxBatchAgeMs: 1000,- maxEventsPerSessionPerBatch: 500,- offsetManager: mockOffsetManager,- fileStorage: mockFileStorage,- metadataStore: mockMetadataStore,- consoleLogStore: mockConsoleLogStore,- featureStore: mockFeatureStore,- encryptor: mockEncryptor,- })-+ describe('createBatch', () => {+ it('mints a recorder with the configured collaborators', () => {+ manager.createBatch()expect(SessionBatchRecorder).toHaveBeenCalledWith(mockOffsetManager,mockFileStorage,@@ -187,86 +92,74 @@ describe('SessionBatchManager', () => {mockConsoleLogStore,mockFeatureStore,mockEncryptor,- 500,+ Number.MAX_SAFE_INTEGER,100)})- it('should pass maxEventsPerSessionPerBatch to batches created after flush', async () => {- manager = new SessionBatchManager({- maxBatchSizeBytes: 100,- maxBatchAgeMs: 1000,- maxEventsPerSessionPerBatch: 250,- offsetManager: mockOffsetManager,- fileStorage: mockFileStorage,- metadataStore: mockMetadataStore,- consoleLogStore: mockConsoleLogStore,- featureStore: mockFeatureStore,- encryptor: mockEncryptor,- })+ it('returns a fresh recorder on each call', () => {+ const first = manager.createBatch()+ const second = manager.createBatch()+ expect(second).not.toBe(first)+ })- await manager.flush()+ // The rate limiter is per-batch, so the configured cap must reach every minted recorder.+ it.each([0, 250, 500, Number.MAX_SAFE_INTEGER])(+ 'passes maxEventsPerSessionPerBatch=%p to minted recorders',+ (maxEventsPerSessionPerBatch) => {+ manager = new SessionBatchManager(config({ maxEventsPerSessionPerBatch }))+ manager.createBatch()+ expect(SessionBatchRecorder).toHaveBeenLastCalledWith(+ mockOffsetManager,+ mockFileStorage,+ mockMetadataStore,+ mockConsoleLogStore,+ mockFeatureStore,+ mockEncryptor,+ maxEventsPerSessionPerBatch,+ 100+ )+ }+ )+ })- expect(SessionBatchRecorder).toHaveBeenLastCalledWith(- mockOffsetManager,- mockFileStorage,- mockMetadataStore,- mockConsoleLogStore,- mockFeatureStore,- mockEncryptor,- 250,- 100- )+ describe('shouldFlush', () => {+ it('flushes when the batch is at or over the size limit', () => {+ const batch = manager.createBatch()+ jest.spyOn(batch, 'size', 'get').mockReturnValue(150)+ expect(manager.shouldFlush(batch, Date.now())).toBe(true)})- it('should handle maxEventsPerSessionPerBatch = 0', () => {- manager = new SessionBatchManager({- maxBatchSizeBytes: 100,- maxBatchAgeMs: 1000,- maxEventsPerSessionPerBatch: 0,- offsetManager: mockOffsetManager,- fileStorage: mockFileStorage,- metadataStore: mockMetadataStore,- consoleLogStore: mockConsoleLogStore,- featureStore: mockFeatureStore,- encryptor: mockEncryptor,+ it('does not flush when the batch is under the size limit', () => {+ const batch = manager.createBatch()+ jest.spyOn(batch, 'size', 'get').mockReturnValue(50)+ expect(manager.shouldFlush(batch, Date.now())).toBe(false)+ })++ describe('time-based', () => {+ beforeEach(() => {+ jest.useFakeTimers()})- expect(SessionBatchRecorder).toHaveBeenCalledWith(- mockOffsetManager,- mockFileStorage,- mockMetadataStore,- mockConsoleLogStore,- mockFeatureStore,- mockEncryptor,- 0,- 100- )- })+ afterEach(() => {+ jest.useRealTimers()+ })- it('should handle maxEventsPerSessionPerBatch = MAX_SAFE_INTEGER', () => {- manager = new SessionBatchManager({- maxBatchSizeBytes: 100,- maxBatchAgeMs: 1000,- maxEventsPerSessionPerBatch: Number.MAX_SAFE_INTEGER,- offsetManager: mockOffsetManager,- fileStorage: mockFileStorage,- metadataStore: mockMetadataStore,- consoleLogStore: mockConsoleLogStore,- featureStore: mockFeatureStore,- encryptor: mockEncryptor,+ it('does not flush when under the size limit and the age timeout is not reached', () => {+ const batch = manager.createBatch()+ jest.spyOn(batch, 'size', 'get').mockReturnValue(50)+ const lastFlushTime = Date.now()+ jest.advanceTimersByTime(500)+ expect(manager.shouldFlush(batch, lastFlushTime)).toBe(false)})- expect(SessionBatchRecorder).toHaveBeenCalledWith(- mockOffsetManager,- mockFileStorage,- mockMetadataStore,- mockConsoleLogStore,- mockFeatureStore,- mockEncryptor,- Number.MAX_SAFE_INTEGER,- 100- )+ it('flushes when the age timeout is reached', () => {+ const batch = manager.createBatch()+ jest.spyOn(batch, 'size', 'get').mockReturnValue(50)+ const lastFlushTime = Date.now()+ jest.advanceTimersByTime(1500)+ expect(manager.shouldFlush(batch, lastFlushTime)).toBe(true)+ })})})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.tsindex 357db7d363c7..1cd60a8b4e76 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.ts@@ -1,4 +1,3 @@-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'@@ -32,15 +31,13 @@ export interface SessionBatchManagerConfig {}/**- * Coordinates the creation and flushing of session batches+ * Creates session batches and decides when a batch is due to flush.*- * The manager ensures there is always one active batch for recording events.- * It handles:- * - Providing the current batch to the consumer- * - Replacing flushed batches with new ones- * - Providing hints for when to flush the current batch+ * Holds no batch state of its own: the layer above the record pipeline owns the current accumulator,+ * threads it back into {@link shouldFlush}, and flushes it directly. This keeps the accumulator's+ * lifetime with its owner, ready to move into the accumulating pipeline.*- * Each flush creates a new session batch file:+ * Each flushed batch is one session batch file; the owner mints the next batch with {@link createBatch}:* ```* Session Batch File 1 (flushed)* ├── Compressed Session Recording Block 1@@ -57,7 +54,7 @@ export interface SessionBatchManagerConfig {* │ └── ...* └── ...*- * Session Batch File 3 (current, returned to consumer)+ * Session Batch File 3 (current, owned by the caller)* ├── Compressed Session Recording Block 1* │ └── JSONL Session Recording Block* │ ├── [windowId, event1]@@ -66,7 +63,6 @@ export interface SessionBatchManagerConfig {* ```*/export class SessionBatchManager {- private currentBatch: SessionBatchRecorderprivate readonly maxBatchSizeBytes: numberprivate readonly maxBatchAgeMs: numberprivate readonly maxEventsPerSessionPerBatch: number@@ -76,7 +72,6 @@ export class SessionBatchManager {private readonly metadataStore: SessionMetadataSinkprivate readonly consoleLogStore: SessionConsoleLogStoreprivate readonly featureStore: SessionFeatureStore- private lastFlushTime: numberprivate readonly encryptor: RecordingEncryptorconstructor(config: SessionBatchManagerConfig) {@@ -90,8 +85,14 @@ export class SessionBatchManager {this.consoleLogStore = config.consoleLogStorethis.featureStore = config.featureStorethis.encryptor = config.encryptor+ }- this.currentBatch = new SessionBatchRecorder(+ /**+ * Mints a fresh, empty batch. The caller owns the returned recorder for one accumulation cycle and+ * flushes it when due.+ */+ public createBatch(): SessionBatchRecorder {+ return new SessionBatchRecorder(this.offsetManager,this.fileStorage,this.metadataStore,@@ -101,14 +102,6 @@ export class SessionBatchManager {this.maxEventsPerSessionPerBatch,this.featuresRolloutPercentage)- this.lastFlushTime = Date.now()- }-- /**- * Returns the current batch- */- public getCurrentBatch(): SessionBatchRecorder {- return this.currentBatch}/**@@ -126,39 +119,14 @@ export class SessionBatchManager {}/**- * Flushes the current batch and replaces it with a new one- */- public async flush(): Promise<void> {- logger.info('🔁', 'session_batch_manager_flushing', { batchSize: this.currentBatch.size })- await this.currentBatch.flush()- this.currentBatch = new SessionBatchRecorder(- this.offsetManager,- this.fileStorage,- this.metadataStore,- this.consoleLogStore,- this.featureStore,- this.encryptor,- this.maxEventsPerSessionPerBatch,- this.featuresRolloutPercentage- )- this.lastFlushTime = Date.now()- }-- /**- * Checks if the current batch should be flushed based on:+ * Whether the given batch is due to flush, by size (bytes accumulated) or age (since it was minted):* - Size of the batch exceeding maxBatchSizeBytes* - Age of the batch exceeding maxBatchAgeMs+ *+ * @param lastFlushTime - When the current accumulation cycle started (the last flush, or startup).*/- public shouldFlush(): boolean {- const batchSize = this.currentBatch.size- const batchAge = Date.now() - this.lastFlushTime- return batchSize >= this.maxBatchSizeBytes || batchAge >= this.maxBatchAgeMs- }-- public discardPartitions(partitions: number[]): void {- logger.info('🔁', 'session_batch_manager_discarding_partitions', { partitions })- for (const partition of partitions) {- this.currentBatch.discardPartition(partition)- }+ public shouldFlush(batch: SessionBatchRecorder, lastFlushTime: number): boolean {+ const batchAge = Date.now() - lastFlushTime+ return batch.size >= this.maxBatchSizeBytes || batchAge >= this.maxBatchAgeMs}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.tsindex b95e97c64d9d..958854b7e72c 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@@ -232,7 +232,6 @@ describe('SessionBatchRecorder', () => {mockOffsetManager = {trackOffset: jest.fn(),- discardPartition: jest.fn(),commit: jest.fn(),} as unknown as jest.Mocked<KafkaOffsetManager>@@ -1222,97 +1221,6 @@ describe('SessionBatchRecorder', () => {expect(mockMetadataStore.storeSessionBlocks).toHaveBeenCalledTimes(1)expect(mockOffsetManager.commit).toHaveBeenCalledTimes(1)})-- it('should not flush discarded partitions', async () => {- const messages = [- createMessage(- 'session1',- [- {- type: EventType.FullSnapshot,- timestamp: 1000,- data: { source: 1 },- },- ],- { partition: 1 }- ),- createMessage(- 'session2',- [- {- type: EventType.IncrementalSnapshot,- timestamp: 2000,- data: { source: 2 },- },- ],- { partition: 2 }- ),- ]-- for (const message of messages) {- await record(message)- }- recorder.discardPartition(1)- await recorder.flush()-- const writtenData = captureWrittenData(mockWriter.writeSession as jest.Mock)- const lines = parseLines(writtenData[0])- // Should only contain message from partition 2- expect(lines).toEqual([['window1', messages[1].message.eventsByWindowId.window1[0]]])- })-- it('should correctly update size when discarding partitions', async () => {- const message1 = createMessage(- 'session1',- [- {- type: EventType.FullSnapshot,- timestamp: 1000,- data: { source: 1 },- },- ],- { partition: 1 }- )- const message2 = createMessage(- 'session2',- [- {- type: EventType.IncrementalSnapshot,- timestamp: 2000,- data: { source: 2 },- },- ],- { partition: 2 }- )-- const size1 = await record(message1)- const size2 = await record(message2)- expect(recorder.size).toBe(size1 + size2)-- recorder.discardPartition(1)- expect(mockOffsetManager.discardPartition).toHaveBeenCalledWith(1)- expect(recorder.size).toBe(size2)-- recorder.discardPartition(2)- expect(mockOffsetManager.discardPartition).toHaveBeenCalledWith(2)- expect(recorder.size).toBe(0)- })-- it('should handle discarding non-existent partitions', async () => {- const message = createMessage('session1', [- {- type: EventType.FullSnapshot,- timestamp: 1000,- data: { source: 1 },- },- ])-- const bytesWritten = await record(message)- expect(recorder.size).toBe(bytesWritten)-- recorder.discardPartition(999)- expect(recorder.size).toBe(bytesWritten)- })})describe('metrics', () => {@@ -1359,45 +1267,6 @@ describe('SessionBatchRecorder', () => {expect(SessionBatchMetrics.incrementEventsFlushed).toHaveBeenCalledTimes(0)})- it('should not count events from discarded partitions', async () => {- const messages = [- createMessage(- 'session1',- [- {- type: EventType.FullSnapshot,- timestamp: 1000,- data: { source: 1 },- },- ],- { partition: 1 }- ),- createMessage(- 'session2',- [- {- type: EventType.IncrementalSnapshot,- timestamp: 2000,- data: { source: 2 },- },- ],- { partition: 2 }- ),- ]-- for (const message of messages) {- await record(message)- }- recorder.discardPartition(1)- await recorder.flush()-- expect(SessionBatchMetrics.incrementBatchesFlushed).toHaveBeenCalledTimes(1)- expect(SessionBatchMetrics.incrementSessionsFlushed).toHaveBeenCalledTimes(1)- expect(SessionBatchMetrics.incrementEventsFlushed).toHaveBeenCalledTimes(1)- expect(SessionBatchMetrics.incrementSessionsFlushed).toHaveBeenLastCalledWith(1) // Only session from partition 2- expect(SessionBatchMetrics.incrementEventsFlushed).toHaveBeenLastCalledWith(1) // Only event from partition 2- })-it('should not count sessions again on subsequent flushes', async () => {const messages = [createMessage('session1', [@@ -1850,36 +1719,6 @@ describe('SessionBatchRecorder', () => {expect(bytesWritten2).toBeGreaterThan(0)})- it('should clean up rate limiter state when partition is discarded', async () => {- recorder = new SessionBatchRecorder(- mockOffsetManager,- mockStorage,- mockMetadataStore,- mockConsoleLogStore,- mockFeatureStore,- mockEncryptor,- 1- )-- const message1 = createMessage('session1', [{ type: EventType.Meta, timestamp: 1000, data: {} }], {- partition: 1,- })- const message2 = createMessage('session1', [{ type: EventType.Meta, timestamp: 2000, data: {} }], {- partition: 1,- })-- await record(message1)- await record(message2)-- recorder.discardPartition(1)-- const message3 = createMessage('session1', [{ type: EventType.Meta, timestamp: 3000, data: {} }], {- partition: 2,- })- const bytesWritten = await record(message3)- expect(bytesWritten).toBeGreaterThan(0)- })-it('should handle rate limiting with different team IDs', async () => {recorder = new SessionBatchRecorder(mockOffsetManager,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.tsindex 3d1da7132452..64c5a80134bb 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts@@ -29,8 +29,6 @@ interface SessionBatchEntry {featureRecorder: SessionFeatureRecordersessionKey: SessionKeyretentionPeriod: RetentionPeriod- /** Kafka partition the session is pinned to; used to drop the session on partition revocation. */- partition: number}/**@@ -78,10 +76,8 @@ interface SessionBatchEntry {*/export class SessionBatchRecorder {// Sessions are keyed by (teamId, sessionId) across all partitions. A session is pinned to one- // partition, so the key is unique; each entry carries its partition for revocation. Not readonly:- // discard and flush swap it for a fresh map.+ // partition, so the key is unique. Not readonly: flush swaps it for a fresh map.private sessions = new SessionMap<SessionBatchEntry>()- private readonly partitionSizes = new Map<number, number>()private _size: number = 0private readonly batchId: stringprivate readonly rateLimiter: SessionRateLimiter@@ -120,7 +116,7 @@ export class SessionBatchRecorder {const sessionId = message.message.session_idconst teamId = message.team.teamId- const isEventAllowed = this.rateLimiter.handleMessage(teamId, sessionId, partition, message.message)+ const isEventAllowed = this.rateLimiter.handleMessage(teamId, sessionId, message.message)if (!isEventAllowed) {logger.debug('🔁', 'session_batch_recorder_event_rate_limited', {@@ -144,10 +140,6 @@ export class SessionBatchRecorder {return 0}- if (!this.partitionSizes.has(partition)) {- this.partitionSizes.set(partition, 0)- }-const existingBatchState = this.sessions.get(teamId, sessionId)if (existingBatchState) {@@ -187,7 +179,6 @@ export class SessionBatchRecorder {),sessionKey,retentionPeriod,- partition,})}@@ -211,8 +202,6 @@ export class SessionBatchRecorder {}}- const currentPartitionSize = this.partitionSizes.get(partition)!- this.partitionSizes.set(partition, currentPartitionSize + bytesWritten)this._size += bytesWrittenlogger.debug('🔁', 'session_batch_recorder_recorded_message', {@@ -235,35 +224,6 @@ export class SessionBatchRecorder {return this.sessions.get(teamId, sessionId)?.retentionPeriod}- /**- * Discards all sessions for a given partition, so that they are not persisted in this batch- * Used when partitions are revoked during Kafka rebalancing- */- public discardPartition(partition: number): void {- const partitionSize = this.partitionSizes.get(partition)- if (partitionSize !== undefined) {- logger.info('🔁', 'session_batch_recorder_discarding_partition', {- partition,- partitionSize,- })-- this.rateLimiter.discardPartition(partition)-- this._size -= partitionSize- this.partitionSizes.delete(partition)- // Revocation is rare, so rebuilding the session map without the partition is fine — it- // keeps the per-message lookups a single, flat map access.- const remaining = new SessionMap<SessionBatchEntry>()- for (const entry of this.sessions.values()) {- if (entry.partition !== partition) {- remaining.set(entry.sessionBlockRecorder.teamId, entry.sessionBlockRecorder.sessionId, entry)- }- }- this.sessions = remaining- this.offsetManager.discardPartition(partition)- }- }-/*** Flushes the session recordings to storage and commits Kafka offsets*@@ -279,7 +239,6 @@ export class SessionBatchRecorder {// recorded then dropped (e.g. rate limited), leaving batch state to reset.if (this.sessions.size === 0) {await this.offsetManager.commit()- this.partitionSizes.clear()this._size = 0this.rateLimiter.clear()logger.info('🔁', 'session_batch_recorder_flushed_no_sessions')@@ -402,9 +361,8 @@ export class SessionBatchRecorder {}}- // Clear sessions, partition sizes, total size, and rate limiter state after successful flush+ // Clear sessions, total size, and rate limiter state after successful flushthis.sessions = new SessionMap()- this.partitionSizes.clear()this._size = 0this.rateLimiter.clear()diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.test.tsindex 50c7a9b31662..77848c7702cf 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.test.ts@@ -26,9 +26,9 @@ describe('SessionRateLimiter', () => {const limiter = new SessionRateLimiter(3)const session: [number, string] = [123, 'session456']- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(true)expect(limiter.getEventCount(...session)).toBe(3)})@@ -48,19 +48,19 @@ describe('SessionRateLimiter', () => {},} as any as ParsedMessageData- expect(limiter.handleMessage(...session, 1, preSerialized)).toBe(true)+ expect(limiter.handleMessage(...session, preSerialized)).toBe(true)expect(limiter.getEventCount(...session)).toBe(2)- expect(limiter.handleMessage(...session, 1, preSerialized)).toBe(false)+ expect(limiter.handleMessage(...session, preSerialized)).toBe(false)})it('should block messages after limit is exceeded', () => {const limiter = new SessionRateLimiter(2)const session: [number, string] = [123, 'session456']- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)})it('should track multiple sessions independently', () => {@@ -68,23 +68,23 @@ describe('SessionRateLimiter', () => {const session1: [number, string] = [123, 'session1']const session2: [number, string] = [123, 'session2']- expect(limiter.handleMessage(...session1, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(...session2, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(...session1, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(...session2, 1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session2, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session2, createMessage(1))).toBe(true)- expect(limiter.handleMessage(...session1, 1, createMessage(1))).toBe(false)- expect(limiter.handleMessage(...session2, 1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session2, createMessage(1))).toBe(false)})it('should continue blocking after limit is hit', () => {const limiter = new SessionRateLimiter(1)const session: [number, string] = [123, 'session456']- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)})it('should count events across multiple windows', () => {@@ -98,7 +98,7 @@ describe('SessionRateLimiter', () => {},} as any- expect(limiter.handleMessage(...session, 1, messageWithMultipleWindows)).toBe(true)+ expect(limiter.handleMessage(...session, messageWithMultipleWindows)).toBe(true)expect(limiter.getEventCount(...session)).toBe(4)})@@ -106,16 +106,16 @@ describe('SessionRateLimiter', () => {const limiter = new SessionRateLimiter(10)const session: [number, string] = [123, 'session456']- expect(limiter.handleMessage(...session, 1, createMessage(3))).toBe(true)+ expect(limiter.handleMessage(...session, createMessage(3))).toBe(true)expect(limiter.getEventCount(...session)).toBe(3)- expect(limiter.handleMessage(...session, 1, createMessage(5))).toBe(true)+ expect(limiter.handleMessage(...session, createMessage(5))).toBe(true)expect(limiter.getEventCount(...session)).toBe(8)- expect(limiter.handleMessage(...session, 1, createMessage(2))).toBe(true)+ expect(limiter.handleMessage(...session, createMessage(2))).toBe(true)expect(limiter.getEventCount(...session)).toBe(10)- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)expect(limiter.getEventCount(...session)).toBe(11)})@@ -124,7 +124,7 @@ describe('SessionRateLimiter', () => {const session: [number, string] = [123, 'session456']for (let i = 0; i < 1000; i++) {- expect(limiter.handleMessage(...session, 1, createMessage(1000))).toBe(true)+ expect(limiter.handleMessage(...session, createMessage(1000))).toBe(true)}expect(limiter.getEventCount(...session)).toBe(1000000)})@@ -140,10 +140,10 @@ describe('SessionRateLimiter', () => {const limiter = new SessionRateLimiter(10)const session: [number, string] = [123, 'session456']- limiter.handleMessage(...session, 1, createMessage(1))+ limiter.handleMessage(...session, createMessage(1))expect(limiter.getEventCount(...session)).toBe(1)- limiter.handleMessage(...session, 1, createMessage(2))+ limiter.handleMessage(...session, createMessage(2))expect(limiter.getEventCount(...session)).toBe(3)})@@ -151,56 +151,24 @@ describe('SessionRateLimiter', () => {const limiter = new SessionRateLimiter(2)const session: [number, string] = [123, 'session456']- limiter.handleMessage(...session, 1, createMessage(1))- limiter.handleMessage(...session, 1, createMessage(1))+ limiter.handleMessage(...session, createMessage(1))+ limiter.handleMessage(...session, createMessage(1))expect(limiter.getEventCount(...session)).toBe(2)- limiter.handleMessage(...session, 1, createMessage(1))- limiter.handleMessage(...session, 1, createMessage(1))+ limiter.handleMessage(...session, createMessage(1))+ limiter.handleMessage(...session, createMessage(1))expect(limiter.getEventCount(...session)).toBe(4)})})- describe('removeSession', () => {- it('should remove session tracking', () => {- const limiter = new SessionRateLimiter(10)- const session: [number, string] = [123, 'session456']-- limiter.handleMessage(...session, 1, createMessage(2))- expect(limiter.getEventCount(...session)).toBe(2)-- limiter.removeSession(...session)- expect(limiter.getEventCount(...session)).toBe(0)-- limiter.handleMessage(...session, 1, createMessage(1))- expect(limiter.getEventCount(...session)).toBe(1)- })-- it('should remove limited session status', () => {- const limiter = new SessionRateLimiter(1)- const session: [number, string] = [123, 'session456']-- limiter.handleMessage(...session, 1, createMessage(1))- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)-- limiter.removeSession(...session)- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)- })-- it('should handle removing non-existent session', () => {- const limiter = new SessionRateLimiter(10)- expect(() => limiter.removeSession(1, 'nonexistent')).not.toThrow()- })- })-describe('clear', () => {it('should clear all sessions', () => {const limiter = new SessionRateLimiter(10)const session1: [number, string] = [123, 'session1']const session2: [number, string] = [123, 'session2']- limiter.handleMessage(...session1, 1, createMessage(2))- limiter.handleMessage(...session2, 1, createMessage(1))+ limiter.handleMessage(...session1, createMessage(2))+ limiter.handleMessage(...session2, createMessage(1))expect(limiter.getEventCount(...session1)).toBe(2)expect(limiter.getEventCount(...session2)).toBe(1)@@ -215,11 +183,11 @@ describe('SessionRateLimiter', () => {const limiter = new SessionRateLimiter(1)const session: [number, string] = [123, 'session456']- limiter.handleMessage(...session, 1, createMessage(1))- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)+ limiter.handleMessage(...session, createMessage(1))+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)limiter.clear()- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(true)})})@@ -228,7 +196,7 @@ describe('SessionRateLimiter', () => {const limiter = new SessionRateLimiter(0)const session: [number, string] = [123, 'session456']- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)expect(limiter.getEventCount(...session)).toBe(1)})@@ -236,8 +204,8 @@ describe('SessionRateLimiter', () => {const limiter = new SessionRateLimiter(1)const session: [number, string] = [123, 'session456']- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)})it('should handle many concurrent sessions', () => {@@ -246,75 +214,10 @@ describe('SessionRateLimiter', () => {for (const session of sessions) {for (let i = 0; i < 5; i++) {- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(true)+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(true)}- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)+ expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)}})})-- describe('discardPartition', () => {- it('should remove all sessions for a partition', () => {- const limiter = new SessionRateLimiter(10)- const session1: [number, string] = [123, 'session1']- const session2: [number, string] = [123, 'session2']- const session3: [number, string] = [123, 'session3']-- limiter.handleMessage(...session1, 1, createMessage(2))- limiter.handleMessage(...session2, 1, createMessage(1))- limiter.handleMessage(...session3, 2, createMessage(1))-- expect(limiter.getEventCount(...session1)).toBe(2)- expect(limiter.getEventCount(...session2)).toBe(1)- expect(limiter.getEventCount(...session3)).toBe(1)-- limiter.discardPartition(1)-- expect(limiter.getEventCount(...session1)).toBe(0)- expect(limiter.getEventCount(...session2)).toBe(0)- expect(limiter.getEventCount(...session3)).toBe(1)- })-- it('should remove limited session status for partition', () => {- const limiter = new SessionRateLimiter(1)- const session1: [number, string] = [123, 'session1']- const session2: [number, string] = [123, 'session2']-- limiter.handleMessage(...session1, 1, createMessage(1))- limiter.handleMessage(...session1, 1, createMessage(1))- limiter.handleMessage(...session2, 2, createMessage(1))- limiter.handleMessage(...session2, 2, createMessage(1))-- expect(limiter.handleMessage(...session1, 1, createMessage(1))).toBe(false)- expect(limiter.handleMessage(...session2, 2, createMessage(1))).toBe(false)-- limiter.discardPartition(1)-- expect(limiter.handleMessage(...session1, 1, createMessage(1))).toBe(true)- expect(limiter.handleMessage(...session2, 2, createMessage(1))).toBe(false)- })-- it('should handle discarding non-existent partition', () => {- const limiter = new SessionRateLimiter(10)- expect(() => limiter.discardPartition(999)).not.toThrow()- })-- it('should allow session to restart on new partition after discard', () => {- const limiter = new SessionRateLimiter(2)- const session: [number, string] = [123, 'session456']-- limiter.handleMessage(...session, 1, createMessage(1))- limiter.handleMessage(...session, 1, createMessage(1))- limiter.handleMessage(...session, 1, createMessage(1))-- expect(limiter.handleMessage(...session, 1, createMessage(1))).toBe(false)-- limiter.discardPartition(1)-- limiter.handleMessage(...session, 2, createMessage(1))- limiter.handleMessage(...session, 2, createMessage(1))- expect(limiter.getEventCount(...session)).toBe(2)- expect(limiter.handleMessage(...session, 2, createMessage(1))).toBe(false)- })- })})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.tsindex 61fa6f0578b8..c2aeaea7d5f0 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.ts@@ -9,7 +9,6 @@ import { SessionBatchMetrics } from './metrics'export class SessionRateLimiter {private readonly eventCounts = new Map<string, number>()private readonly limitedSessions = new Set<string>()- private readonly sessionPartitions = new Map<string, number>()constructor(private readonly maxEventsPerSession: number = Number.MAX_SAFE_INTEGER) {}@@ -21,7 +20,7 @@ export class SessionRateLimiter {* Handle a message for a session* @returns true if message should be processed, false if rate limited*/- public handleMessage(teamId: number, sessionId: string, partition: number, message: ParsedMessageData): boolean {+ public handleMessage(teamId: number, sessionId: string, message: ParsedMessageData): boolean {const key = SessionRateLimiter.key(teamId, sessionId)// Count total events in the message across all windows@@ -35,10 +34,7 @@ export class SessionRateLimiter {}const newCount = (this.eventCounts.get(key) ?? 0) + eventCount-- // Always increment the count and track partitionthis.eventCounts.set(key, newCount)- this.sessionPartitions.set(key, partition)if (this.limitedSessions.has(key)) {SessionBatchMetrics.incrementEventsRateLimited()@@ -62,40 +58,11 @@ export class SessionRateLimiter {return this.eventCounts.get(SessionRateLimiter.key(teamId, sessionId)) ?? 0}- /**- * Remove tracking for a session (used when partition is discarded)- */- public removeSession(teamId: number, sessionId: string): void {- this.removeByKey(SessionRateLimiter.key(teamId, sessionId))- }-- /**- * Discard all sessions for a given partition- */- public discardPartition(partition: number): void {- const keysToRemove: string[] = []- for (const [key, sessionPartition] of this.sessionPartitions.entries()) {- if (sessionPartition === partition) {- keysToRemove.push(key)- }- }- for (const key of keysToRemove) {- this.removeByKey(key)- }- }-/*** Clear all rate limiting state*/public clear(): void {this.eventCounts.clear()this.limitedSessions.clear()- this.sessionPartitions.clear()- }-- private removeByKey(key: string): void {- this.eventCounts.delete(key)- this.limitedSessions.delete(key)- this.sessionPartitions.delete(key)}}